当前位置:   article > 正文

Tensorflow2.0 keras 自定义损失函数_keras 自定义均方差损失

keras 自定义均方差损失

关键代码

# 自定义损失函数
def custom_loss(y_true, y_prd):
    # mean((y_prd-y_true)** 2)  均方差损失函数
    return tf.reduce_mean(tf.square(y_prd - y_true))


# 模型的编译  设置损失函数 优化器
model.compile(loss=custom_loss,  # 使用自定义损失函数
              optimizer='sgd',
              metrics=['mean_squared_error'])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

完整代码(回归模型)

import pprint
import sys

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
import tensorflow as tf
from tensorflow import keras

print(tf.__version__)
print(sys.version_info)

for module in mpl, np, pd, sklearn, keras, tf:
    print(module.__name__, module.__version__)

from sklearn.datasets import fetch_california_housing

# 1.加载数据集 波士顿房价预测
housing = fetch_california_housing()
print(housing.DESCR)
print(housing.data.shape)
print(housing.target.shape)

pprint.pprint(housing.data[:5])
pprint.pprint(housing.target[:5])

from sklearn.model_selection import train_test_split

# 2.拆分数据集
#   训练集与测试集拆分
x_train_all, x_test, y_train_all, y_test = train_test_split(housing.data,
                                                            housing.target,
                                                            random_state=7,
                                                            test_size=0.20)
# 训练集与验证集的拆分
x_train, x_valid, y_train, y_valid = train_test_split(
    x_train_all, y_train_all, random_state=11, test_size=0.20)

print(x_train.shape, y_train.shape)
print(x_valid.shape, y_valid.shape)
print(x_test.shape, y_test.shape)

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()

# 3、数据预处理 数据集的归一化
x_train_scaled = scaler.fit_transform(x_train)
x_valid_scaled = scaler.transform(x_valid)
x_test_scaled = scaler.transform(x_test)

# 4、网络模型的搭建
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(30, activation='relu', input_shape=x_train.shape[1:]),
    tf.keras.layers.Dense(20, activation='relu'),
    tf.keras.layers.Dense(1),
])

print(model.layers)
model.summary()


# 自定义损失函数
def custom_loss(y_true, y_prd):
    # mean((y_prd-y_true)** 2)
    return tf.reduce_mean(tf.square(y_prd - y_true))


# 5、模型的编译  设置损失函数 优化器
model.compile(loss=custom_loss,  # 使用自定义损失函数
              optimizer='sgd',
              metrics=['mean_squared_error'])

# 6、设置回调函数
callbacks = [tf.keras.callbacks.EarlyStopping(patience=5, min_delta=1e-3)]

# 7、训练网络
history = model.fit(x_train_scaled, y_train,
                    validation_data=(x_valid_scaled, y_valid),
                    epochs=100,
                    callbacks=callbacks)


# 8、绘制训练过程数据
def plot_learning_curves(hst):
    pd.DataFrame(hst.history).plot()
    plt.grid(True)
    plt.gca().set_ylim(0, 1)
    plt.show()


plot_learning_curves(history)

# 9.验证数据
model.evaluate(x_test_scaled, y_test)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/133199
推荐阅读
相关标签
  

闽ICP备14008679号