首页 > 解决方案 > Python 的 Numpy 数组维度的问题

问题描述

我正在努力解决一个我无法上班的问题!我目前正在使用 Tensorflow 并完成了基本教程

正如您在本教程中所见,神经网络模型需要一个 train_images Numpy 形状数组,(60000, 28, 28)因为本教程的训练集中有 60,000 张大小为 28x28 的图像。我正在阅读 Flavia 数据集,这是一组树叶图片。训练集由 1588 张图片组成,分辨率为 300x300px。这是我的代码:

for root, dirs, files in os.walk(pathname_data):
for name in files:
    img = keras.preprocessing.image.load_img(os.path.join(root,name), color_mode="grayscale",target_size=(300,300))      #get image in 300x300 grayscale
    array = keras.preprocessing.image.img_to_array(img)                                                                 #convert to numpy array
    array = array.squeeze(axis=2)                                                                                       #convert to 300x300 2d array
    array = array / 255.0                                                                                               #preprocess data
    pathSegments = os.path.normpath(os.path.join(root,name)).split(os.sep)                                              #split path
    if pathSegments[len(pathSegments)-3] == "Train":                                                                    #assign to training- or testSet
        #TODO: how to store the 2x2 arrays ?? 
        #store in training set 
    elif pathSegments[len(pathSegments)-3] == "Test":
        #store in test set 

我现在的问题是,如何存储“数组”以便最终得到一个(1588, 300, 300)可以提供给模型的 - 形 Numpy 数组?我已经尝试过reshape,追加和转置,但还没有成功:(非常感谢任何帮助!

标签: pythonarraysnumpytensorflowdimension

解决方案


我假设您从文件生成的每个“数组”都是一个(300, 300)形状

您可以预先生成数组并使用计数器

all_img = np.empty((1588, 300, 300))
count = 0
for root, dirs, files in os.walk(pathname_data):
    for name in files:
        ...
        all_img[count] = array.copy()
        count += 1
        ...

或者您可以将所有图像附加到列表中并稍后将其更改为数组

all_img = []
for root, dirs, files in os.walk(pathname_data):
    for name in files:
        ...
        all_img.append(array)
        ...
all_img = np.array(all_img)

这两种方法都会给你一个(1588, 300, 300)数组,我没有使用 Tensorflow 的经验,但这是你需要的形状。


推荐阅读