Keras用两组不同的数据同时训练一个神经网络模型,并将两组数据各自的损失函数显示在进度条后面。该模型的架构如下图所示:
下面是相关的python代码:
import keras
import numpy as np
import tensorflow as tf
loss_tracker0 = keras.metrics.Mean(name="loss0")
loss_tracker1 = keras.metrics.Mean(name="loss1")
mae_metric0 = keras.metrics.MeanAbsoluteError(name="mae0")
mae_metric1 = keras.metrics.MeanAbsoluteError(name="mae1")
class CustomModel(keras.Model):
def train_step(self, data):
# Unpack the data. Its structure depends on your model and
# on what you pass to `fit()`.
x,y = data
with tf.GradientTape() as tape:
y_pred1 = self(x[1], training=True) # Forward pass
y_pred0 = self(x[0], training=True) # Forward pass
# Compute the loss value
# (the loss function is configured in `compile()`)
loss1 = self.compiled_loss(y[1], y_pred1, regularization_losses=self.losses)
loss0 = self.compiled_loss(y[0], y_pred0, regularization_losses=self.losses)
loss = loss1+loss0
# Compute gradients
trainable_vars = self.trainable_variables
gradients = tape.gradient(loss, trainable_vars)
# Update weights
self.optimizer.apply_gradients(zip(gradients, trainable_vars))
# Compute our own metrics
loss_tracker0.update_state(loss0)
mae_metric0.update_state(y[0], y_pred0)
loss_tracker1.update_state(loss1)
mae_metric1.update_state(y[1], y_pred1)
# Return a dict mapping metric names to current value
return {"loss1": loss_tracker1.result(), "mae1": mae_metric1.result(),"loss0": loss_tracker0.result(), "mae0": mae_metric0.result()}
def test_step(self, data):
# Unpack the data
x, y = data
# Compute predictions
y_pred1 = self(x[1], training=True) # Forward pass
y_pred0 = self(x[0], training=True) # Forward pass
# Updates the metrics tracking the loss
loss1 = self.compiled_loss(y[1], y_pred1, regularization_losses=self.losses)
loss0 = self.compiled_loss(y[0], y_pred0, regularization_losses=self.losses)
# Compute our own metrics
loss_tracker0.update_state(loss0)
mae_metric0.update_state(y[0], y_pred0)
loss_tracker1.update_state(loss1)
mae_metric1.update_state(y[1], y_pred1)
# Return a dict mapping metric names to current value.
return {"loss1": loss_tracker1.result(), "mae1": mae_metric1.result(),"loss0": loss_tracker0.result(), "mae0": mae_metric0.result()}
# Just use `fit` as usual
x1 = np.random.random((1000, 32))
y1 = np.random.random((1000, 1))
x0 = np.random.random((1000, 32))
y0 = np.random.random((1000, 1))
val_x1 = np.random.random((100, 32))
val_y1 = np.random.random((100, 1))
val_x0 = np.random.random((100, 32))
val_y0 = np.random.random((100, 1))
val_data = ([val_x1,val_x0], [val_y1,val_y0])
# Construct and compile an instance of CustomModel
inputs = keras.Input(shape=(32,))
hidden = keras.layers.Dense(10)(inputs)
outputs = keras.layers.Dense(1)(hidden)
model = CustomModel(inputs, outputs)
model.compile(optimizer="adam", loss=["mse"], metrics=['mae'])
history = model.fit([x1,x0], [y1,y0],validation_data=val_data,verbose=1, epochs=4,batch_size=10)
代码运行的结果如下: