回归模型中的损失函数loss,自定义损失函数

446 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第五天,点击查看活动详情

总结:此文为12月更文计划第四天第十篇。

回归模型中的损失函数loss

今天开始一个学习回归模型中的loss实战。

在训练的过程中,以前使用到是损失函数loss是均方误差函数:mean_squared_error .

首先从sklearn中导入所需要的数据:这里以加利福尼亚的数据来学习


from sklearn.datasets import fetch_california_housing

housing = fetch_california_housing()
# print(housing.DESCR)
print(housing.data.shape)
print(housing.target.shape)

输出的结果如下:

image.png

对这些数据进行划分为训练集与测试集

from sklearn.model_selection import train_test_split

x_train_all, x_test, y_train_all, y_test = train_test_split(
    housing.data, housing.target, random_state = 7)
x_train, x_valid, y_train, y_valid = train_test_split(
    x_train_all, y_train_all, random_state = 11)
print(x_train.shape, y_train.shape)
print(x_valid.shape, y_valid.shape)
print(x_test.shape, y_test.shape)

输出的结果如下:

image.png

接下来就要进行自定义损失函数的学习了

接下来写一个函数,作为自定义的损失函数:

def customized_mse(y_true, y_pred):
    return tf.reduce_mean(tf.square(y_pred - y_true))
# m=tf.keras.losses.MeanSquaredError()  #用框架提供的对象
model = keras.models.Sequential([
    keras.layers.Dense(30, activation='relu',
                       input_shape=x_train.shape[1:]),
    keras.layers.Dense(1),
])
model.summary()
model.compile(loss=customized_mse, optimizer="sgd",
              metrics=["mean_squared_error"])  #为了验证自定义损失是否正确
callbacks = [keras.callbacks.EarlyStopping(
    patience=5, min_delta=1e-2)]

在训练的时候,模型会对这个函数进行调用,称之为回调函数。

不是在你将函数放在这里就使用,而是在函数的执行过程中调用的函数称之为回调函数。

输出的结果如下:

image.png

比较系统所给的mse损失函数与自己所写的损失函数的区别与相同:

这是系统的

mse = tf.keras.losses.MeanSquaredError()
loss = mse([0., 0., 1., 1.], [1., 1., 1., 0.])
loss # Loss: 0.75

输出的结果如下:

image.png

调用自己所写的:

customized_mse(np.array([0., 0., 1., 1.]), np.array([1., 1., 1., 0.]))

输出的结果如下:

image.png

看以看到在计算逻辑相同的情况下,自己写的和系统所给的是相同的。可以改变自己所写的逻辑来进行改变损失函数的计算