Tensorflow基础概念

Tensorflow基础概念

一、第一个简单计算样例

  • tensorflow是基于计算图的,因此,需要先建立图中的连接,然后运行图
  • 图的连接可以想象成做流程图,例子中a,b,result就是建立流程图中的各个节点以及连接方式
import tensorflow as tf
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=a+b
sess=tf.Session()
print(sess.run(result))
sess.close()
[3. 5.]

二、tensorflow图的概念

  • 把图当做一张稿纸,再上面进行节点布置,节点连接
  • 一个程序中可以定义多个图,图与图之间没有关联,通过tf.Graph()生成新的图。
  • 如果程序中没有手动定义图,系统会自动维护一个默认图,将所定义的节点以及连接方式放到默认图中
  • 上面就是一个默认图
  • 使用tf.get_default_graph()可以得到当前的默认图
  • 使用节点.graph(eg. a.graph)可以得到节点所在的图是哪一个
print(a.graph is tf.get_default_graph())
print(a.graph)
True
<tensorflow.python.framework.ops.Graph object at 0x7fa42417eb70>
t1=tf.Graph()#定义新图
with t1.as_default():
    b1=tf.constant([1.0,2.0],name='b1')
t2=tf.Graph()#定义新图
with t2.as_default():
    b2=tf.constant([9.0,8.0],name='b2')
with tf.Session(graph=t1) as sess1:
    print(sess1.run(b1))
with tf.Session(graph=t2) as sess1:
    print(sess1.run(b2))
[1. 2.]
[9. 8.]

三、数据模型(tensor的概念)

  • tensor意味张量,是tensorflow中的唯一一种数据格式,可以看做一种多维数组,但是其只作为一种数据的引用,没有保存具体数字,这里的“引用”的意思是保存计算过程。
  • 下面的例子中保存了对加法的引用,包括名称,维度和类型
  • a、b、result都是tensor,可以看出result并不是一个结果,它只是一个引用,用来表明连接关系。
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=tf.add(a,b,name='add')
print(result)
Tensor("add_8:0", shape=(2,), dtype=float32)

四、运行模型(回话(Session)的概念)

  • 创建完成tensor后,需要使用到Session模型运行图。
  • Session的使用分为创建,运行,最后关闭的过程(第一部分使用的方式)
  • 使用python中的with语句,可以自动关闭创建的模型(第二部分使用的方式)
  • 通过指定默认回话,然后通过tf.Tensor.eval函数计算张量的取值,也可以运行图(接下来使用)
  • 使用Session运行图时,需要指定最后的运行节点,其他相关节点会自动运行。
import tensorflow as tf
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=a+b
sess=tf.Session()
with sess.as_default(): ##指定默认会话
    print(result.eval())
[3. 5.]
###tensorflow还提供了一种将回话直接注册为默认回话的方式,以便更为方便的获取张量的值
import tensorflow as tf
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=a+b
sess=tf.InteractiveSession() ##这里就是
print(result.eval())
sess.close()
[3. 5.]

上面是基础的三个概念,下面是神经网络相关的概念在tensorflow中的应用。


五、参数与变量

  • tf.Variable()用来指定变量,就是用来保存和更新神经网络中的权重
  • 变量需要指定初值,指定初值可以使用随机数生成方式或者是常数生成方式
  • 变量在使用之前还需要进行初始化initializer
  • 还有一种变量生成方式是依靠其他变量生成新的变量
#变量的随机数生成方式
import tensorflow as tf
w1=tf.Variable(tf.random_normal([2,3],stddev=2))###产生一个2*3正态分布随机数,其标准差为2,均值为0
w2=tf.Variable(tf.random_uniform([2,3],minval=0,maxval=10))###产生0到10之间均匀分布的随机数
w3=tf.Variable(tf.truncated_normal([2,3],stddev=2))
###截断分布的正态分布随机数,
###如果随机出来的数值偏离平均值两个以上的标准差,就舍弃
w4=tf.Variable(tf.random_gamma([2,3],alpha=1,beta=2))###产生高斯分布的随机数


##变量的常数生成方式
w11=tf.Variable(tf.zeros([2,3],tf.int32))
w12=tf.Variable(tf.ones([2,3],tf.float32))
w13=tf.Variable(tf.fill([2,3],9))
w14=tf.Variable(tf.constant([2,3,4]))

###依靠其他变量生成变量的方式
w22=tf.Variable(w14.initialized_value()*2)


with tf.Session() as sess:
    #sess.run(w1.initializer)  ##变量的初始化过程
    #sess.run(w2.initializer)
    #sess.run(w3.initializer)
    #sess.run(w4.initializer)
#注释的部分是单个变量的初始化方式,使用下面一句话对所有的变量进行初始化
    sess.run(tf.global_variables_initializer())

    print(sess.run(w1))
    print(sess.run(w2))
    print(sess.run(w3))
    print(sess.run(w4))

    print(sess.run(w11))
    print(sess.run(w12))
    print(sess.run(w13))
    print(sess.run(w14))

    print(sess.run(w22))
[[ 0.11835031 -3.9811993   1.8016566 ]
 [ 0.08974894 -3.2420113  -2.340603  ]]
[[6.333414  3.649708  2.4709487]
 [9.512668  4.313182  2.9540467]]
[[ 0.8003709   0.7710215   1.1304915 ]
 [ 1.847279   -0.18616255  0.7370041 ]]
[[0.09745248 0.14700052 1.2569703 ]
 [1.5379981  0.06972744 0.24128863]]
[[0 0 0]
 [0 0 0]]
[[1. 1. 1.]
 [1. 1. 1.]]
[[9 9 9]
 [9 9 9]]
[2 3 4]
[4 6 8]

六、数据的输入(placeholder)

  • 在神经网络中,如果每次迭代进行的数据输入都定义为常量,将会在计算图中生成大量的节点,利用率低
  • tensorflow中使用placeholder占位符改善这种情况
  • 数据输入的一般方式如下
  • 这里插入一个matmul是矩阵相乘
import tensorflow as tf
w1=tf.Variable(tf.random_normal([2,3],stddev=2))
w2=tf.Variable(tf.random_normal([3,1],stddev=2))

x=tf.placeholder(tf.float32,shape=(1,2),name="input") ###这里定义了输入数据占位符,在训练的时候提供需要的数据。
# x=tf.placeholder(tf.float32,shape=(None,2),name="input") ###这里定义了输入数据占位符,在训练的时候提供需要的数据。
a=tf.matmul(x,w1)
y=tf.matmul(a,w2)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    result=sess.run(y,feed_dict={x:[[1,2]]})###通过feed_dict给占位符提供数据,注意这里并没有运行a,它是自动推导的结果
    #result=sess.run(y,feed_dict={x:[[1,2],[2,4],[1,2]]})###前面不确定行数
    print(result)
[[-5.0509615]]
  • 使用None代替占位符中的shape的行数,可以自由的确定输入数据的条数,可以同事确定多个样例的输出结果。
  • 上面注释掉的部分

七、损失函数的定义

  • 前面已经介绍了tensorflow最基础的三个概念(计算图、tensor张量、会话)
  • 之后介绍了神经网络中的参数与变量,然后介绍数据的输入方式
  • 这里介绍一下损失函数的定义

一种损失函数的定义方式
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_data*tf.log(y),reduction_indices=[1]))
reduction_indices=[1]将所有的行元素相加,得到一个列向量。
这里reduce_mean是取平均值。

八、tensorflow提供的反向传播算法(优化方法)

  • tensorflow提供了10中不同的优化算法
  • eg.
  • tf.train.GradientDescentOptimizer
  • tf.train.AdamOptimizer
  • tf.train.MomentumOptimer

九、构建简单的神经网络

  • 导入数据
  • 定义输入数据(x、y)与变量(w,b),如果有多层的话就需要定义多层的w和b
  • 定义数据与变量的连接方式(例如使用矩阵相乘)
  • 定义损失函数的表达形式
  • 选择方向传播算法
  • 运行程序
    栗子:
  • 与编程语言中的“hello,world”、嵌入式系统中的点亮流水灯,神经网络中与之地位类似的是手写字体识别(MNIST)。
### 数据导入
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)

print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)
####定义输入与变量

x_data=tf.placeholder(tf.float32,[None,784])
y_data=tf.placeholder(tf.float32,[None,10])

w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x_data,w) + b)

#定义损失函数

cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_data*tf.log(y),reduction_indices=[1]))
#reduction_indices=[1]##reduction_indices=[1]将所有的行元素相加,得到一个列向量。

###选择方向传播算法 
train=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) ####梯度下降法,学习率为0.5,最小化损失函数

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(1000):  ###设置迭代次数
        batch_xs,batch_ys=mnist.train.next_batch(100)  ###读入输入数据
        sess.run(train,feed_dict={x_data:batch_xs,y_data:batch_ys})

###在测试集上验证正确率
    correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_data,1))
    accuracy=tf.reduce_mean(tf.reduce_mean(tf.cast(correct_prediction,tf.float32)))
    acc1=sess.run(accuracy,feed_dict={x_data:mnist.train.images,y_data:mnist.train.labels})
    print(acc1)
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
(55000, 784) (55000, 10)
(10000, 784) (10000, 10)
(5000, 784) (5000, 10)
0.91096365

猜你喜欢

转载自blog.csdn.net/weixin_40100431/article/details/81840894