1 回答
TA贡献1812条经验 获得超5个赞
一旦你做了一些对 Keras 来说不完全正常的事情,我建议使用自定义训练循环。然后您可以控制训练过程的每一步。
我这样做了,我不需要改变你的损失函数。
import tensorflow as tf
import numpy as np
ds_x = tf.data.Dataset.from_tensor_slices(np.random.randn(5, 5).astype(np.float32))
ds_y = tf.data.Dataset.from_tensor_slices({'l1': np.arange(5), 'l2':np.arange(5)})
ds = tf.data.Dataset.zip((ds_x, ds_y)).batch(2)
input_ = tf.keras.Input(shape=[5])
x = tf.keras.layers.Dense(30, activation='relu')(input_)
x1 = tf.keras.layers.Dense(5, activation='softmax')(x)
x2 = tf.keras.layers.Dense(5, activation='softmax')(x)
model = tf.keras.Model(inputs=input_, outputs={'l1':x1, 'l2':x2})
def model_loss(y, y_):
res = 3 * tf.losses.SparseCategoricalCrossentropy()(y['l1'], y_['l1'])
res += tf.losses.SparseCategoricalCrossentropy()(y['l2'], y_['l2'])
return res
train_loss = tf.keras.metrics.Mean()
optimizer = tf.keras.optimizers.Adam()
for i in range(25):
for x, y in ds:
with tf.GradientTape() as tape:
out = model(x)
loss = model_loss(y, out)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
print(f'Epoch {i} Loss: {train_loss.result():=4.4f}')
train_loss.reset_states()
Epoch 0 Loss: 6.4170
Epoch 1 Loss: 6.3396
Epoch 2 Loss: 6.2737
Epoch 11 Loss: 5.7191
Epoch 12 Loss: 5.6608
Epoch 19 Loss: 5.2646
Epoch 24 Loss: 4.9896
添加回答
举报