Tensorflow2.0 利用API 自定义构建回归模型

低阶API构建回归模型

  1. 准备数据
import numpy as np 
import pandas as pd
from matplotlib import pyplot as plt 
#样本数量
n = 400
# 生成测试用数据集
X = tf.random.uniform([n,2],minval=-10,maxval=10) 
w0 = tf.constant([[2.0],[-3.0]])
b0 = tf.constant([[3.0]])
Y = X@w0 + b0 + tf.random.normal([n,1],mean = 0.0,stddev= 2.0)  # @表示矩阵乘法,增加正态扰动
  1. 数据可视化
# 数据可视化

%matplotlib inline
# %config InlineBackend.figure_format = 'svg'

plt.figure(figsize = (5,5))
ax1 = plt.subplot(121)
ax1.scatter(X[:,0],Y[:,0], c = "b")
plt.xlabel("x1")
plt.ylabel("y",rotation = 0)

ax2 = plt.subplot(122)
ax2.scatter(X[:,1],Y[:,0], c = "g")
plt.xlabel("x2")
plt.ylabel("y",rotation = 0)
plt.show()

在这里插入图片描述

  1. 数据管道
### 数据迭代器
### tf.gather 获取指定列表中 指定索引的值
def data_iter(features, labels, batch_size=8):
    num_examples = len(features)
    indices = list(range(num_examples))
    np.random.shuffle(indices)  #样本的读取顺序是随机的
    for i in range(0, num_examples, batch_size):
        ## 防止 上越界
        indexs = indices[i: min(i + batch_size, num_examples)]
        yield tf.gather(features,indexs), tf.gather(labels,indexs)
  1. 定义模型
w = tf.Variable(tf.random.normal(w0.shape))
b = tf.Variable(tf.zeros_like(b0,dtype = tf.float32))

# 自定义模型
class LinearRegression:     
    #正向传播
    def __call__(self,x): 
        return x@w + b ## @表示矩阵乘法
    # 损失函数
    def loss_func(self,y_true,y_pred):  
        return tf.reduce_mean((y_true - y_pred)**2/2)

model = LinearRegression()
  1. 训练,旨在更新参数,获取对应的损失及其他输出
##使用autograph机制转换成静态图加速

@tf.function
def train_step(model, features, labels):
    with tf.GradientTape() as tape:
        predictions = model(features)
        loss = model.loss_func(labels, predictions)
    # 反向传播 求梯度(线性函数其实没有反向传播,可以直接求各个参数的倒数)
    dloss_dw, dloss_db = tape.gradient(loss,[w,b])
    # 梯度下降法 更新参数
    w.assign(w - 0.001*dloss_dw)
    b.assign(b - 0.001*dloss_db)
    
    return loss
    
def train_model(model,epochs):
    for epoch in tf.range(1,epochs+1):
        for features, labels in data_iter(X,Y,10):
            loss = train_step(model,features,labels)
        if epoch%50==0:
            ##printbar()
            tf.print("epoch =",epoch,"loss = ",loss)
            tf.print("w =",w)
            tf.print("b =",b)

train_model(model,epochs = 200)
## 以下展示的是学习出来的 某一维度 与 label的关系图

在这里插入图片描述

高阶API构建回归模型

此处值列举与原生API 差异。

  1. 构建模型差异。高阶api可以直接定义模型,添加Layer ,这样就基本完成网络的构建
tf.keras.backend.clear_session()
model = models.Sequential()
model.add(layers.Dense(1,input_shape =(2,)))
model.summary()
  1. 训练差异。
### 使用fit方法进行训练
#### 可以指明损失函数,优化器,评估函数
model.compile(optimizer="adam",loss="mse",metrics=["mae"])
#### 定义训练过程中参数,迭代次数,每次feed 多少数据 batch_size
model.fit(X,Y,batch_size = 10,epochs = 200)  
tf.print("w = ",model.layers[0].kernel)
tf.print("b = ",model.layers[0].bias)

总结

构建模型的核心思路应该有以下步骤:
1、构建模型部分。从低阶API可以看出,此部分核心是定义 网络结构。包括网络层数,每层的激活函数、参数维度等
2、训练模型部分。核心就是参数更新。正向传播求模型预测结果,反向传播是根据预测结果 计算损失,并得出梯度,进行进行参数更新

感谢 eat_tensorflow2_in_30_days 教程, 对于低阶与高阶API构建模型的对比,更好的了解底层机制

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值