【问题标题】:I have problem in loading my data set in Tensorflow (python 3.7)我在 Tensorflow (python 3.7) 中加载我的数据集时遇到问题
【发布时间】:2019-06-19 20:26:55
【问题描述】:

我正在尝试将图像数据集加载到 tensorflow 中,但我遇到了正确加载它的问题。实际上,我在 C 盘中有一个名为 PetImages 的文件夹,其中包含两个名为 cat 和 dog 的文件夹。每个文件夹包含更多 12450 张图片,因此总共有 24500 张图片。我正在使用以下代码加载它们:

import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
DATADIR = "C:\Datasets\PetImages"
CATEGORIES = ["Dog","Cat"]
for the category in CATEGORIES:
path = os.path.join(DATADIR, category)

for img in os.listdir(path):
    img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
    plt.imshow(img_array, cmap="gray")
    plt.show()
    break
break

代码的结果看起来非常好,它显示了文件夹的第一张图片。 然后我使用以下代码将整个阵列的形状转换为所需的像素率:

IMG_SIZE=50
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
plt.imshow(new_array, cmap = "gray")
plt.show()

这部分也很好,但是我想混合(洗牌)图像,这样我就可以迷惑系统并以这种方式检查准确性,但问题是它只显示 12450 图像结果在这段代码之后:

training_data = []
def create_training_data():
for category in CATEGORIES:
    path = os.path.join(DATADIR, category)
    class_num = CATEGORIES.index(category)
for img in os.listdir(path):
    try:
        img_array = cv2.imread(os.path.join(path,img), 
cv2.IMREAD_GRAYSCALE)
        new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
        training_data.append([new_array, class_num])
    except Exception as e:
        pass       
create_training_data()
print(len(training_data)

然后使用随机我没有成功从两个文件夹中随机播放图像,它只显示一个文件夹的值。

import random   
random.shuffle(training_data)
for the sample in training_data[:10]:  
print(sample[1])

但我的结果是 1 1 1 1 1 而不是随机生成的 0 1 0 1 0 0 0 1 1 这种风格我的意思是出乎意料的下一个将是 10

您的帮助对我来说很有价值。在此先感谢

【问题讨论】:

    标签: python tensorflow-datasets loaddata


    【解决方案1】:

    在我看来像是一个缩进错误。您的第二个 for 循环位于您的第一个 for 循环之外,这会导致第一个循环完全终止并在进入第二个循环之前将 class_num 设置为 1。你可能想嵌套它们。试试:

    def create_training_data():
        for category in CATEGORIES:
            path = os.path.join(DATADIR, category)
            class_num = CATEGORIES.index(category)
            for img in os.listdir(path):
                try:
                    img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
                    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
                    training_data.append([new_array, class_num])
                except Exception as e:
                    pass       
    create_training_data()
    print(len(training_data)
    

    【讨论】:

      【解决方案2】:

      您可以尝试打乱训练数据的掩码或索引

      import random
      index=[k for k in range(len(training_data))]
      shuffIndex=random.shuffle(index)
      shuffTrainigData=[training_data[val] for val in shuffIndex]
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2020-05-07
        • 1970-01-01
        • 1970-01-01
        • 2023-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-05
        • 1970-01-01
        相关资源
        最近更新 更多