我是 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])
我想可能有几个地方我没有做对。
回答:
存在两个问题:
-
你使用了
'relu'
作为最后一层的激活函数(即输出层),然而你的模型应该产生零和一的向量。因此,你需要使用'sigmoid'
代替。 -
由于最后一层的激活函数使用了
'sigmoid'
,你还需要使用binary_crossentropy
作为损失函数。
为了让你更好地理解这个问题,你可以将其视为一个多标签分类问题:输出层中的每个节点都应作为一个独立的二元分类器(因此使用 sigmoid 作为激活函数和二元交叉熵作为损失函数)。