【问题标题】:Keras - "ValueError: Error when checking target: expected activation_1 to have shape (None, 9) but got array with shape (9,1)Keras - “ValueError:检查目标时出错:预期activation_1具有形状(无,9)但得到形状为(9,1)的数组
【发布时间】:2020-02-05 05:51:01
【问题描述】:

我正在构建一个模型以将文本分类为 9 层之一,并且在运行它时出现此错误。 Activation 1 似乎是指卷积层的输入,但我不确定输入有什么问题。

num_classes=9
Y_train = keras.utils.to_categorical(Y_train, num_classes)
#Reshape data to add new dimension
X_train = X_train.reshape((100, 150, 1)) 
Y_train = Y_train.reshape((100, 9, 1)) 
model = Sequential() 
model.add(Conv1d(1, kernel_size=3, activation='relu', input_shape=(None, 1))) 
model.add(Dense(num_classes)) 
model.add(Activation('softmax')) 

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) 
model.fit(x=X_train,y=Y_train, epochs=200, batch_size=20)

运行此程序会导致以下错误:

"ValueError: 检查目标时出错:预期activation_1 的形状为(None, 9),但得到的数组的形状为(9,1)

【问题讨论】:

  • 为什么将Y_train 重新定义为X_train.reshape((100, 9, 1))
  • @desertnaut 这是一个错字。已修复,但在我发布此问题时输入错误。

标签: python tensorflow machine-learning keras keras-layer


【解决方案1】:

您的代码中有几个拼写错误和错误。

  1. Y_train = Y_train.reshape((100,9))

  2. 1234563 987654324@.
  3. 在馈入 Dense 层之前,您需要扁平化 conv1d 的输出。

import keras
from keras import Sequential
from keras.layers import Conv1D, Dense, Flatten

X_train = np.random.normal(size=(100,150))
Y_train = np.random.randint(0,9,size=100)

num_classes=9
Y_train = keras.utils.to_categorical(Y_train, num_classes)
#Reshape data to add new dimension
X_train = X_train.reshape((100, 150, 1)) 
Y_train = Y_train.reshape((100, 9)) 
model = Sequential() 
model.add(Conv1D(2, kernel_size=3, activation='relu', input_shape=(150,1)))
model.add(Flatten())
model.add(Dense(num_classes, activation='softmax')) 

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) 
model.fit(x=X_train,y=Y_train, epochs=200, batch_size=20)

【讨论】:

    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2018-07-29
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多