简体   繁体   English

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

[英]Error with input shape in keras Sequential model

All welcome. 大家欢迎。 Trying to deal with keras. 试图对付喀拉拉邦。 I have several images saved in .npy format, as well as their labels. 我有几张以.npy格式保存的图像及其标签。

When training a model, I get an error: 训练模型时,出现错误:

ValueError: Error when checking input: expected dense_input to have shape (135, 240) but got array with shape (240, 3) ValueError:检查输入时出错:预期density_input具有形状(135,240),但数组具有形状(240,3)

Which is very strange, because the shape of the submitted image is: 这很奇怪,因为提交的图像的形状为:

(135, 240, 3) (135,240,3)

My class 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

And main: 主要:

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)

Why she get only (240, 3), instead (135, 240)? 为什么她只得到(240,3),而不是(135,240)?

Thanks in advance for the answer! 预先感谢您的回答!

Your input_shape for dense-layer is not correct. 您的致密层input_shape不正确。 Your images, have shape (135, 240, 3) but you feed (135,240) which means you miss the image channels. 您的图像的形状为(135, 240, 3) (135,240) ,但进给(135,240) ,这意味着您错过了图像通道。 In addition, you forget to Flatten the images before feeding them into dense-layer. 此外,在将图像馈送到密集层之前,您忘了将图像展平。 Here is the example with some dummy data: 这是一些虚拟数据的示例:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM