TensorFLow-常见命令

目录

tf.placeholder

函数形式

为什么要用placeholder

 tf.matmul

1.tf.multiply()两个矩阵中对应元素各自相乘

2.tf.matmul()将矩阵a乘以矩阵b,生成a * b

程序示例

tf.name_scope和tf.variable_scope

1.tf.name_scope

2.tf.variable_scope

tf.truncated_normal

tf.summary.histogram

tf.summary

1、tf.summary.scalar

2、tf.summary.histogram

3、tf.summary.distribution

4、tf.summary.text

5、tf.summary.image

6、tf.summary.audio

7、tf.summary.merge_all

8、tf.summary.FileWriter

9、tf.summary.merge


tf.placeholder

函数形式

tf.placeholder(
    dtype,
    shape=None,
    name=None
)

参数:

dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
shape:数据形状。默认是None,就是一维值,也可以是多维(比如[2,3], [None, 3]表示列是3,行不定)
name:名称

为什么要用placeholder

        Tensorflow的设计理念称之为计算流图,在编写程序时,首先构筑整个系统的graph,代码并不会直接生效,这一点和python的其他数值计算库(如Numpy等)不同,graph为静态的,类似于docker中的镜像。然后,在实际的运行时,启动一个session,程序才会真正的运行。这样做的好处就是:避免反复地切换底层程序实际运行的上下文,tensorflow帮你优化整个系统的代码。我们知道,很多python程序的底层为C语言或者其他语言,执行一行脚本,就要切换一次,是有成本的,tensorflow通过计算流图的方式,帮你优化整个session需要执行的代码,还是很有优势的。

       所以placeholder()函数是在神经网络构建graph的时候在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符喂入数据。


代码示例:

import tensorflow as tf
import numpy as np
 
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:[3.], input2: [4.]})

import tensorflow as tf
import numpy as np
 
x = tf.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
 
with tf.Session() as sess:
    #print(sess.run(y))  # ERROR:此处x还没有赋值
    rand_array = np.random.rand(1024, 1024)
    print(sess.run(y, feed_dict={x: rand_array})) 

 tf.matmul

1.tf.multiply()两个矩阵中对应元素各自相乘

格式: tf.multiply(x, y, name=None) 
参数: 
x: 一个类型为:half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128的张量。 
y: 一个类型跟张量x相同的张量。  
返回值: x * y element-wise.  

注意: 
(1)multiply这个函数实现的是元素级别的相乘,也就是两个相乘的数元素各自相乘,而不是矩阵乘法,注意和tf.matmul区别。 
(2)两个相乘的数必须有相同的数据类型,不然就会报错。

2.tf.matmul()将矩阵a乘以矩阵b,生成a * b

格式: tf.matmul(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None) 
参数: 
a: 一个类型为 float16, float32, float64, int32, complex64, complex128 且张量秩 > 1 的张量。 
b: 一个类型跟张量a相同的张量。 
transpose_a: 如果为真, a则在进行乘法计算前进行转置。 
transpose_b: 如果为真, b则在进行乘法计算前进行转置。 
adjoint_a: 如果为真, a则在进行乘法计算前进行共轭和转置。 
adjoint_b: 如果为真, b则在进行乘法计算前进行共轭和转置。 
a_is_sparse: 如果为真, a会被处理为稀疏矩阵。 
b_is_sparse: 如果为真, b会被处理为稀疏矩阵。 
name: 操作的名字(可选参数) 
返回值: 一个跟张量a和张量b类型一样的张量且最内部矩阵是a和b中的相应矩阵的乘积。

 注意: 
(1)输入必须是矩阵(或者是张量秩 >2的张量,表示成批的矩阵),并且其在转置之后有相匹配的矩阵尺寸。 
(2)两个矩阵必须都是同样的类型,支持的类型如下:float16, float32, float64, int32, complex64, complex128。 
引发错误: 
ValueError: 如果transpose_a 和 adjoint_a, 或 transpose_b 和 adjoint_b 都被设置为真


程序示例

TensorFLow-常见命令

运行结果: 

TensorFLow-常见命令

注意: 在TensorFlow的世界里,变量的定义和初始化是分开的,所有关于图变量的赋值和计算都要通过tf.Session的run来进行。想要将所有图变量进行集体初始化时应该使用tf.global_variables_initializer。


tf.name_scope和tf.variable_scope

1.tf.name_scope

tf.name_scope 主要结合 tf.Variable() 来使用,方便参数命名管理。

'''
Signature: tf.name_scope(*args, **kwds)
Docstring:
Returns a context manager for use when defining a Python op.
'''
# 也就是说,它的主要目的是为了更加方便地管理参数命名。
# 与 tf.Variable() 结合使用。简化了命名
with tf.name_scope('conv1') as scope:
    weights1 = tf.Variable([1.0, 2.0], name='weights')
    bias1 = tf.Variable([0.3], name='bias')

# 下面是在另外一个命名空间来定义变量的
with tf.name_scope('conv2') as scope:
    weights2 = tf.Variable([4.0, 2.0], name='weights')
    bias2 = tf.Variable([0.33], name='bias')

# 所以,实际上weights1 和 weights2 这两个引用名指向了不同的空间,不会冲突
print weights1.name
print weights2.name

# 输出
conv1/weights:0
conv2/weights:0
# 注意,这里的 with 和 python 中其他的 with 是不一样的
# 执行完 with 里边的语句之后,这个 conv1/ 和 conv2/ 空间还是在内存中的。这时候如果再次执行上面的代码
# 就会再生成其他命名空间
with tf.name_scope('conv1') as scope:
    weights1 = tf.Variable([1.0, 2.0], name='weights')
    bias1 = tf.Variable([0.3], name='bias')

with tf.name_scope('conv2') as scope:
    weights2 = tf.Variable([4.0, 2.0], name='weights')
    bias2 = tf.Variable([0.33], name='bias')

print weights1.name
print weights2.name

# 输出
conv1_1/weights:0
conv2_1/weights:0

2.tf.variable_scope

tf.variable_scope() 主要结合 tf.get_variable() 来使用,实现 变量共享。

# 这里是正确的打开方式~~~可以看出,name 参数才是对象的唯一标识
import tensorflow as tf
with tf.variable_scope('v_scope') as scope1:
    Weights1 = tf.get_variable('Weights', shape=[2,3])
    bias1 = tf.get_variable('bias', shape=[3])

# 下面来共享上面已经定义好的变量
# note: 在下面的 scope 中的变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('v_scope', reuse=True) as scope2:
    Weights2 = tf.get_variable('Weights')

print Weights1.name
print Weights2.name
# 可以看到这两个引用名称指向的是同一个内存对象

# 输出
v_scope/Weights:0
v_scope/Weights:0

也可以结合 tf.Variable() 一块使用。

import tensorflow as tf
# 注意, bias1 的定义方式
with tf.variable_scope('v_scope') as scope1:
    Weights1 = tf.get_variable('Weights', shape=[2,3])
#     bias1 = tf.Variable([0.52], name='bias')

# 下面来共享上面已经定义好的变量
# note: 在下面的 scope 中的get_variable()变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('v_scope', reuse=True) as scope2:
    Weights2 = tf.get_variable('Weights')
    bias2 = tf.Variable([0.52], name='bias')

print Weights1.name
print Weights2.name
print bias2.name

# 输出
v_scope/Weights:0
v_scope/Weights:0
v_scope_1/bias:0

如果 reuse=True 的scope中的变量没有已经定义,会报错!!


tf.truncated_normal

tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。这个函数产生正太分布,均值和标准差自己设定。这是一个截断的产生正太分布的函数,就是说产生正太分布的值如果与均值的差值大于两倍的标准差,那就重新生成。和一般的正太分布的产生随机数据比起来,这个函数产生的随机数与均值的差距不会超过两倍的标准差,但是一般的别的函数是可能的。如:

import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
 
c = tf.truncated_normal(shape=[10,10], mean=0, stddev=1)
 
with tf.Session() as sess:
	print sess.run(c)
输出:
[[ 1.95758033 -0.68666345 -1.83860338  0.78213859 -1.08119416 -1.44530308
   0.38035342  0.57904619 -0.57145643 -1.22899497]
 [-0.75853795  0.48202974  1.03464043  1.19210851 -0.15739718  0.8506189
   1.18259966 -0.99061841 -0.51968449  1.38996458]
 [ 1.05636907 -0.02668529  0.64182931  0.4110294  -0.4978295  -0.64912242
   1.27779591 -0.01533993  0.47417602 -1.28639436]
 [-1.65927458 -0.364887   -0.45535028  0.078814   -0.30295736  1.91779387
  -0.66928798 -0.14847915  0.91875714  0.61889237]
 [-0.01308221 -0.38468206  1.34700036  0.64531708  1.15899456  1.09932268
   1.22457981 -1.1610316   0.59036094 -1.97302651]
 [-0.24886213  0.82857937  0.09046989  0.39251322  0.21155456 -0.27749416
   0.18883201  0.08812679 -0.32917103  0.20547724]
 [ 0.05388507  0.45474565  0.23398806  1.32670367 -0.01957406  0.52013856
  -1.13907862 -1.71957874  0.75772947 -1.01719368]
 [ 0.27155915  0.05900437  0.81448066 -0.37997526 -0.62020499 -0.88820189
   1.53407145 -0.01600445 -0.4236775  -1.68852305]
 [ 0.78942037 -1.32458341 -0.91667277 -0.00963761  0.76824385 -0.5405798
  -0.73307443 -1.19854116 -0.66179073  0.26329204]
 [ 0.59473759 -0.37507254 -1.21623695 -1.30528259  1.18013096 -1.32077384
  -0.59241474 -0.28063133  0.12341146  0.48480138]]

tf.summary.histogram

tf.summary.histogram(): 
输出一个直方图的Summary protocol buffer .

  • name:生成的节点名称.作为TensorBoard中的一个系列名称.
  • values:一个实数张量.用于构建直方图的值.
  • collections:图形集合键的可选列表.添加新的summary操作到这些集合中.默认为GraphKeys.SUMMARIES.
  • family: summary标签名称的前缀,用于在Tensorboard上显示的标签名称.(可选项)

详细参考:https://blog.****.net/akadiao/article/details/79551180 


tf.summary

其中tensorboard 作为一款可视化神器,可以说是学习tensorflow时模型训练以及参数可视化的法宝。

而在训练过程中,主要用到了tf.summary()的各类方法,能够保存训练过程以及参数分布图并在tensorboard显示。

转载自:https://www.cnblogs.com/lyc-seu/p/8647792.html

1、tf.summary.scalar

用来显示标量信息,其格式为:

tf.summary.scalar(tags, values, collections=None, name=None)
例如:tf.summary.scalar('mean', mean)

一般在画loss,accuary时会用到这个函数。

2、tf.summary.histogram

用来显示直方图信息,其格式为:

tf.summary.histogram(tags, values, collections=None, name=None) 

例如: tf.summary.histogram('histogram', var)

一般用来显示训练过程中变量的分布情况

3、tf.summary.distribution

分布图,一般用于显示weights分布

4、tf.summary.text

可以将文本类型的数据转换为tensor写入summary中:

例如:

text = """/a/b/c\\_d/f\\_g\\_h\\_2017"""
summary_op0 = tf.summary.text('text', tf.convert_to_tensor(text))

5、tf.summary.image

输出带图像的probuf,汇总数据的图像的的形式如下: ' tag /image/0', ' tag /image/1'...,如:input/image/0等。

格式:tf.summary.image(tag, tensor, max_images=3, collections=None, name=Non

6、tf.summary.audio

展示训练过程中记录的音频 

7、tf.summary.merge_all

merge_all 可以将所有summary全部保存到磁盘,以便tensorboard显示。如果没有特殊要求,一般用这一句就可一显示训练时的各种信息了。

格式:tf.summaries.merge_all(key='summaries')

8、tf.summary.FileWriter

指定一个文件用来保存图。

格式:tf.summary.FileWritter(path,sess.graph)

可以调用其add_summary()方法将训练过程数据保存在filewriter指定的文件中

Tensorflow Summary 用法示例:

tf.summary.scalar('accuracy',acc)                   #生成准确率标量图  
merge_summary = tf.summary.merge_all()  
train_writer = tf.summary.FileWriter(dir,sess.graph)#定义一个写入summary的目标文件,dir为写入文件地址  
......(交叉熵、优化器等定义)  
for step in xrange(training_step):                  #训练循环  
    train_summary = sess.run(merge_summary,feed_dict =  {...})#调用sess.run运行图,生成一步的训练过程数据  
    train_writer.add_summary(train_summary,step)#调用train_writer的add_summary方法将训练过程以及训练步数保存  

此时开启tensorborad:

  1. tensorboard --logdir=/summary_dir 

便能看见accuracy曲线了。

另外,如果我不想保存所有定义的summary信息,也可以用tf.summary.merge方法有选择性地保存信息:

9、tf.summary.merge

格式:tf.summary.merge(inputs, collections=None, name=None)

一般选择要保存的信息还需要用到tf.get_collection()函数

示例:

tf.summary.scalar('accuracy',acc)                   #生成准确率标量图  
merge_summary = tf.summary.merge([tf.get_collection(tf.GraphKeys.SUMMARIES,'accuracy'),...(其他要显示的信息)])  
train_writer = tf.summary.FileWriter(dir,sess.graph)#定义一个写入summary的目标文件,dir为写入文件地址  
......(交叉熵、优化器等定义)  
for step in xrange(training_step):                  #训练循环  
    train_summary = sess.run(merge_summary,feed_dict =  {...})#调用sess.run运行图,生成一步的训练过程数据  
    train_writer.add_summary(train_summary,step)#调用train_writer的add_summary方法将训练过程以及训练步数保存  

使用tf.get_collection函数筛选图中summary信息中的accuracy信息,这里的

tf.GraphKeys.SUMMARIES  是summary在collection中的标志。

当然,也可以直接:

acc_summary = tf.summary.scalar('accuracy',acc)                   #生成准确率标量图  
merge_summary = tf.summary.merge([acc_summary ,...(其他要显示的信息)])  #这里的[]不可省

 如果要在tensorboard中画多个数据图,需定义多个tf.summary.FileWriter并重复上述过程。