TensorFlow模拟简单线性模型小栗子

时间:2022-05-03
本文章向大家介绍TensorFlow模拟简单线性模型小栗子,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

作者:赵 慧

编辑:李文臣

TensorFlow是什么

官方英文介绍:TensorFlow™ is an open source software library for numerical computation using data flow graphs.

TensorFlow是谷歌2015年开源的一个人工智能平台。就如命名一样,TensorFlow为张量从图的一端流动到另一端计算过程。TensorFlow是将复杂的数据结构传输至人工智能神经网中进行分析和处理过程的系统。TensorFlow可被用于语音识别或图像识别等多项机器深度学习领域,它可在小到一部智能手机、大到数千台数据中心服务器的各种设备上运行。与TensorFlow类似的库还有Caffe,Theano, MXNet.

TensorFlow的核心组件:

1. 张量(Tensor):大部分针对向量和矩阵

2. 基于张量的各种操作:比如矩阵乘法、计算均值方差等,本质上是从输入变量到输出变量的一个映射,

3. 计算图(Computation Graph):

4. 自动微分(Automatic Differentiation)工具:即定义了一连串的运算后,计算机就可以自动帮你计算整个输入输出间的梯度,

5. BLAS、cuBLAS、cuDNN等拓展包

TensorFlow框架

本文的标题和内容牵都涉及到 TensorFlow,仅仅是因为它是可以选用的工具之一,像Keras等等其他的框架都可以实现文章中想要的模型。本人无工具上的偏好,所以就当是拿 TensorFlow 举一个小小的例子。

从市面上的书籍和文章我们可以了解到TensorFlow 貌似是为深度学习而生的,好像不做些图像识别、机器人等深度学习项目就触不到TensorFlow,自己一直是这样固执的认为, 所以做模型的时候对TensorFlow都是视而不见的态度。

模拟线性模型

文中通过模拟产生数据,构造简单的线性模型,使用TensorFlow工具,利用梯度下降算法,估计模型系数,给出模拟的收敛效果;同时,我们使用著名的鸢尾花数据集来小试牛刀,so,let’s begin , just do it !

#首先加载我们将要用到的库
import tensorflow as tf
import numpy as np

#模拟产生数据
x_data = np.random.rand(1000).astype(np.float32)

#公式
y_data = 0.5 * x_data**2 + 0.3

下面看看我们画图看看数据到底长成什么样子,是不是美丽的:

从图中我们是可以看出二次趋势的,下面开始我们的tensorflow模拟过程。

#产生TensorFlow结构的数据
###create tensorflow Weights and biases ###
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)
biases = tf.Variable(tf.zeros([1])

#公式和上面的一样
###generate formula as above
y = Weights*x_data**2 + biases

#优化过程
#首先,定义损失函数(这里使用MSE)
###define loss function
loss = tf.reduce_mean(tf.square(y-y_data))

#使用梯度下降最优化损失函数,步长暂定为0.05
optimizer = tf.train.GradientDescentOptimizer(0.05)
#极小化损失函数
train = optimizer.minimize(lose)

#初始化变量
init = tf.global_variables_initializer()

#结束创建tensorflow结构,并且run起来
sess = tf.Session()
sess.run(init)

#我们选择迭代次数最大为500次,部分打印优化得到的结果
for step in range(501):
    sess.run(train)
    if step % 20 :
        print(step,sess.run(Weights),sess.run(biases))

#打印部分迭代结果如下:

0 [ 0.45762387] [ 0.31559378]

20 [ 0.46390951] [ 0.31328076]

40 [ 0.46926278] [ 0.3113108]

60 [ 0.47382206] [ 0.30963311]

80 [ 0.477705] [ 0.3082042]

100 [ 0.48101205] [ 0.30698729]

120 [ 0.48382849] [ 0.30595091]

140 [ 0.48622724] [ 0.30506817]

160 [ 0.48827016] [ 0.30431643]

180 [ 0.49001008] [ 0.30367616]

200 [ 0.49149185] [ 0.30313087]

220 [ 0.49275389] [ 0.30266646]

240 [ 0.49382871] [ 0.30227098]

260 [ 0.49474409] [ 0.30193409]

280 [ 0.49552372] [ 0.30164719]

300 [ 0.49618763] [ 0.30140293]

320 [ 0.49675313] [ 0.30119479]

340 [ 0.49723473] [ 0.30101761]

360 [ 0.49764487] [ 0.30086669]

380 [ 0.49799421] [ 0.3007381]

400 [ 0.49829179] [ 0.30062863]

看看预测效果

pre = sess.run(Weights) * x_data**2 + sess.run(biases)

为方便将我们的预测结果与原始数据做对比,选择迭代次数变化过程中拟合效果的可视化展示:

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(20,10))

plt.plot(x_data,pre,'bo',label="Predicted data",color='red')
plt.plot(x_data,y_data,'bo',label="Original data",color='blue')
###open the grid###
plt.grid(True)

plt.legend(bbox_to_anchor=(1.0,1),fontsize=23,loc=1,borderaxespad=0.)
plt.title("Linear Model:iteration 100 times : y = 0.5*x^2 + 0.3",fontsize=25)

plt.show()

迭代100次效果:

迭代200次效果:

迭代300次效果:

迭代400次效果:

迭代500次效果:

固定学习率,从迭代次数逐渐增加的过程中可以看出效果也是逐渐趋向完美拟合。

实现一个小栗子

下面我们使用著名的鸢尾花数据集进行实例分析:

读取数据集

import pandas as pd

iris = pd.read_csv('iris.csv')
#查看数据
iris.head()
y_data = np.array(iris["Sepal.Length"]) #萼片长度
x = np.array(iris["Petal.Width"])   #花瓣宽度

#初始化权重和偏差
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))

biases = tf.Variable(tf.zeros([1]))

y = Weights * x + biases

loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.05)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

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

Loss = pd.Series(np.arange(400,dtype = float))
for step in range(301):
    sess.run(train)
    Loss[step] = sess.run(loss)
    if step % 40 == 0:
        print(step,sess.run(Weights),sess.run(biases),"MSE:",sess.run(loss))

得到部分迭代结果如下:

0 [0.57750076] [0.61055863] MSE: 20.8943

20 [2.08994746] [2.9580822] MSE: 1.20182

40 [1.68378949] [3.5774076] MSE: 0.65115

60 [1.413679] [3.98509526] MSE: 0.411057

80 [1.23531616] [4.25429916] MSE: 0.30637

100[1.11753857] [4.43206167] MSE:0.260724

120[1.03976703] [4.54944229] MSE:0.240821

140[0.98841262] [4.62695217] MSE:0.232142

160[0.95450181] [4.67813396] MSE:0.228358

180[0.93210948] [4.71193075] MSE:0.226708

200[0.91732353] [4.73424721] MSE:0.225989

220[0.90755975] [4.74898386] MSE:0.225675

240[0.90111274] [4.7587142] MSE:0.225538

260[0.89685577] [4.7651391] MSE:0.225479

280[0.89404517] [4.76938105] MSE:0.225453

300[0.89218873] [4.77218294] MSE:0.225441

320[0.8909629] [4.77403307] MSE:0.225436

340[0.89015353] [4.77525473] MSE:0.225434

360[0.88961929] [4.77606106] MSE:0.225433

380[0.88926637] [4.77659416] MSE:0.225433

400[0.88903302] [4.77694607] MSE:0.225433

fig,ax = plt.subplots(figsize=(20,10))
Loss.plot(ylim = [0,20])
plt.show()
pre = sess.run(Weights)*x + sess.run(biases)

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(20,10))

#"x-",go-,rs,bo,+-
plt.plot(x,pre,'bo',label="Predicted data",color='red')

#'#00FF7F'
plt.plot(x,y_data,"bo",label="Original data",color='blue')
#plt.plot(x_data,y,"bo",label="Original data",color='green')#'#00FF7F'
'''open the grid'''
plt.grid(True)

plt.legend(bbox_to_anchor=(1.0,1),fontsize=25,loc=1,borderaxespad=0.)
plt.show()

可以看出简单线性模型对鸢尾花数据集拟合效果还是不错的。实际中我们可以使用花瓣宽度x对萼片长度y进行大体的预测。

结束语

一个使用Tensorflow应用于传统统计模型的小例子就这样告成了,欢迎指正。