我想使用Keras神经网络进行预测。我的输出数据有三个不同的值-1、0、1。当我运行我的神经网络时,我得到了以下错误:
ValueError: Error when checking target: expected dense_35 to have shape (3,) but got array with shape (1,)
然后我尝试了以下操作:
from tensorflow.python.keras.utils import to_categoricalresults = to_categorical(results)
但我再次得到了相同的错误:
ValueError: Error when checking target: expected dense_35 to have shape (3,) but got array with shape (2,)
我做错了什么?这是我的代码:
features = df.iloc[:,-8:]results = df.iloc[:,-9]x_train, x_test, y_train, y_test = train_test_split(features, results, test_size=0.3, random_state=42)model = Sequential()model.add(Dense(64, input_dim = x_train.shape[1], activation = 'relu')) # input layer requires input_dim parammodel.add(Dense(32, activation = 'relu'))model.add(Dense(16, activation = 'relu'))model.add(Dense(3, activation = 'softmax'))model.compile(loss="categorical_crossentropy", optimizer= "adam", metrics=['accuracy'])# call the function to fit to the data training the network)es = EarlyStopping(monitor='val_loss', min_delta=0.001, patience=0, verbose=1, mode='auto')model.fit(x_train, y_train, epochs = 10, shuffle = True, batch_size=128, validation_data=(x_test, y_test), verbose=2, callbacks=[es])
回答:
results = df.iloc[:,-9]
你选择的是一维输出(形状:(rows,1)),但你的最后一层有3个单元 model.add(Dense(3, activation = 'softmax'))
。
所以,你的结果必须是形状:(rows, 3),而不是(rows, 1)。
我看到你的结果值有-1、0、1。只要加1,使它们变成0、1、2。这就是为什么你在使用 to_categorical
时会出错;根据文档,它期望
y
: 要转换为矩阵的类向量(从0到num_classes的整数)。
所以你应该这样做
results = results + 1
然后,应用 to_categorical
。
之后 fit
应该可以正常工作了。