【问题标题】:why is keras saying i only have one label instead of three为什么keras说我只有一个标签而不是三个
【发布时间】:2021-05-29 15:35:31
【问题描述】:

我得到一个错误是 tensorflow/keras 说我只有一个输出,所以我应该在密集层有一个 (1) 而不是 (4),我制作了一组标签

#goes through files and turns images into arrays
#going through each folder
for categories in os.listdir('train'):
    category = str('train/' + folder)
    #going through each file in folder
    for files in os.listdir(category):
        #creates file path
        filePath = category + '/' + files
        image = keras.preprocessing.image.load_img(filePath)
        imageArr = keras.preprocessing.image.img_to_array(image)
        features.append(imageArr)

# makes labels
# iterates over folders
for names in os.listdir('train'):
      label = 0
      #increment as value of current folder
      label += 1
      for files in os.listdir('train/' + names):
          #adds a number per label
          labels.append(label)

features = np.asarray(features)
labels = np.asarray(labels)


model = keras.Sequential()
model.add(Conv2D(30, (20, 20), input_shape=(600, 600, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(4, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

我得到的错误表明,当我知道我有 4 个时,我只有一个输出,因为当我打印“标签”时,我得到一系列从 1 到 4 的数字,是因为它们都在一个数组中吗?感谢您的帮助

错误:

ValueError: logits and labels must have the same shape ((None, 4) vs (None, 1))

【问题讨论】:

标签: python numpy tensorflow keras


【解决方案1】:

您有 1 到 4 个范围内的标签,但每个图像有 1 个标签。您将损失指定为 binary_cross 熵。这意味着您的密集层中应该有 1 个神经元而不是 4 个。此外,您的标签在 1-4 范围内,它们应该在 0-3 范围内,因此在您的代码中 标签应该是

for names in os.listdir('train'):
      label = 0
      #increment as value of current folder      
      for files in os.listdir('train/' + names):
          #adds a number per label
          labels.append(label)
      label += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    相关资源
    最近更新 更多