[英]How to use keras for mutli label multiclass classification
我有一個數據集,其中包含 6 個可能的類型標簽:
Class 1: Near-large
Class 2: Far- Large
Class 3: Near - Medium
Class 4: Far - Medium
Class 5: Near - small
Class 6: far - small
我想修改問題以分離標簽,以便每個樣本都可以獨立地分類為遠/近和小/中/小,給定每個分類的不同特征作為輸入。
我的第一個想法是為每個子標簽訓練 2 個不同的模型,然后創建一個自定義函數來加入預測,但我想知道在 Keras 框架內是否有更快的方法。
我知道我可以使用函數式 API 來創建兩個具有獨立輸入和兩個獨立輸出的模型。 這會給我 2 個不同子標簽的 2 個預測。 如果我對子標簽進行熱編碼,這些模型的輸出將是這樣的:
Model1.output = [ 0,1 ] or [1,0] ( far/near)
Model2.output = [ 1, 0, 0 ] or [0,1,0] or [0,0,1](small/medium/large)
但是,如何合並這兩個輸出以創建完整標簽的 6 個暗向量?
Model_merged.output = [1, 0, 0, 0, 0 ,0 ] , [010000], ...., [000001] (class1,... ,Class6)
您可以reshape
1 輸出以擴展軸,將其與模型 2 輸出相乘並將它們都展平。
from keras.models import Model
reshaped = keras.layers.Reshape((2,-1))(model1.output)
combined = keras.layers.Multiply()([reshaped,model2.output])
flattened = keras.layers.Reshape((6,))(combined)
Combined_model = Model([model1.input,model2.input], flattened)
上面的一個簡單的 numpy 示例是:
model1_output = np.array([0,1])[:,None] #Reshaped
#array([[0],
# [1]])
model2_output = np.array([1,0,0])
# array([1, 0, 0])
combined = model1_output*model2_output
#array([[0, 0, 0],
# [1, 0, 0]])
combined.ravel()
#array([0, 0, 0, 1, 0, 0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.