繁体   English   中英

编译Keras顺序模型的问题

[英]Issues with compiling a Keras sequential model

在编译Keras顺序模型时遇到了以下错误:

ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 45985 arrays: [array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
   ...

这是我用于X_train,y_train,X_test和y_test的代码和数据格式:

print(X_train.shape)

>>(45985, 50, 50, 3)

print(X_test.shape)

>>(22650, 50, 50, 3)

print(y_train[0])

>>array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
model = Sequential()

model.add(Conv2D(64, kernel_size=3, activation="relu", input_shape=(50,50,3)))
model.add(Conv2D(32, kernel_size=3, activation="relu"))
model.add(Flatten())
model.add(Dense(10, activation="softmax"))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3)

您的y_train为numpy数组的列表,它应该是一个具有形状(samples, 10)的单个numpy数组。 您可以使用以下方法进行转换:

y_train = np.array(y_train, dtype=np.float32)

然后,您应该记住对标签进行一次热编码(它们看起来像整数标签):

from keras.utils import to_categorical

y_train = to_categorical(y_train)

作为对另一个答案中提到的标签进行一次热编码的一种替代方法,您可以保持标签不变,即稀疏/整数标签,而可以使用'sparse_categorical_crossentropy'作为损失函数。 这将有助于节省内存,尤其是在您有大量示例和/或类的情况下。 不过,不要忘记,无论如何您都需要将标签转换为numpy数组。

暂无
暂无

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

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