![](/img/trans.png)
[英]ValueError: Error when checking model target: expected dense_4 to have shape (None, 4) but got array with shape (13252, 1)
[英]Keras model building - ValueError: Error when checking target: expected dense_24 to have shape (None, 1) but got array with shape (576, 2)
我正在嘗試構建一個keras模型,為此我有576個樣本,4個輸入變量和1個目標變量,即1或0。我認為我的目標的尺寸/格式或模型最后一層的尺寸。 我碰壁了,可以幫忙。
我嘗試的第一件事是將目標變量轉換為二進制numpy數組,但是當我輸入以下代碼時:
import pandas as pd
from keras.layers import Dense
import numpy as np
from keras.models import Sequential
from keras.utils.np_utils import to_categorical
n_cols = predictors.shape[1]
target_b = to_categorical(target)
model = Sequential()
model.add(Dense(6, activation='relu',input_shape=(n_cols,) ))
model.add(Dense(1))
model.compile(optimizer = 'adam', loss ='categorical_crossentropy',metrics= ['accuracy'] )
model.fit(predictors, target_b, validation_split=.3)
我收到以下錯誤:
ValueError: Error when checking target: expected dense_24 to have shape (None, 1) but got array with shape (576, 2)
當我嘗試將目標變量保留為整數numpy ndarray時,我改用sparse_categorical_crossentropy,但收到此錯誤:
InvalidArgumentError (see above for traceback): Received a label value of 1 which is outside the valid range of [0, 1). Label values: 0 0 0 1 0 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 1 0 1
[[Node: SparseSoftmaxCrossEntropyWithLogits_6/SparseSoftmaxCrossEntropyWithLogits = SparseSoftmaxCrossEntropyWithLogits[T=DT_FLOAT, Tlabels=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](Reshape_13, Cast_30)]
我想我要做的就是更改目標變量或模型尺寸,但是我不確定要更改哪個變量,也不確定如何更改。 非常感謝您的指導。 謝謝!
幾種方法:
Dense(2, activation='softmax')
to_categorical
行,並使用Dense(2, activation='softmax')
和loss='sparse_categorical_crossentropy'
to_categorical
行,並使用Dense(1, activation='sigmoid')
和loss='binary_crossentropy'
輸入到“密集”層的形狀需要1D輸入,但是看起來要輸入的數據是2D。 您可以將輸入大小調整為input_shape=(576, 2)
。
您的最后一層應該是Dense(2)
。 這是因為target_b矩陣必須為形狀(576,2)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.