TensorFlow2.0入门到进阶3.5 —— 自定义损失函数(含完整神经网络房价预测代码)

在之前的实际应用中,一般直接使用了其内置的损失函数,但是有些时候我们需要根据我们的实际需求自定义损失函数,这一节将详细讲解

1. 自定义损失函数详解

先上代码:

def customized_mse(y_true,y_test):
    return tf.reduce_mean(tf.square(y_true - y_test))


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='adam',
              metrics=["mean_squared_error"])

这里,首先要定义一个损失函数,对于入口参数:

对于神经网络的设计,和之前一致,如果需要可以考古一下之前的博客

通过compile来确定模型的损失函数,这里只要将之前的函数名写上即可,对于优化算法,这里使用了ADAM,对于评价指标,这里使用了mean_squared_error

2.完整代码实践

是否还记得第二章中已经对分类和回归都进行了具体的实践代码?已经好长时间了,这里就带着大家回顾一下完整的代码吧:

2.1 加载所需包

import matplotlib as mpl
import matplotlib.pyplot as plt
#为了在jupyter notebook中画图
%matplotlib inline
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras

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

2.2 加载房屋价格预测数据集

这个数据集是sklearn中自带的数据集,第一次运行时会从网上自动下载,所以会慢一下,之后就会很快

from sklearn.datasets import fetch_california_housing

housing=fetch_california_housing()

print(housing.DESCR)
print(housing.data.shape)
print(housing.target.shape)

2.3 查看数据集信息

import pprint

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

2.4 划分训练集、测试集和验证集

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)

2.5 数据标准化


from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(x_train)
x_valid_scaled = scaler.transform(x_valid)
x_test_scaled = scaler.transform(x_test)

2.6 创建模型(包括自定义损失函数)

#  自定义损失函数
def customized_mse(y_true,y_test):
    return tf.reduce_mean(tf.square(y_true - y_test))


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='adam',
              metrics=["mean_squared_error"])

2.7 训练模型

callbacks=[keras.callbacks.EarlyStopping(patience=5,min_delta=1e-2)]
history=model.fit(x_train_scaled,y_train,
         epochs=100,
         validation_data=(x_valid_scaled,y_valid),
         callbacks = callbacks )

2.8 查看结果

def plot_learning_curves(history):
    #设置画布大小为8和5
    pd.DataFrame(history.history).plot(figsize=(8,5))
    #显示网格
    plt.grid(True)
    #set_ylim为设置y坐标轴的范围
    plt.gca().set_ylim(0,1)
    plt.show()
    
plot_learning_curves(history)
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力改掉拖延症的小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值