python - 如何使用 keras 进行多标签多类分类
问题描述
我有一个数据集,其中包含 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
使用 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])
推荐阅读
- date - 检查最近的日子
- asp.net-identity - 使用名为“page”的 URL GET 参数时,Actionlink 生成空 href
- angular - TypeError:无法读取 Object.eval 处未定义的属性“ShoppingCart”
- android - 如何在父布局中正确缩放图像视图?
- laravel - Laravel 路由在谷歌应用引擎中不起作用
- sockets - 用外部数据缓冲区分配 mbuf
- javascript - Jquery AJAX 请求正文为空。(Docker 内的 Django REST)
- json - 我无法在 PhpStorm 的 JSON 脚本标签中粘贴 Twig 代码
- xml - WS-Trust 1.3 规范与 xsd 的区别
- cordova - 将事件从 Native 发送到 Ionic