【问题标题】:Issues with compiling a Keras sequential model编译 Keras 顺序模型的问题
【发布时间】:2019-12-23 11:41:07
【问题描述】:

我在编译 Keras Sequential 模型时遇到以下错误:

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)

【问题讨论】:

  • 每个数组的 dtype (X_train.dtype) 是什么?
  • X_train.dtype---> dtype('float64')
  • 您的输入形状是 xtrain 的 (45985, 50, 50, 3),而 keras 的输入是 50,50,3,这是导致错误的原因
  • @JaskaranSingh 我不确定在这种情况下如何准确更改代码。你介意澄清一下吗?
  • @JaskaranSingh 不,错了,错误指向目标。

标签: python keras computer-vision classification conv-neural-network


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您的 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)
    

    【讨论】:

    • 我的 y_train 已经是一个热编码,现在我收到以下错误:ValueError: Error when checks target: expected dense_27 to have shape (10,) but got array with shape (24,)跨度>
    • @EwaSzyszka 听起来你有 24 个类而不是 10 个,模型需要 10 个类,你应该将最后一个 Dense 更改为 Dense(24, activation="softmax")
    • 将列表更改为 np 数组解决了问题:y_train = np.asarray(y_train) y_test = np.asarray(y_test)
    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多