在前两篇文章中,我们介绍tf的一些基础概念以及模型运算的基本流程,现在我们进一步学习tf.今天主要有以下学习目标:
自定义(损失函数+评估指标)
多个输入输出模型
回调函数
传送门:TensorFlow上手(一)TensorFlow上手(二)
自定义损失和指标
自定义损失函数
keras允许我们在complie方法里面传入自定义的损失函数:
def get_uncompiled_model():
inputs = keras.Input(shape=(784,), name="digits")
x = layers.Dense(64, activation="relu", name="dense_1")(inputs)
x = layers.Dense(64, activation="relu", name="dense_2")(x)
outputs = layers.Dense(10, activation="softmax", name="predictions")(x)
model = keras.Model(inputs=inputs, outputs=outputs)
return model
def custom_mean_squared_error(y_true, y_pred):
return tf.math.reduce_mean(tf.square(y_true - y_pred))
model = get_uncompiled_model()
model.compile(optimizer=keras.optimizers.Adam(), loss=custom_mean_squared_error)
自定义评估指标
同样,也允许传入自定义的评估指标,它要继承keras.metrics.Metric。下面的例子实现了计算多少个正样本的评估指标:
class CategoricalTruePositives(keras.metrics.Metric):
def __init__(self, name="categorical_true_positives", **kwargs):
super(CategoricalTruePositives, self).__init__(name=name, **kwargs)
self.true_positives = self.add_weight(name="ctp", initializer="zeros")
def update_state(self, y_true, y_pred, sample_weight=None):
y_pred = tf.reshape(tf.argmax(y_pred, axis=1), shape=(-1, 1))
values = tf.cast(y_true, "int32") == tf.cast(y_pred, "int32")
values = tf.cast(values, "float32")
if sample_weight is not None:
sample_weight = tf.cast(sample_weight, "float32")
values = tf.multiply(values, sample_weight)
self.true_positives.assign_add(tf.reduce_sum(values))
def result(self):
return self.true_positives
def reset_states(self):
# The state of the metric will be reset at the start of each epoch.
self.true_positives.assign(0.0)
model = get_uncompiled_model()
model.compile(
optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),
loss=keras.losses.SparseCategoricalCrossentropy(),
metrics=[CategoricalTruePositives()],
)
自定义指标实现过程依赖四个方法:
__init__(self),为指标创建状态变量
update_state(self),使用目标 y_true 和模型预测 y_pred 更新状态变量
result(self),使用状态变量来计算最终结果
reset_states(self),在下一次迭代中,重新初始化指标的状态
上面代码中,self.add_weight表示增加一个