Keras-从一个神经网络做出两个预测 [英] Keras - Making two predictions from one neural network

查看:96
本文介绍了Keras-从一个神经网络做出两个预测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并由同一网络产生的两个输出,这些输出对4类任务和10类任务进行预测.然后,我希望将这些输出结合起来,以提供一个长度为14的数组,并将其用作最终目标.

I'm trying to combine two outputs that are produced by the same network that makes predictions on a 4 class task and a 10 class task. Then I look to combine these outputs to give a length 14 array which I use as my end target.

虽然这似乎很有效,但预测始终是针对一个类别的,因此它产生的概率分布仅与从14个选项中选择1个而不是2个有关.我实际上需要做的是提供2个预测,每节课一个.我希望所有这些都由同一模型产生.

While this seems to work actively the predictions are always for one class so it produces a probability dist which is only concerned with selecting 1 out of the 14 options instead of 2. What I actually need it to do is to provide 2 predictions, one for each class. I want this all to be produced by the same model.

input = Input(shape=(100, 100), name='input')
lstm = LSTM(128, input_shape=(100, 100)))(input)

output1 = Dense(len(4), activation='softmax', name='output1')(lstm)
output2 = Dense(len(10), activation='softmax', name='output2')(lstm)

output3 = concatenate([output1, output2])

model = Model(inputs=[input], outputs=[output3])

我的问题是确定适当的损失函数和预测方法?为了进行预测,我可以简单地在softmax之后获取每个层的输出,但是我不确定如何为要训练的每个事物设置损失函数.

My issue here is determining an appropriate loss function and method of prediction? For prediction I can simply grab the output of each layer after the softmax however I'm unsure how to set the loss function for each of these things to be trained.

有什么想法吗?

非常感谢

推荐答案

您不需要连接输出,您的模型可以有两个输出:

You don't need to concatenate the outputs, your model can have two outputs:

input = Input(shape=(100, 100), name='input')
lstm = LSTM(128, input_shape=(100, 100)))(input)

output1 = Dense(len(4), activation='softmax', name='output1')(lstm)
output2 = Dense(len(10), activation='softmax', name='output2')(lstm)

model = Model(inputs=[input], outputs=[output1, output2])

然后要训练该模型,通常使用两个损失,这些损失经加权产生一个损失:

Then to train this model, you typically use two losses that are weighted to produce a single loss:

model.compile(optimizer='sgd', loss=['categorical_crossentropy', 
              'categorical_crossentropy'], loss_weights=[0.2, 0.8])

只需确保正确格式化数据,因为现在每个输入样本对应于两个带有输出标签的样本.有关更多信息,请参见功能API指南.

Just make sure to format your data right, as now each input sample corresponds to two output labeled samples. For more information check the Functional API Guide.

这篇关于Keras-从一个神经网络做出两个预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆