簡體   English   中英

無法修復 ValueError:在 Keras 中構建簡單的神經網絡 model

[英]Can't fix ValueError: Building a simple neural network model in Keras

我是 TensorFlow 和 Keras 的新手,我想在 Keras 中構建一個簡單的神經網絡,可以從 0 到 7 的二進制數(即 000-111)。 網絡應具有:

  • 1 個輸入層,3 個節點,
  • 1 個具有 8 個節點的隱藏層,
  • 1 output 層,3 個節點。

這聽起來很簡單,但我在構建 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])

我想可能有幾件事我沒有做對。

有兩個問題:

  1. 您正在使用'relu'作為最后一層(即 output 層)的激活,但是您的 model 應該產生零和一的向量。 因此,您需要改用'sigmoid'

  2. 由於'sigmoid'將用於激活最后一層,因此您還需要使用binary_crossentropy損失 function。

為了讓您更好地理解該問題,您可以將其視為多標簽分類問題:output 層中的 3 個節點中的每一個都應充當獨立的二元分類器(因此使用 sigmoid 作為激活函數,二元交叉熵作為損失函數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM