亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

另一個“檢查目標時出錯:期望dense_2具有形狀(4,)但得到形狀為(1,)的數組”

另一個“檢查目標時出錯:期望dense_2具有形狀(4,)但得到形狀為(1,)的數組”

收到一只叮咚 2023-10-11 21:34:01
我在 Python 3 中使用 Keras。我遇到的問題似乎與許多其他問題相似,我能告訴的最好的情況是我可能需要使用 Flatten(),盡管我不知道如何正確設置參數。我收到錯誤:ValueError:檢查目標時出錯:預期dense_2具有形狀(4,)但得到形狀為(1,)的數組我的數據還不是圖像,但它們是我已轉換為數據幀的序列。model = Sequential()model.add(Dense(30, input_dim=16, activation='relu'))model.add(Dense(len(TheBinsizeList), activation='softmax'))model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])model.fit(Train_Columns, TrainTarget_Columns.to_frame(), epochs=100, batch_size=64)print(Train_Columns.shape)# Gives a value of (1627, 16)print((TrainTarget_Columns.to_frame()).shape)# Gives a value of (1627,1)現在 TrainTarget_Columns 的值是這兩個元組中的 1627:(1494, 3) (1080, 2) (1863, 2) (919, 4) (1700, 2) (710, 4) (1365, 4) (1815, 3) (1477, 2) (1618, 1)...主題編號是每個管中的第一個條目,第二個條目是訓練目標的值。雖然我看到將密集_2 中的 TheBinsizeList 從 4 更改為 2 會導致預期形狀從 (4,) 變為 (2,),但我不知道如何使用 Flatten (如果需要的話)來正確格式化值。Model: "sequential_1"_________________________________________________________________Layer (type)                 Output Shape              Param #   =================================================================dense_1 (Dense)              (None, 30)                510       _________________________________________________________________dense_2 (Dense)              (None, 4)                 124       =================================================================Total params: 634Trainable params: 634Non-trainable params: 0任何幫助表示贊賞和感謝。
查看完整描述

1 回答

?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

考慮到您的模型摘要,模型需要輸入 shape(batch_size, 16)和目標 shape (batch_size, 4)。


如果你的目標的形狀是(1627,1)你的問題。


解決方案:將其更改為一個熱變量(例如使用tf.one_hot(y, n_classes)),錯誤應該消失


import numpy as np

import tensorflow as tf


input_dim = 16

hidden_dim = 30

n_classes = 4


model = tf.keras.Sequential()

model.add(tf.keras.layers.Dense(hidden_dim, input_dim=input_dim, activation='relu'))

model.add(tf.keras.layers.Dense(n_classes, input_dim=hidden_dim, activation='relu'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])


X = np.random.randn(100, input_dim)

y = np.random.randint(0, n_classes, size=(100,))


model.fit(X, y)

# ValueError: Shapes (None, 1) and (None, 4) are incompatible


y = tf.one_hot(y, n_classes)

model.fit(X, y)

# Works !


查看完整回答
反對 回復 2023-10-11
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號