【问题标题】:Problems with Python's Numpy array dimensionsPython 的 Numpy 数组维度的问题
【发布时间】:2019-01-28 22:48:29
【问题描述】:

我正在努力解决一个我无法上班的问题!我目前正在使用 Tensorflow 并通过 basic tutorials 工作。

正如您在本教程中所见,神经网络模型需要一个 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,追加和转置,但至今无济于事:(非常感谢任何帮助!

【问题讨论】:

    标签: python arrays numpy tensorflow dimension


    【解决方案1】:

    我假设您从文件生成的每个“数组”都是(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的经验,但这是你需要的形状。

    【讨论】:

    • 完美!我知道它必须很简单,但我昨晚做不到......非常感谢,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多