TensorFlow写简单的代码是大财小用,需要很繁琐的代码方能实现简单的功能,但对于复杂的机器学习算法和深度神经网络却是十分的简单,下边看一个tf实现线性回归的Demo


首先引入tf包的相关的package,并初始化100个点。这里我们假定线性回归中的w为0.1 b为0.3,并设置一个随机数保证在y=0.1X + 0.3 上下浮动。

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
# coding: utf-8
'''
create by: Thinkgamer
create time: 2018/04/22
desc: 使用tensorflow创建线性回归模型
'''
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# 随机生成100个点
num_points = 100
vectors_set = list()
for i in range(num_points):
x1 = np.random.normal(0.00,00.55)
y1 = x1* 0.1 + 0.3 + np.random.normal(0.0,0.03)
vectors_set.append([x1,y1])

# 生成一些样本
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
# print(x_data)
# print(y_data)
plt.scatter(x_data,y_data,c='r')
plt.show()

生成的图如下所示:
这里写图片描述

用刚才生成的数据进行线性回归拟合

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
# 构造线性回归模型

# 生成一维的W矩阵,取值是[-1,1]之间的随机数
W = tf.Variable(tf.random_uniform([1],-1,1),name='W')
# 生成一维的b矩阵,初始值为0
b = tf.Variable(tf.zeros([1]),name='b')
# 经过计算得出预估值y
y=W*x_data + b

# 定义损失函数,以预估值y和y_data之间的均方误差作为损失
loss = tf.reduce_mean(tf.square(y - y_data),name='loss')
# 采用地图下降算法来优化参数
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 训练过程就是最小化误差
train = optimizer.minimize(loss,name='train')

sess = tf.Session()

init = tf.global_variables_initializer()
sess.run(init)

# 初始化W 和 b
print("初始化值: W = ",sess.run(W), "b= ",sess.run(b))
for step in range(20):
sess.run(train)
# 打印出每次训练后的w和b
print("第 %s 步: W = " % step,sess.run(W), "b= ",sess.run(b))

# 展示
plt.scatter(x_data,y_data,c='r')
plt.plot(x_data,sess.run(W)*x_data+sess.run(b),c='b')
plt.show()

对应的输出结果为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
初始化值:  W =  [-0.300848] b=  [0.]
0 步: W = [-0.17744449] b= [0.3065566]
1 步: W = [-0.09421768] b= [0.30550653]
2 步: W = [-0.03631891] b= [0.3047983]
3 步: W = [0.0039596] b= [0.3043056]
4 步: W = [0.0319802] b= [0.3039629]
5 步: W = [0.05147332] b= [0.30372444]
6 步: W = [0.06503413] b= [0.30355856]
7 步: W = [0.07446799] b= [0.30344316]
8 步: W = [0.08103085] b= [0.30336288]
9 步: W = [0.08559645] b= [0.30330706]
10 步: W = [0.0887726] b= [0.3032682]
11 步: W = [0.09098216] b= [0.30324116]
12 步: W = [0.09251929] b= [0.30322236]
13 步: W = [0.09358863] b= [0.30320928]
14 步: W = [0.09433253] b= [0.3032002]
15 步: W = [0.09485004] b= [0.30319384]
16 步: W = [0.09521006] b= [0.30318946]
17 步: W = [0.09546052] b= [0.3031864]
18 步: W = [0.09563475] b= [0.30318424]
19 步: W = [0.09575596] b= [0.30318278]

生成的图如下:
这里写图片描述


打开微信扫一扫,加入数据与算法交流大群