[英]ValueError: logits and labels must have the same shape ((None, 5) vs (None, 1))
[英]Model returning error - ValueError: logits and labels must have the same shape ((None, 18) vs (None, 1))
我正在玩一個基於 keras 的多 label 分類器。 我創建了一個加載訓練和測試數據的 function,然后我在 function 本身中處理/拆分 X/Y。 運行 model 時出現錯誤,但不太確定其含義:
這是我的代碼:
def KerasClassifer(df_train, df_test):
X_train = df_train[columnType].copy()
y_train = df_train[variableToPredict].copy()
labels = y_train.unique()
print(X_train.shape[1])
#using keras to do classification
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation
from tensorflow.keras.optimizers import SGD
model = Sequential()
model.add(Dense(5000, activation='relu', input_dim=X_train.shape[1]))
model.add(Dropout(0.1))
model.add(Dense(600, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(len(labels), activation='sigmoid'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy',
optimizer=sgd)
model.fit(X_train, y_train, epochs=5, batch_size=2000)
preds = model.predict(X_test)
preds[preds>=0.5] = 1
preds[preds<0.5] = 0
score = model.evaluate(X_test, y_test, batch_size=2000)
score
這是我的數據的屬性(如果有幫助的話):
x train shape (392436, 109)
y train shape (392436,)
len of y labels 18
如何修復代碼以避免此錯誤?
如果您有 18 個類別,則y_train
的形狀應為(392436, 18)
。 您可以為此使用tf.one_hot
:
import tensorflow as tf
y_train = tf.one_hot(y_train, depth=len(labels))
而且,如果您從一列中獲取值,我懷疑這不是“多標簽”,而是多類。 一個樣本真的可以屬於多個類別嗎? 如果沒有,您還需要更改其他一些內容。 例如,您需要 softmax 激活:
model.add(Dense(len(labels), activation='softmax'))
還有分類交叉熵損失:
model.compile(loss='categorical_crossentropy', optimizer=sgd)
你的標簽是一維的...如果你的目標是操作一個多 label 任務,你需要對它們進行單熱編碼。 你可以簡單的使用
tf.keras.utils.to_categorical(y, num_classes)
通過這種方式,您可以將目標從 (n_sample) 轉換為 (n_sample, num_classes)
如果這是一個簡單的多 class問題,那么您有以下兩種可能性:
1 種可能性)如果你有 1D integer 編碼目標,你可以使用sparse_categorical_crossentropy
作為損失 function 和softmax
激活來生成概率
n_class = 3
n_features = 100
n_sample = 1000
X = np.random.randint(0,10, (n_sample,n_features))
y = np.random.randint(0,n_class, n_sample)
inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)
model = Model(inp, out)
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
pred = np.argmax(model.predict(X), 1)
2 種可能性)如果您對目標進行單熱編碼以獲得 2D 形狀(n_samples, num_classes)
,則可以使用帶有softmax
激活的categorical_crossentropy
來生成概率
n_class = 3
n_features = 100
n_sample = 1000
X = np.random.randint(0,10, (n_sample,n_features))
y = tf.keras.utils.to_categorical(np.random.randint(0,n_class, n_sample))
inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)
model = Model(inp, out)
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
pred = np.argmax(model.predict(X), 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.