我在Keras中有一个具有许多输出的网络,然而,我的训练数据一次只提供单个输出的信息。
目前,我的训练方法是对有问题的输入运行预测,更改我正在训练的特定输出的值,然后执行一次批量更新。如果我是正确的,这与将所有输出的损失设置为零是相同的,除了我试图训练的输出。
有没有更好的方法?我已经尝试了类权重,除了我正在训练的输出之外,我对所有的输出都设置了零权重,但是它没有给我预期的结果?
我正在使用Theano后端。
发布于 2019-05-16 18:53:37
输出多个结果并只优化其中的一个
假设您希望返回来自多个层的输出,可能是来自某些中间层的输出,但您只需要优化一个目标输出。下面是你怎么做的:
让我们从这个模型开始:
inputs = Input(shape=(784,))
x = Dense(64, activation='relu')(inputs)
# you want to extract these values
useful_info = Dense(32, activation='relu', name='useful_info')(x)
# final output. used for loss calculation and optimization
result = Dense(1, activation='softmax', name='result')(useful_info)使用多个输出进行编译,对于额外的输出将loss设置为None:
为不想用于损失计算和优化的输出提供None
model = Model(inputs=inputs, outputs=[result, useful_info])
model.compile(optimizer='rmsprop',
loss=['categorical_crossentropy', None],
metrics=['accuracy'])训练时仅提供目标输出。正在跳过额外的输出:
model.fit(my_inputs, {'result': train_labels}, epochs=.., batch_size=...)
# this also works:
#model.fit(my_inputs, [train_labels], epochs=.., batch_size=...)一次预测就能得到所有的结果
对于一个模型,您只需运行一次predict即可获得所需的所有输出:
predicted_labels, useful_info = model.predict(new_x)发布于 2017-08-21 10:35:10
为了达到这个目的,我最终使用了“函数式API”。您基本上创建了多个模型,使用相同的层输入层和隐藏层,但不同的输出层。
例如:
https://keras.io/getting-started/functional-api-guide/
from keras.layers import Input, Dense
from keras.models import Model
# This returns a tensor
inputs = Input(shape=(784,))
# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions_A = Dense(1, activation='softmax')(x)
predictions_B = Dense(1, activation='softmax')(x)
# This creates a model that includes
# the Input layer and three Dense layers
modelA = Model(inputs=inputs, outputs=predictions_A)
modelA.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
modelB = Model(inputs=inputs, outputs=predictions_B)
modelB.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])https://stackoverflow.com/questions/40446488
复制相似问题