【问题标题】:How to use keras for mutli label multiclass classification如何使用keras进行多标签多类分类
【发布时间】:2020-06-26 12:09:26
【问题描述】:

我有一个包含 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) 

【问题讨论】:

    标签: python keras classification


    【解决方案1】:

    您可以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])
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 2021-02-17
      • 2017-09-27
      • 1970-01-01
      • 2018-08-04
      • 2020-10-26
      • 2021-04-12
      • 2019-05-21
      • 2017-10-25
      相关资源
      最近更新 更多