我正在尝试使用tf keras模型使用自定义损失(add_loss)训练标量变量。问题在于标量变量的值不会改变。这是一个简单的版本:
import tensorflow as tf
inputs = [[float(x)] for x in range(100)]
outputs = [float(x) for x in range(100)]
input_t = tf.keras.layers.Input((1,))
output_t = tf.keras.layers.Dense(1)(input_t)
v1 = tf.keras.backend.variable((1.0,), dtype='float32')
model = tf.keras.Model(inputs=input_t, outputs=output_t, name='testnet')
model.add_loss(lambda: -v1*100.0)
model.compile(optimizer='sgd', loss='mae')
model.fit(inputs, outputs, steps_per_epoch=100, epochs=10, batch_size=1)
我希望损失会迅速下降,而v1会变大,看来标量变量的损失是经过计算的,但变量本身并未更新。
Train on 100 samples
Epoch 1/10
100/100 [==============================] - 0s 3ms/sample - loss: -82.0786
Epoch 2/10
100/100 [==============================] - 0s 730us/sample - loss: -83.6085
Epoch 3/10
100/100 [==============================] - 0s 747us/sample - loss: -83.5726
Epoch 4/10
100/100 [==============================] - 0s 746us/sample - loss: -83.9825
Epoch 5/10
100/100 [==============================] - 0s 794us/sample - loss: -83.1476
Epoch 6/10
100/100 [==============================] - 0s 1ms/sample - loss: -83.8165
Epoch 7/10
100/100 [==============================] - 0s 790us/sample - loss: -83.3511
Epoch 8/10
100/100 [==============================] - 0s 769us/sample - loss: -83.6053
Epoch 9/10
100/100 [==============================] - 0s 744us/sample - loss: -83.5687
Epoch 10/10
100/100 [==============================] - 0s 772us/sample - loss: -83.6377