tessorflow基本语法

    xiaoxiao2022-07-13  171

    文章目录

    tessorflow基本语法占位符、字典、数值运算shape函数perm函数tf.random_normal()函数矩阵相乘、相减、初始化变量FetchFeedtf.strided_slice函数一维数组二维数组三维数组 tf.nn.in_top_k的用法实现简单可视化

    tessorflow基本语法

    占位符、字典、数值运算

    import tensorflow as tf #定义‘符号’变量,也称为占位符 a = tf.placeholder("float") b = tf.placeholder("float") y = tf.multiply(a, b) # 构造一个op节点,每一个运算操作opretion作为一个节点 sess = tf.Session() # 建立会话 # 运行会话,输入数据,并计算节点,同时打印结果 print(sess.run(y, feed_dict={a: 3, b: 3})) # 任务完成, 关闭会话 sess.close()

    shape函数

    shape函数是numpy.core.fromnumeric中的函数,它的功能是读取矩阵的长度。shape的输入参数可以是一个整数(表示维度),也可以是一个矩阵

    1)参数是一个数时,返回空: >>> import numpy as np >>> np.shape(0) ()2)参数是一个一维矩阵: >>> np.shape([1]) (1,) >>> np.shape([1,2]) (2,)3)参数是一个二维矩阵: >>> np.shape([[1],[2]]) (2, 1) >>> np.shape([[1,1],[2,2],[3,3]]) (3, 2)4)参数是一个三维矩阵: 1. >>> a=np.array([[[1, 2, 3],[4, 5, 6]],[[7, 8, 9],[10, 11, 12]]]) >>> a.shape (2, 2, 3) >>> a array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]]) 2. >>> a=np.array([[[1, 2, 3],[4, 5, 6]],[[7, 8, 9],[10, 11, 12]],[[7, 8, 9],[10, 11, 12]]]) >>> a array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]], [[ 7, 8, 9], [10, 11, 12]]]) >>> a.shape (3, 2, 3) conclusion:三维数组中,第一位数字表示二维数组的个数,第二位数字表示二维数组的行数,第三位数字表示二维数组的列数 (5)直接用.shape可以快速读取矩阵的形状,使用shape[0]读取矩阵行数,shape[1]读取矩阵列数 >>> a=np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a.shape (3, 3) >>> a.shape[0] 3 >>> a.shape[1] 36)但是当某一维度长度不一致时,读取所有维度时则不能读出长短不一致的维度 >>> a=np.array([[1,2,3],[4,5]]) >>> a array([[1, 2, 3], [4, 5]], dtype=object) >>> a.shape (2,) >>> a.shape[0] 2 >>> a.shape[1] Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> a.shape[1] IndexError: tuple index out of range

    perm函数

    (1)对于二维数组,perm=[0,1],0代表二维数组的行,1代表二维数组的列。perm[1,0]代表将数组的行和列进行交换,代表矩阵的转置(2)对于三维数组,perm=[0,1,2],0代表三维数组的高(即为二维数组的个数),1代表二维数组的行,2代表二维数组的列。tf.transpose(x, perm=[1,0,2])代表将三位数组的高和行进行转置

    import tensorflow as tf import numpy as np # 设计一个3维数组 x = tf.placeholder('float') # 加法器 y = tf.add(x, x) # 随机产生一个2*2 数组 rand_array1 = np.random.rand(2, 2) # 两个中括号,二维 # print(rand_array1) rarray = [rand_array1] # 又加中括号,二维变三维 # print(rarray) with tf.Session() as sess: # 使用with代码块可以自动关闭sess对话 print(sess.run(y, feed_dict={x: rarray})) sess = tf.Session() x = [[1, 2, 3], [4, 5, 6]] t1 = tf.transpose(x) # transpose(x)转置 t2 = tf.transpose(x, perm=[1, 0]) # perm=[1, 0],将数组的行和列进行交换 x = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]] # x.shape=(2,2,3),表示两个2*3的二维数组 t3 = tf.transpose(x, perm=[0, 2, 1]) # 表示将数组的行和列进行交换 print(sess.run(t1)) print() print(sess.run(t2)) # t1和t2结果一样 print() print(sess.run(t3)) sess.close()

    可以将sess = tf.Session()和sess.close()去掉,将后续的代码对齐到print(…),也可实现相同的效果。

    tf.random_normal()函数

    tf.random_rand(3,2)返回一个随机值介于0~1之间的三行两列的数组 tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)正态(高斯)分布 shape形状,必选 mean均值,默认为0 stddev标准差,默认为1 dtype数据类型,默认为tf.float32 seed随机数种子,是一个整数,设置以后,每次生成的随机数都一样 name操作的名称

    #产生服从正态分布的数组 # tf.random_normal()正态分布函数 tf.random_uniform()均匀分布函数 # -*- coding: utf-8 -*-) import tensorflow as tf #shape为(2,2),标准差为1,随机种子为1 w1 = tf.Variable(tf.random_normal([2, 2], stddev=1, seed=1)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #变量w1声明之后并没有被赋值,需要在Session中调用run(tf.global_variables_initializer())方法初始化之后才会被具体赋值。 # sess.run(tf.initialize_all_variables()) #比较旧一点的初始化变量方法 print(w1) #获取w1的形状和数据类型等属性信息 print(sess.run(w1)) # 获取w1的值需要调用sess.run(w1)方法

    疑问:结果:[[-0.8113182 1.4845988 ] [ 0.06532937 -2.4427042 ]]的标准差等于1.6439 疑问解决:其实,在生成均值为0,方差为1的随机数时,matlab要遵守一定的算法,这个算法保证在数据量非常大时,其均值为0,方差为1,但并不能保证数据量非常小时,计算其均值和方差也是0和1

    MATLAB举例:R = random('Normal',0,1,2,4): 生成期望为 0,标准差为 1 的(2 行 4 列)2× 4 个正态随机数 R = random('Normal',0,1,2,4) >> std2(R) 1.0619 R = random('Normal',0,1,2000,4000) >> std2(R) 0.9998 可见随着数据量的增大,偏差值越趋于真实值。

    标准差MATLAB公式: (1)一维数组 (1)二维数组 std2(A) 补充:

    import tensorflow as tf w1 = tf.random_normal((5,)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(w1))

    运行结果:[-0.28473374 0.36357746 -0.04123257 -0.7963872 0.41197917] w1 = tf.random_normal((5,))改成w1 = tf.random_normal((1,5)) 运行结果:[[-0.17727162 -0.8383046 0.22584556 0.04784792 0.64250875]] w1 = tf.random_normal((1,5))改成w1 = tf.random_normal([1,5]) 运行结果:[[-0.8113182 1.4845988 0.06532937 -2.4427042 0.0992484 ]] conclusion:

    shape的括号可以是小括号或者中括号。shape为(5,),表示一行5列的一维向量空间;shape为(1,5),表示一行5列的二维向量空间向量维数:向量分量的个数。向量空间的维数(不能少于两个):向量空间是由好多个向量组成的空间

    矩阵相乘、相减、初始化

    sess = tf.InteractiveSession()与 sess = tf.Session() 区别:tf.InteractiveSession()是一种交互式的session方式,它让自己成为了默认的session。用户在不需要指明用哪个session运行的情况下,就可以运行起来。run()和eval()函数可以不指明session。它允许变量不需要使用session就可以产生结构。

    # 进入一个交互式 TensorFlow 会话. import tensorflow as tf sess = tf.InteractiveSession() x = tf.Variable([1.0, 2.0]) a = tf.constant([3.0, 3.0]) # 使用初始化器 initializer op 的 run() 方法初始化 'x' x.initializer.run() # 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果 sub = tf.subtract(x, a) print(sub.eval()) # ==> [-2. -1.] #矩阵相乘 import tensorflow as tf sess = tf.InteractiveSession() #建立两个矩阵变量w1和w2 w1 = tf.Variable(tf.random_normal([2,3],mean=1.0, stddev=1.0)) w2 = tf.Variable(tf.random_normal([3,1],mean=1.0, stddev=1.0)) #定义一个二维的常量矩阵,注意:这里不是一维数组 x = tf.constant([[0.7, 0.9]]) # print(sess.run(x)) #初始化全局变量,这里由于只有w1和w2没有被初始化(之前只是定义了w1和w2的tensor,并没有被初始化),故这一步只会初始化w1和w2. tf.global_variables_initializer().run() #在完全构建好模型并加载之后才运行这个操作 #tf.initialize_all_variables().run() #这种写法也可,官方推荐使用上面的写法 #计算矩阵相乘a=x*w1 a = tf.matmul(x ,w1) #矩阵相乘tf.matmul(a,b) #计算矩阵相乘y=a*w2 y = tf.matmul(a, w2) #输出计算结果,是一个1行1列的二维矩阵 print(y.eval()) print(sess.run(y)) #结果与上行相同 import tensorflow as tf # 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点 # 加到默认图中 # 构造器的返回值代表该常量 op 的返回值. matrix1 = tf.constant([[3., 3.]]) # 创建另外一个常量 op, 产生一个 2x1 矩阵. matrix2 = tf.constant([[2.],[2.]]) # 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入. # 返回值 'product' 代表矩阵乘法的结果. product = tf.matmul(matrix1, matrix2) # 启动默认图. sess = tf.Session() # 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数. # 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回 # 矩阵乘法 op 的输出. # 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的. # 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行. # 返回值 'result' 是一个 numpy `ndarray` 对象. result = sess.run(product) print(result) # ==> [[ 12.]] # 任务完成, 关闭会话. sess.close() import tensorflow as tf with tf.Session() as sess: with tf.device("gpu:1"): matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([[2.],[2.]]) product = tf.matmul(matrix1, matrix2) print(sess.run(product))

    疑问:最后一个模块有bug 解决:"gpu:1"改为"cpu:0"可解决问题,因为我所运行的电脑没有gpu,只有一个cpu,而python是从0开始计数的。

    变量

    # 创建一个变量, 初始化为标量 0. import tensorflow as tf state = tf.Variable(0, name="counter") # 创建一个 op, 其作用是使 state 增加 1 one = tf.constant(2) new_value = tf.add(state, one) update = tf.assign(state, new_value) # 启动图后, 变量必须先经过`初始化` (init) op 初始化, # 首先必须增加一个`初始化` op 到图中. init_op = tf.initialize_all_variables() # 启动图, 运行 op with tf.Session() as sess: # 运行 'init' op sess.run(init_op) # 打印 'state' 的初始值 # print(sess.run(state)) # 运行 op, 循环3次,更新 'state', 并打印 'state' for j in range(3): sess.run(update) print(sess.run(state))

    结果: 2 4 6

    Fetch

    需要获取的多个 tensor 值,在 op 的一次运行中一起获得(而不是逐个去获取 tensor)

    # 创建一个变量, 初始化为标量 0. import tensorflow as tf input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) intermed = tf.add(input2, input3) mul = tf.multiply(input1, intermed) with tf.Session() as sess: result = sess.run([mul, intermed]) print(result)

    Feed

    feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为 run() 调用的参数. feed 只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为 “feed” 操作, 标记的方法是使用 tf.placeholder() 为这些操作创建占位符.

    # 创建一个变量, 初始化为标量 0. import tensorflow as tf input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.multiply(input1, input2) with tf.Session() as sess: print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

    tf.strided_slice函数

    一维数组

    import tensorflow as tf data = [1,2,3,4,5,6,7,8] x = tf.strided_slice(data,[0],[4]) y = tf.strided_slice(data,[1],[5]) with tf.Session() as sess: print(sess.run(x)) print(sess.run(y))

    结果 [1 2 3 4] [2 3 4 5] tf.strided_slice(data,[a],[b])函数的三个值为:原数据,起始位置a,终点位置b,即a<=x<b

    二维数组

    import tensorflow as tf data = [[1,2,3,4,5,6,7,8],[11,12,13,14,15,16,17,18]] x1 = tf.strided_slice(data,[0,0],[1,4]) x2 = tf.strided_slice(data,[0,1],[1,4]) x3 = tf.strided_slice(data,[1,0],[2,4]) x4 = tf.strided_slice(data,[1,0],[1,4]) x5 = tf.strided_slice(data,[1,1],[2,5]) with tf.Session() as sess: print(sess.run(x1)) print(sess.run(x2)) print(sess.run(x3)) print(sess.run(x4)) print(sess.run(x5))

    结果: [[1 2 3 4]] [[2 3 4]] [[11 12 13 14]] [] [[12 13 14 15]]

    tf.strided_slice(data,[a1,a2],[b1,b2])函数, a1代表索引为a1的一维数组 a2代表索引为a1的一维数组中,索引为a2的数值 b1代表第b1行 b2代表第b1行中索引为b2的数值

    三维数组

    import tensorflow as tf data = [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]] x = tf.strided_slice(data,[2,0,0],[3,2,3]) with tf.Session() as sess: print(sess.run(x))

    结果: [[[5 5 5] [6 6 6]]] 以三维数组中索引为2的二维数组,索引为0的一维数组,索引为0的数字开始,以三维数组中第3个二维数组中,第2个一维数组中,索引为3的数字结束

    tf.nn.in_top_k的用法

    目的:用于计算预测的结果和实际结果的是否相等,返回一个bool类型的张量 tf.nn.in_top_k(prediction, target, K): prediction就是表示你预测的结果,大小就是预测样本的数量乘以输出的维度,类型是tf.float32等。 target就是实际样本类别的标签,大小就是样本数量的个数。 K表示每个样本的预测结果的前K个最大的数的索引里面是否含有target中的值。一般都是取1。 K=1,表示每个样本的预测结果的最大数的索引是否与target中的值(索引值)相等。

    import tensorflow as tf A = [[0.8, 0.6, 0.3], [0.1, 0.6, 0.4]] B = [1, 1] out = tf.nn.in_top_k(A, B, 1) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) print(sess.run(out))

    输出: [False True]

    解释:因为A张量里面的第一个元素的最大值的标签是0,第二个元素的最大值的标签是1.。但是实际的确是1和1.所以输出就是False 和True。如果把K改成2,那么第一个元素的前面2个最大的元素的位置是0,1,第二个的就是1,2。实际结果是1和1。包含在里面,所以输出结果就是True 和True.如果K的值大于张量A的列,那就表示输出结果都是true

    实现简单可视化

    import tensorflow as tf print('version:', tf.__version__) foo = tf.Variable(3, name='foo') bar = tf.Variable(2, name='bar') result = tf.add(foo, bar, name='add') #初始化变量 init = tf.global_variables_initializer() #启动图 (graph) sess = tf.Session() sess.run(init) print('result:', sess.run(result)) train_writer = tf.summary.FileWriter('/tmp/tensorflow/add/logs/testTf/train', sess.graph) #结果存放路径

    会发现这个log文件按指定位置存在: copy此路径:tensorboard --logdir=C:\tmp\tensorflow\add\logs\testTf\train 粘贴到terminal中: 复制http://susan-HP:6006 到谷歌浏览器,即可看到gragh

    由于版本的更新,可能会出现以下问题,下面给出解决方案:

    粘贴到terminal中可能出现以下错误 解决方案:找到manager.py, 更改代码 FutureWarning: Conversion of the second argument of issubdtype from float to… 解决方案:timinal输入pip install h5py==2.8.0rc1 sd-20190404yevy 拒绝了我们的连接请求
    最新回复(0)