使用Keras神经网络运行时结果形状问题

我想使用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 应该可以正常工作了。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注