我在Keras中有一个具有多个输出的网络,然而我的训练数据每次只提供一个输出的信息。
目前我的训练方法是对所涉及的输入进行预测,在更改我正在训练的特定输出的值,然后进行单批次更新。如果我没错的话,这与将所有输出的损失设置为零,除了我正在尝试训练的那个输出是相同的。
是否有更好的方法?我尝试过使用类权重,其中我为除我正在训练的输出之外的所有输出设置了零权重,但它没有给我期望的结果?
我正在使用Theano后端。
我在Keras中有一个具有多个输出的网络,然而我的训练数据每次只提供一个输出的信息。
目前我的训练方法是对所涉及的输入进行预测,在更改我正在训练的特定输出的值,然后进行单批次更新。如果我没错的话,这与将所有输出的损失设置为零,除了我正在尝试训练的那个输出是相同的。
是否有更好的方法?我尝试过使用类权重,其中我为除我正在训练的输出之外的所有输出设置了零权重,但它没有给我期望的结果?
我正在使用Theano后端。
假设您想从多个层返回输出,可能是一些中间层,但您只需要优化一个目标输出,那么可以按照以下方式操作:
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)
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)
None
。请确保您的所有操作都有定义梯度(即可微分)。没有梯度的常见操作:K.argmax,K.round,K.eval。” 我使用的tensorflow版本是1.14.0。我的损失是[None,''categorical_crossentropy"]。 - Cam Khttps://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'])
predictions = Concatenate()([predictions_A, predictions_B])
,并将其设置为第三个模型的输出。 - Bersan