无法修复 ValueError:在 Keras 中构建一个简单的神经网络模型

我是 TensorFlow 和 Keras 的新手,我想在 Keras 中构建一个简单的能从 0 到 7 进行二进制计数的神经网络(即从 000 到 111)。这个网络应该具有:

  • 一个包含 3 个节点的输入层,
  • 一个包含 8 个节点的隐藏层,
  • 一个包含 3 个节点的输出层。

这听起来很简单,但我遇到了构建模型的问题。我收到了以下错误:

ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (3,)

我尝试过的代码如下:

import plaidml.keras
plaidml.keras.install_backend()
import os
os.environ["KERAS_BACKEND"] = plaidml.keras.backend
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
x_train = [ [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0],[1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]
y_train = [ [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0],[1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]
x_train = np.array(x_train)
y_train = np.array(y_train)
x_test = x_train
y_test = y_train
print(x_train)
print(y_train)
print("x_test_len", len(x_test))
print("y_test_len", len(y_test))
# Build a CNN model. You should see INFO:plaidml:Opening device xxx after you run this chunk
model = keras.Sequential()
model.add(Dense(input_dim=3, output_dim=8, activation='relu'))
model.add(Dense(input_dim=8, output_dim=3, activation='relu'))
# Compile the model
model.compile(optimizer='adam', loss=keras.losses.sparse_categorical_crossentropy, metrics=['accura cy'])
# Fit the model on training set
model.fit(x_train, y_train, epochs=10)
# Evaluate the model on test set
score = model.evaluate(x_test, y_test, verbose=0)
# Print test accuracy
print('\n', 'Test accuracy ', score[1])

我想可能有几个地方我没有做对。


回答:

存在两个问题:

  1. 你使用了 'relu' 作为最后一层的激活函数(即输出层),然而你的模型应该产生零和一的向量。因此,你需要使用 'sigmoid' 代替。

  2. 由于最后一层的激活函数使用了 'sigmoid',你还需要使用 binary_crossentropy 作为损失函数。

为了让你更好地理解这个问题,你可以将其视为一个多标签分类问题:输出层中的每个节点都应作为一个独立的二元分类器(因此使用 sigmoid 作为激活函数和二元交叉熵作为损失函数)。

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中创建了一个多类分类项目。该项目可以对…

发表回复

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