[英]Can't fix ValueError: Building a simple neural network model in Keras
我是 TensorFlow 和 Keras 的新手,我想在 Keras 中构建一个简单的神经网络,可以从 0 到 7 的二进制数(即 000-111)。 网络应具有:
这听起来很简单,但我在构建 model 时遇到了问题。 我收到以下错误:
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'
作为最后一层(即 output 层)的激活,但是您的 model 应该产生零和一的向量。 因此,您需要改用'sigmoid'
。
由于'sigmoid'
将用于激活最后一层,因此您还需要使用binary_crossentropy
损失 function。
为了让您更好地理解该问题,您可以将其视为多标签分类问题:output 层中的 3 个节点中的每一个都应充当独立的二元分类器(因此使用 sigmoid 作为激活函数,二元交叉熵作为损失函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.