在线性回归中,我们通过一个一条直线进行整个数据的进行拟合,具体代码如下:
由于线性回归的代码很常见,因此本次使用TensorFlow深度学习框架进行线性回归的计算
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
## 新添加
from IPython import display
在其中“from IPython import display”,是用来制作线性回归的仿真动画,同时导入matplotib进行曲线的绘制。
## 算法参数设置
learning_rate = 0.1
training_epochs = 1000
display_step = 5
线性回归中的优化算法为梯度下降算法,具体包括learning_rate为梯度下降的学习率,学习率过小,会使得模型收敛速度过慢,学习率太大会使得模型提前收敛,甚至造成模型发散,由于线性回归的模型比较简单,所以不需要使用复杂优化器,training_epochs为模型迭代次数,display_step为每多少次进行一次损失函数的显示。
## 产生需要拟合的数据
train_X = np.random.rand(100).astype(np.float32)
train_X.sort()
train_Y = (train_X - 5)*100 + 0.3
n_samples = train_X.shape[0]
X = tf.compat.v1.placeholder("float")
Y = tf.compat.v1.placeholder("float")
w = tf.compat.v1.Variable(np.random.randn(), name='weight')
b = tf.compat.v1.Variable(np.random.randn(), name='bias')
pred = tf.add(tf.multiply(X, w), b)
产生100个为32浮点型数据点,初始化x,y,w,b参数
cost = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples)
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.compat.v1.global_variables_initializer()
定义损失函数tf.pow为TensorFlow框架中计算幂函数,在昨天的公式中,将预测的损失函数分母为抽取样本的两倍。优化器为梯度下降,也可以试试SGD,Adam优化器
with tf.compat.v1.Session() as sess:
sess.run(init)
plt.figure(num=1)
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X: x, Y: y})
if (epoch + 1) % display_step == 0:
# plt.figure(num=3)
plt.ion()
plt.cla()
c = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c),
"W=", sess.run(w), 'b=', sess.run(b))
### draw the picture
plt.plot(train_X, train_Y, 'ro', label='Orginal data')
plt.plot(train_X, sess.run(w)*train_X + sess.run(b) , label='Fitted line')
plt.legend()
plt.pause(0.001)
#### 新添加
display.clear_output(wait=True)
plt.show()
正式进行线性回归的计算,本文使用的TensorFlow1.x,最终输出figure(1)的图片每0.001进行一帧的显示,形成完整的动画。
AI学习的道路上,一起学习进步~