python ValueError:检查目标时出错:预期密集_2的形状为(12,),但数组的形状为(1,)

时间:2020-03-03 08:10:03

标签: python keras

编写程序,使用keras构建BP神经网络来预测数据(回归),程序如下:

bp_dataset = pd.read_csv('Dataset/allGlassStraightThroughTube.csv')
bp_tube_par = bp_dataset.iloc[:, 3:8]
bp_tube_eff = bp_dataset.iloc[:, -1:]


bp_tube_par_X_train,bp_tube_par_X_test,bp_tube_eff_Y_train,bp_tube_eff_Y_test = train_test_split(bp_tube_par,
                                                                                                 bp_tube_eff,
                                                                                                 random_state=33,
                                                                                                 test_size=0.3)

# normalize the train and test Dataset
sc_X = StandardScaler()
sc_Y = StandardScaler()
sc_bp_tube_par_X_train = sc_X.fit_transform(bp_tube_par_X_train)
sc_bp_tube_par_X_test = sc_X.transform(bp_tube_par_X_test)
sc_bp_tube_eff_Y_train = sc_Y.fit_transform(bp_tube_eff_Y_train)
sc_bp_tube_eff_Y_test = sc_Y.transform(bp_tube_eff_Y_test)

# build BP neural network
model = Sequential()
model.add(Dense(12, input_dim=5, activation='relu'))
model.add(Dense(12, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy', 'mae'])
model.fit(sc_bp_tube_par_X_train, sc_bp_tube_eff_Y_train, epochs=100)
pre_sc_bp_tube_eff_Y_test = model.predict(sc_bp_tube_par_X_test)

但出现错误:

Traceback (most recent call last):
  File "C:/Users/win/PycharmProjects/allGlassStraightThroughTube/bpTest.py", line 44, in <module>
model.fit(sc_bp_tube_par_X_train, sc_bp_tube_eff_Y_train, epochs=100)
  ...
  ValueError: Error when checking target: expected dense_2 to have shape (12,) but got array with shape (1,)

能否请您告诉我原因和纠正方法

1 个答案:

答案 0 :(得分:1)

model.add(Dense(12, activation='linear'))

12在这里代表输出尺寸。在您的情况下12是第二层的输入尺寸。 Keras处理中间层的输入尺寸,您不必明确提及。

您的代码应为

model.add(Dense(1, activation='linear'))