假设我们的学习函数是 y = 2x + 1
打开jupyter编译,先导入必要的包,本文的代码是在tensorflow2.0上实现的
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
print(tf.__version__)
为了能够直接在jupyter上显示图形,再输入
%matplotlib inline
1.使用numpy产生数据
#载入随机种子
np.random.seed(5)
#生成100个等差序列,每个值在-1 - 1 之间
x_data = np.linspace(-1,1,100)
#y = 2x + 1 + 噪声,噪声的维度和x_Data一致
y_data = 2 * x_data +1.0 +np.random.randn(*x_data.shape) * 0.4 #*表示把元组拆分为一个个单独的实参
画出散点图以及训练前的线性函数
plt.scatter(x_data,y_data)
plt.plot(x_data,2*x_data+1,color = 'red' ,linewidth = 3)
结果如图
2.训练模型
定义模型函数以及线性函数的斜率和截距
#定义模型函数
def model(x,w,b):
return tf.multiply(x,w)+b
#构建线性函数的斜率和截距
w = tf.Variable(np.random.randn(),tf.float32)
b = tf.Variable(0.0,tf.float32)
因为模型比较简单,因此超参的迭代次数设置的比较小
#设置迭代次数和学习率
train_epochs = 10
learning_rate = 0.01
loss = []
count = 0
display_count = 10 #控制显示粒度的参数,每训练10个样本输出一次损失值
设置损失函数,这里使用均方差作为损失函数
def loss_fun(x,y,w,b):
err = model(x,w,b)-y
squared_err = tf.square(err)
return tf.reduce_mean(squared_err)
返回梯度向量
def grad(x,y,w,b):
with tf.GradientTape() as tape:
loss_ = loss_fun(x,y,w,b)
return tape.gradient(loss_,[w,b])
开始训练,轮数为epoch,采用SGD随机梯度下降优化方法
#开始训练,轮数为epoch,采用SGD随机梯度下降优化方法
for epoch in range(train_epochs):
for xs,ys in zip(x_data,y_data):
#计算损失,并保存本次损失计算结果
loss_ =loss_fun(xs,ys,w,b)
loss.append(loss_)
#计算当前[w,b]的梯度
delta_w,delta_b = grad(xs,ys,w,b)
change_w = delta_w * learning_rate
change_b = delta_b * learning_rate
w.assign_sub(change_w)
b.assign_sub(change_b)
#训练步数加1
count = count +1
if count % display_count == 0:
print('train epoch : ','%02d'%(epoch+1),'step:%03d' % (count),'loss= ','{:.9f}'.format(loss_))
#完成一轮训练后,画图
plt.plot(x_data,w.numpy() * x_data +b.numpy())
运行结果如图:
可以看出,因为模型比较简单,训练五次后就开始收敛
显示w和b的值
#显示训练结果
print('w: ',w.numpy())
print('b: ',b.numpy())
输出结果:
w: 1.9883282
b: 1.0375928
3.结果可视化
plt.scatter(x_data,y_data,lable = 'original data')
plt.plot(x_data,x_data *2.0 +1.0, label = 'object line',color = 'g',linewidth = 3)
plt.plot(x_data,x_data *w.numpy() + b.numpy(),label = 'fitted line',color = 'r',linewidth = 3)
plt.legend(loc = 2) #通过指定参数loc指定图例的位置
结果如图:
4.预测数据
x_test= 3.21
predict = model(x_test,w.numpy(),b.numpy())
print('预测值是:%f' % predict)
target = 2*x_test+1.0
print('目标值是:%f' % target)
输出结果:
预测值是:7.420126
目标值是:7.420000