我使用的是Python 3.7和Keras 2.2.4。我创建了一个具有两个输出层的Keras模型:
self.df_model = Model(inputs=input, outputs=[out1,out2])
由于损失历史只返回每个epoch的一个损失值,我想获取每个输出层的损失。如何可能在每个epoch中获取两个损失值,每个输出层一个?
回答:
在Keras中,每个模型都有一个默认的History
回调函数,它存储了所有epoch的所有损失和度量值,包括总体值以及每个输出层的具体值。这个回调函数会创建一个History
对象,当调用fit
模型时返回,你可以通过该对象的history
属性访问所有这些值(实际上是一个字典):
history = model.fit(...)print(history.history) # <-- 一个包含每个epoch的所有损失和度量值的字典
一个最小的可复现示例:
from keras import layersfrom keras import Modelimport numpy as npinp = layers.Input((1,))out1 = layers.Dense(2, name="output1")(inp)out2 = layers.Dense(3, name="output2")(inp)model = Model(inp, [out1, out2])model.compile(loss='mse', optimizer='adam')x = np.random.rand(2, 1)y1 = np.random.rand(2, 2)y2 = np.random.rand(2, 3)history = model.fit(x, [y1,y2], epochs=5)print(history.history)#{'loss': [1.0881365537643433, 1.084699034690857, 1.081269383430481, 1.0781562328338623, 1.0747418403625488],# 'output1_loss': [0.87154925, 0.8690172, 0.86648905, 0.8641926, 0.8616721],# 'output2_loss': [0.21658726, 0.21568182, 0.2147803, 0.21396361, 0.2130697]}