值错误:检查目标时出错:期望dense_1具有形状(无,1)但是具有形状的数组(6000,3)

时间:2018-04-06 02:50:50

标签: python keras

我面临分类分类器

模型输入形状的问题
   x         y
 [1,2,3]    [0]
 [2,3,5]    [1]
 [2,1,6]    [2]
 [1,2,3]    [0]
 [2,3,5]    [0]
 [2,1,6]    [2]

然后我将y标签更改为分类为

   y
  [1,0,0]
  [0,1,0]
  [0,0,1]
  [1,0,0]
  [1,0,0]
  [0,0,1]

我的x_train形状是(6000,3) y_train形状是(6000,3) x_test形状是(2000,3) y_test形状是(2000,3)

我尝试了这个模型并获得了价值错误

model=sequential()
model.add(Dense(1, input_shape(3,), activation="softmax"))
model.compile(Adam(lr=0.5), 'categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train,y_train,epochs=50, verbose=1)

Value error: Error when checking target: expected dense_1 to have shape(None,1) but got array with shape (6000,3)

我不明白这个错误。帮我理清这个

1 个答案:

答案 0 :(得分:0)

您的网络需要一个与输出类数相匹配的输出层。你可以这样做

X_train = np.zeros((10,3))
y_train = np.zeros((10,))

X_test = np.zeros((10,3))
y_test = np.zeros((10,))

num_classes = 3
y_train_binary = keras.utils.to_categorical(y_train, num_classes)
y_test_binary = keras.utils.to_categorical(y_test, num_classes)

input_shape = (3,)

model = Sequential()                 
model.add(Dense(16, activation='relu',input_shape=input_shape))         
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss='categorical_crossentropy',
                       optimizer='rmsprop',
                       metrics=['mae'])

model.summary()

history=model.fit(X_train,
                  y_train_binary,
                  epochs=5,
                  batch_size=8,
                  validation_data=(X_test, y_test_binary))