[英]Problem with result shape when running Keras Neural Network
I want to make prediction with Keras Neural Network.我想用 Keras 神经网络进行预测。 My output data has 3 different values -1,0,1.我的 output 数据有 3 个不同的值 -1,0,1。 When I run my NN I get the error:当我运行我的 NN 时,我得到了错误:
ValueError: Error when checking target: expected dense_35 to have shape (3,) but got array with shape (1,)
Then I tried to do:然后我试着做:
from tensorflow.python.keras.utils import to_categorical
results = to_categorical(results)
But again I get the same error:但我又得到了同样的错误:
ValueError: Error when checking target: expected dense_35 to have shape (3,) but got array with shape (2,)
What am I doing wrong?我究竟做错了什么? This is my code:这是我的代码:
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 param
model.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]
you're choosing 1-d output (shape: (rows,1)), but your last layer has 3 units model.add(Dense(3, activation = 'softmax'))
. results = df.iloc[:,-9]
您选择 1-d output (形状:(行,1)),但您的最后一层有 3 个单位model.add(Dense(3, activation = 'softmax'))
.
So, your result must have shape: (rows, 3) not (rows, 1).因此,您的结果必须具有形状:(rows, 3) 而不是 (rows, 1)。
I see your result has values -1, 0, 1. Just add one so that they are 0, 1, 2. That's why you're getting error with to_categorical
;我看到您的结果具有值 -1、0、1。只需添加一个,使它们为 0、1、2。这就是您在to_categorical
中出现错误的原因; according to the docs , it expects根据文档,它期望
y
: class vector to be converted into a matrix (integers from 0 to num_classes).y
: class 向量要转换成矩阵(从 0 到 num_classes 的整数)。
So go for所以 go 为
results = results + 1
Then, apply to_categorical
.然后,申请to_categorical
。
After that fit
should work fine.之后fit
应该工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.