如何使用Keras进行多标签多类分类

3

我有一个数据集,其中包含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创建两个具有独立输入和两个独立输出的模型。这将为我提供两个不同子标签的预测。如果对子标签进行一次热编码,则这些模型的输出将类似于以下内容:

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) 

1个回答

0
您可以使用reshape函数来调整model1的输出,扩展轴的维度,然后将其与model2的输出相乘并将它们都压平。
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])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接