3 回答

TA貢獻1797條經(jīng)驗 獲得超4個贊
您確實確實直接解決了問題-方法如下:
Keras 二進制分類期望標簽(“目標”)形狀為
(batch_size, 1)
. 原因:最后一層的目標是輸出預測,將其與標簽進行比較以計算指標(損失、準確性等) - 并且標簽被塑造(batch_size, 1)
以上也是問題所在 - 請參閱下面文檔
to_categorical
中的片段;對于二進制分類,one-hot 編碼是多余的,因為直接將標簽與提供的預測進行比較binary_crossentropy
Keras
Dense
期望輸入是 2D:(batch_size, input_dim)
. 您的重塑使輸入 3D:(batch_size, 1, input_dim)
以上也是
shape=(1, no_terms)
-->shape=(no_terms,)
幫助的原因;事實上,兩者都適合您當時提供的數(shù)據(jù)形狀。完整的批次形狀僅包括批次暗淡:(batch_size, no_terms)
(no_terms == input_dim
)最后,對于二元分類,
loss='binary_crossentropy'
對分類問題使用 - 而不是均方誤差(除非出于非常特殊的原因)
# Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:
> labels
array([0, 2, 1, 2, 0])
# `to_categorical` converts this into a matrix with as many
# columns as there are classes. The number of rows
# stays the same.
> to_categorical(labels)
array([[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.]], dtype=float32)

TA貢獻1844條經(jīng)驗 獲得超8個贊
好吧,我找到了錯誤的解決方案,但仍然無法理解為什么以前的形狀沒有成功,坦率地說,這個修復在無數(shù)次嘗試和錯誤中取得了成功。
我將以下圖層輸入從形狀格式 (1, x) 更改為 (x,) 格式:
input_layer = Input(shape=(no_terms,), name='docs')
k_constants = backend.constant(np.reshape(tpr_fpr.T, (1,2*no_terms)))
fixed_input = Input(tensor=k_constants, shape=(2*no_terms,), name='tpr_fpr')
h = Dense(int(300), activation='relu', name='hidden', input_shape=(2*no_terms,), trainable=True)(fixed_input)
o = ReLU(max_value=None, negative_slope=0.0, threshold=0.0)(o)
o = Dense(1, activation='sigmoid', input_shape=(no_terms,))(o)
并且還從代碼中刪除了以下幾行:
train_docs.shape = (train_docs.shape[0], 1, train_docs.shape[1])
train_label = to_categorical(train_label, num_classes=2, dtype='float32')
現(xiàn)在我只使用形狀標簽 (#no_of_samples, 1),它是二進制而不是分類標簽。
所以新的結構是:
我希望有人可以解釋以前的模型有什么問題,所以我會避免再次犯同樣的錯誤。

TA貢獻1865條經(jīng)驗 獲得超7個贊
檢查目標:預期dense_1有3維,但得到的數(shù)組形狀為(1430, 2)"
這意味著 dense_1 有 3 個維度,但如果您在圖像處理中設計此模型,則您的輸入只有 2 個維度,在這種情況下,您已聲明圖像形狀 yhat 為 ((48,48),1) & ((48,48),3 ) 這里 1 用于灰度,3 用于 rgb 圖像
添加回答
舉報