keras顺序模型中的输入形状错误

时间:2019-01-11 09:14:26

标签: python machine-learning neural-network

全部欢迎。试图对付喀拉拉邦。我有几张以.npy格式保存的图像及其标签。

训练模型时出现错误:

  

ValueError:检查输入时出错:预期density_input具有形状(135,240),但数组的形状为(240,3)

这很奇怪,因为提交的图像的形状是:

  

(135,240,3)

我的课程NeuralNetwork:

class NeuralNetwork():
    def __init__(self):

    self.model = keras.models.Sequential()
    self.model.add(keras.layers.Dense(1024, input_shape=(135, 240), activation="relu"))
    self.model.add(keras.layers.Dense(512, activation="relu"))
    self.model.add(keras.layers.Dense(9, activation="softmax"))

    opt = keras.optimizers.Adam()
    self.model.compile(loss="categorical_crossentropy", optimizer=opt,
                  metrics=["accuracy"])

    def FitModel(self, trainX, trainY):
        self.model.fit(trainX, trainY, epochs=30)


    def Predict(self, image):
        predictions = self.model.predict(image)

        choice = np.argmax(predictions[0])
        return choice

主要:

Data_Count = 7990

WIDTH = 240
HEIGHT = 135

nn = NeuralNetwork()

for i in range(1, DataCount+1):

    file_name = 'D:/TrainingData/training_data-{}.npy'.format(i)
    train_data = np.load(file_name)

    image = np.array([i[0] for i in train_data])[0]
    label = np.array([i[1] for i in train_data])[0]

    image = image / 255

    nn.FitModel(image, label)

为什么她只得到(240,3),而不是(135,240)?

提前感谢您的回答!

1 个答案:

答案 0 :(得分:0)

您的致密层输入形状不正确。您的图像的形状为(135, 240, 3),但是您喂入(135,240)意味着您错过了图像通道。此外,在将图像馈送到密集层之前,您忘了将图像展平。这是一些虚拟数据的示例:

import numpy as np
from tensorflow.python import keras

model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(135, 240, 3)))
model.add(keras.layers.Dense(1024, activation="relu"))
model.add(keras.layers.Dense(512, activation="relu"))
model.add(keras.layers.Dense(9, activation="softmax"))

model.compile(loss="categorical_crossentropy", optimizer='adam', metrics=["accuracy"])

# dummy data
images = np.zeros(shape=(7990, 135, 240, 3))
labels = np.zeros(shape=(7990, 9))

# train model
model.fit(x=images, y=labels, batch_size=128)