目录
一、简介
TensorFlow是谷歌基于DistBelief进行研发的第二代人工智能学习系统,其命名来源于本身的运行原理。
Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow为张量从流图的一端流动到另一端的计算过程。
TensorFlow是将复杂的数据结构传输至人工智能神经网中进行分析和处理过程的系统。
TensorFlow是开源的,任何人都可以用。
网站:http://playground.tensorflow.org
支持CNN(卷积神经网络)、RNN(循环神经网络)和LSTM(长短期记忆网络)算法,是目前在 Image,NLP 最流行的深度神经网络模型.
二、优点
TensorFlow优点:
- 基于Python,写的很快并且具有可读性。
- 在CPU或GPU系统上的都可运行。
- 代码编译效率较高。
- 社区发展的非常迅速并且活跃。
- 能够生成显示网络拓扑结构和性能的可视化图。
三、原理
TensorFlow原理:
TensorFlow是用数据流图(data flow graphs)技术来进行数值计算的。
数据流图是描述有向图中的数值计算过程。
有向图中,节点通常代表数学运算,边表示节点之间的某种联系,它负责传输多维数据(Tensors)。
四、使用
1、TensorFlow使用
- 使用图(graph)来表示任务
- 在被称之为会话(Session)的上下文(context)中执行图
- 使用tensor表示数据
- 通过变量(Variable)维护状态f(x) = w*x + b
- 使用feed和fetch可以为任意操作(arbitrary operation)赋值或者从其中获取数据。
2、下载
在管理员模式下cmd窗口中执行:
pip install tensorflow
3、第一个 tf 程序
这里需要先安装 Ipython,进入cmd输入
pip3 install Ipython
导入包
#导包
import tensorflow as tf
import numpy as np
from IPython.display import display
常量
#定义常量
a = tf.constant(np.random.randint(0,100,size=(3,4)))
b = tf.constant(3.14)
s = tf.constant('hello world')
display(a,b,s)
Tensor(“Const:0”, shape=(3, 4), dtype=int32)
Tensor(“Const_1:0”, shape=(), dtype=float32)
Tensor(“Const_2:0”, shape=(), dtype=string)
很明显能看出你定义的常量大小和类型。
变量
#定义变量
w = tf.Variable(np.random.randint(0,100,size=(2,3)),
dtype=tf.int8, #数据类型
name='w' #变量命名,可省略
)
print(w)
<tf.Variable ‘w:0’ shape=(2, 3) dtype=int8_ref>
创建会话
sess = tf.Session()
关闭会话
sess.close()
使用会话运行graph
-
一般使用with语句来创建会话,这样就不用手动关闭会话,with语句会自动关闭会话。
-
run()函数可以让代码变得更加简洁,在搭建神经网络中,经历了数据集准备、前向传播过程设计、损失函数及反向传播过程设计等三个过程,形成计算网络,再通过会话tf.Session().run()进行循环优化网络参数。这样可以使得代码变得更加简洁,可以集中处理多个图和会话,明确调用tf.Session().run()可能是一种更加直观的方法。
-
run语法:run(
fetches
,feed_dict
=None,options
=None,run_metadata
=None)
fetches
参数可以是单个图元素(single graph element),也可以是任意嵌套的列表list,元组tuple,名称元组namedtuple,字典dict或包含图元素的OrderedDict。feed_dict
可选参数允许调用者覆盖图中张量的值options
可选参数需要一个[‘RunOptions’]原型。 选项允许控制该特定步骤的行为run_metadata
可选参数需要一个[RunMetadata]原型。 适当时,将在那里收集此步骤的非Tensor输出。- 函数返回值与 ‘ fetches ’ 参数具有相同的形状
- run的参数是字典形式,如果按照顺序传参,可以不写成字典形式
常量
with tf.Session() as sess:
ret = sess.run(fetches=[a,b,s])
print(ret)
[array([[82, 83, 87, 73],
[55, 37, 48, 11],
[54, 58, 4, 50]]), 3.14, b’hello world’]
变量
with tf.Session() as sess:
# 如果要使用变量,需要进行初始化
sess.run(tf.global_variables_initializer())
print(sess.run(w))
[[30 13 41]
[ 8 81 57]]
加减乘除
#加减乘除
a = tf.constant(100,dtype=tf.float16)
b = tf.constant(5,dtype=tf.float16)
#加
c = a + b
d = tf.add(a,b)
#减
e = tf.subtract(a,b)
#乘
f = tf.multiply(a,b)
#除
h = tf.div(a,b)
with tf.Session() as sess:
print(sess.run([a,b,c,d,e,f,h]))
[100.0, 5.0, 105.0, 105.0, 95.0, 500.0, 20.0]
矩阵乘法(叉乘:左列右行一致)
import numpy as np
from IPython.display import display
a = tf.constant(np.random.randint(0,10,size = (2,3)))
b = tf.constant(np.random.randint(0,10,size = (3,2)))
#矩阵乘法
m = tf.matmul(a,b)
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(b))
print(sess.run(m))
[[4 0 4]
[2 8 0]]
[[8 1]
[2 7]
[6 2]]
[[56 12]
[32 58]]
降维加法
- 叫降维是因为运算后矩阵某一维度的维数减小
- 叫加法是因为运算是通过元素相加得到
列降维
a = tf.constant(np.random.randint(0,10,size = (4,5)))
#axis=1,列相加,即每列之间做加法
#比如第一个数26 = 4+0+4+8+5
b = tf.reduce_sum(a,axis = 1)
with tf.Session() as sess:
print(sess.run(a))
print('-----------------')
print(sess.run(b))
结果
[[4 0 4 8 5]
[4 4 2 0 4]
[8 1 4 7 3]
[6 4 6 4 5]]
-----------------
[21 14 23 25]
行降维
import tensorflow as tf
import numpy as np
from IPython.display import display
a = tf.constant(np.random.randint(0,10,size = (4,5)))
#axis=0,行相加,即每行之间做加法
#比如第一个数19=8+2+7+2
b = tf.reduce_sum(a,axis = 0)
with tf.Session() as sess:
print(sess.run(a))
print('-----------------')
print(sess.run(b))
结果
[[8 1 2 9 6]
[2 5 8 5 4]
[7 1 4 2 6]
[2 1 2 4 8]]
-----------------
[19 8 16 20 24]
4、placeholder占位符
placeholder:可以先定义矩阵的维度,不必赋初值,在具体的运算时再赋值,定义的变量可以多次赋值。
#定义一个[None,None]的矩阵和[3,None]的矩阵
#矩阵行和列可以不具体指定,里面的元素值也可以不给
a = tf.placeholder(dtype=tf.float32,shape=[None,None])
b = tf.placeholder(dtype=tf.float32,shape=[3,None])
m = tf.matmul(a,b)
with tf.Session() as sess:
a1 = np.random.randint(0,10,size = (2,3))
b1 = np.random.randint(0,10,size = (3,1))
print('a=',a1)
print('b=',b1)
print('a和b的矩阵乘法=',
sess.run( # 输出乘积
m,
feed_dict={ # 给变量赋值
a:a1,
b:b1
}
)
)
a= [[0 0 6]
[8 0 3]]
b= [[2]
[4]
[8]]
a和b的矩阵乘法= [[48.]
[40.]]
五、使用TensorFlow实现线性回归
#导包
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt # 绘图包
#绘图时可以显示中文
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
#生成训练数据
X_train = np.linspace(0,12,40)
y_train = np.linspace(0,5,40)
#加噪声
y_train += np.random.randn(40)*0.5
plt.figure(1)
plt.scatter(X_train,y_train)
#定义TensorFlow参数:X,Y,W,b
X = tf.placeholder(dtype=tf.float32,shape=[None,1],name='data')
Y = tf.placeholder(dtype=tf.float32,shape=[None,1],name='target')
#定义两个变量W和b,赋初值
#斜率
W = tf.Variable(np.random.randn(1,1),name='weight',
dtype=tf.float32)
#截距
b = tf.Variable(np.random.randn(1,1),name='bias',
dtype=tf.float32)
#创建线性模型
pred = tf.matmul(X,W) + b
# 均方误差损失函数
# tf.reduce_sum() 降维加法
# pred = [[p1],[p2],[p3]……]
# Y = [[y1],[y2],[y3],……]
# (pred-Y) 相同的位置进行相减
# 有40个点,除以40求平均值.
cost = tf.reduce_sum(tf.pow(tf.subtract(pred,Y),2))/40
#创建梯度下降优化器optimizer,学习率0.01
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
#定义训练次数
epoches = 1000
with tf.Session() as sess:
#变量初始化
sess.run(tf.global_variables_initializer())
#循环
for i in range(epoches):
opt,c = sess.run([optimizer,cost],
# 给占位符设置数据
feed_dict={
X:X_train.reshape(-1,1),
Y:y_train.reshape(-1,1)
}
)
#100次循环打印输出一次
if (i+1)%100 == 0:
w_ = sess.run(W)
b_ = sess.run(b)
print('训练次数:%d,损失函数是:%0.4f,斜率是:%0.2f,截距是:%0.2f'%(i,c,w_,b_))
c = sess.run(cost,feed_dict={X:X_train.reshape(-1,1),Y:y_train.reshape(-1,1)})
w_ = sess.run(W)
b_ = sess.run(b)
print('训练结束,损失函数是:%0.4f,斜率是:%0.2f,截距是:%0.2f'%(c,w_,b_))
#绘制图形
plt.figure(2)
plt.scatter(X_train,y_train)
x1 = np.linspace(0,12,200)
#绘制回归线
plt.plot(x1,x1*0.42 + 0.15,color = 'green',label='斜率=%0.2f 截距=%0.2f'%(0.42,0.15))
plt.legend()
plt.show()
训练次数:99,损失函数是:0.3926,斜率是:0.47,截距是:-0.56
训练次数:199,损失函数是:0.3601,斜率是:0.45,截距是:-0.38
训练次数:299,损失函数是:0.3484,斜率是:0.44,截距是:-0.28
训练次数:399,损失函数是:0.3442,斜率是:0.43,截距是:-0.21
训练次数:499,损失函数是:0.3427,斜率是:0.43,截距是:-0.18
训练次数:599,损失函数是:0.3422,斜率是:0.42,截距是:-0.15
训练次数:699,损失函数是:0.3420,斜率是:0.42,截距是:-0.14
训练次数:799,损失函数是:0.3419,斜率是:0.42,截距是:-0.13
训练次数:899,损失函数是:0.3419,斜率是:0.42,截距是:-0.13
训练次数:999,损失函数是:0.3419,斜率是:0.42,截距是:-0.12
训练结束,损失函数是:0.3419,斜率是:0.42,截距是:-0.12
六、使用TensorFlow实现类逻辑斯蒂回归
导入包
import numpy as np
import matplotlib.pyplot as plt # 绘图
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # 导入手写数字的数据
加载当前目录下data文件夹中的4个压缩文件
mnist = input_data.read_data_sets('./data/',one_hot=True)
print(mnist.train.num_examples) #训练样本数
images = mnist.train.images # 二维化的图片数据 原始图像大小28*28
print(images.shape) # 输入大小55000个28*28
55000
(55000, 784)
# 在其它地方的概率为0,下标为7的地方概率为1
# 所以其代表数字7
mnist.train.labels[0] # labels数组中的每一个元素值代表的是概率,哪个下标对应的概率大,这个数组就表示是哪个数字的概率大。
plt.figure(figsize=(1,1))
plt.imshow(images[0].reshape(28,28),cmap = 'gray')
plt.show() # 输出图片
a = tf.constant([3,1,-3],dtype=tf.float32) # 定义常量a
# 使用softmax函数把元素值映射成0到1的概率
b = tf.nn.softmax(a) # nn:神经网络的缩写neural network
with tf.Session() as sess: # 打开一个会话层
print(sess.run(b)) # 经过softmax()的概率,将原来输出是3,1,-3通过softmax函数一作用,就映射成为(0,1)的值
print(sess.run(b).sum()) # 概率和,累和为1
[0.87887824 0.11894324 0.00217852]
1.0
# 定义tensorflow参数X,Y,W,b
X = tf.placeholder(dtype=tf.float32,shape=[None,784]) # None表示任意,表示样本数量
p = tf.placeholder(dtype=tf.float32,shape=[None,10]) # p目标值,真实分布;数字0到9有10个,于是输出的数组有10列
# 训练样本数据,一共有784个特征,所以矩阵X与W相乘时需要784行,
# 训练的目标数据,输出的预测值pred有10列,所以W有10列
# [None,784]*[784,10] -----> [None,10]
W = tf.Variable(np.zeros(shape=(784,10)),dtype=tf.float32) # W代表斜率,给变量赋初值为全0的矩阵
b = tf.Variable(np.zeros(shape=10),dtype=tf.float32) # 截距,给变量赋初值为全0的矩阵
# 创建线性模型
pred = tf.matmul(X,W) + b # Y=X*W+b
q = tf.nn.softmax(pred) # 将求解出来的pred转换成softmax 概率,q是预测出来,非真实分布
sub_key = tf.multiply(p,tf.log(1/q)) # 交叉熵p*log(1/q)
sub_sum = tf.reduce_sum(sub_key,axis=1) # axis=1 把每一列对应数值取出来相加得到一维数组A,比如A[0] = 取出每一列的第一个数相加
cost = tf.reduce_mean(sub_sum) # 求均值A数组是每一个样本的交叉熵,对A求均值
# cost = tf.reduce_mean(tf.reduce_sum(tf.multiply(p,tf.log(1/q)),axis = 1)) # 上面语句的整合
#创建梯度下降优化器,学习率0.01
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
初始化,训练样本并保存模型
# 初始化TensorFlow进行运算
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # 变量初始化
for i in range(100): # 训练55000次,每次取出100个样本
c_ = 0
for j in range(550):
X_train,y_train = mnist.train.next_batch(100) # 每次取100个样本
opt_, c = sess.run([optimizer,cost],
feed_dict={
X:X_train,
p:y_train
}
)
c_ += c # 对求得损失函数值求和
c_ = c_ / 550 # 求均值
if (i+1)%10 == 0: # 每10次循环打印一次
print('训练次数: %d,损失函数: %0.4f'%(i,c_))
saver = tf.train.Saver() # 保存模型
saver.save(sess,'./model/like_logistic/log_estimator') # 模型命名为log_estimator
训练次数: 9,损失函数: 0.3924
训练次数: 19,损失函数: 0.3454
训练次数: 29,损失函数: 0.3250
训练次数: 39,损失函数: 0.3129
训练次数: 49,损失函数: 0.3045
训练次数: 59,损失函数: 0.2983
训练次数: 69,损失函数: 0.2933
训练次数: 79,损失函数: 0.2894
训练次数: 89,损失函数: 0.2861
训练次数: 99,损失函数: 0.2832
# 计算准确率
with tf.Session() as sess:
saver = tf.train.Saver()
saver.restore(sess, './model/like_logistic/log_estimator')
y_ = sess.run(q, feed_dict={X: mnist.test.images}) # 预测
print(y_.shape)
(10000, 10)
y_ = tf.argmax(y_, axis=1) # 获取y_中每一行最大的概率
y_test = tf.argmax(mnist.test.labels, axis=1) # 获取真实分布中每一行最大的概率
e = tf.equal(y_, y_test) # 比较预测值和真实值
acc = tf.cast(e, dtype=np.float32) # 类型转换 True --> 1 False --> 0
accuracy = tf.reduce_mean(acc) # 求均值
print('对10000个测试数据,进行校验,准确率: %0.4f' % (sess.run(accuracy)))
对10000个测试数据,进行校验,准确率: 0.9222
- tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,不相等返回False,返回的值的矩阵维度和A是一样的
- tf.cast()函数的作用是执行 tensorflow 中张量数据类型转换,这里将整型变为浮点型。
原文:https://blog.youkuaiyun.com/lm_is_dc/article/details/81489458