版权声明: https://blog.csdn.net/Dorothy_Xue/article/details/83903763
1. tf.Session() 与 tf.InteractiveSession()
用tf.Seesino()构建会话,要定义好所有的operation之后,才能构建会话
用tf.InteractiveSession()构建会话,可以先构建一个会话再定义operation,适用于交互式环境。
2. tf.ConfigProto()
创建session时,对session进行参数设置
with tf.Session(config=tf.ConfigProto(...),...)
#tf.ConfigProto()的参数
log_device_placement=True #是否打印设备分配日志
allow_soft_placement=True #如果你指定的设备不存在,允许TF自动分配设备
tf.ConfigProto(log_device_placement=True,allow_soft_placement=True)
3. tf.get_variable() 与 tf.variable_scope()
tf.get_variable() 用于创建或获取变量
(1)用于创建变量时,与tf.Variable()功能基本相同
v=tf.get_variable("v",shape=[1],initializer.constant(1.0))
v=tf.Variable(tf.constant(1.0,shape=[1]),name="v")
- 相同点:创建变量的过程基本类似,调用tf.Variable()时所用的维度以及初始化的参数与tf.get_variable()基本类似
- 不同点:指定变量名称的参数不同,对于tf.Variable()变量名称是一个可选的参数,通过name="v"的形式给出;而tf.get_variable()中变量名是必须要有的参数,函数根据变量名创建或者获取参数。
(2)用于获取变量时
先通过tf.variable_scope()生成一个上下文管理器,并指明需求的变量在这个上下文管理器中
然后直接用tf.get_variable()获取已经生成的变量
#通过tf.variable_scope()控制tf.get_variable(),以获取或创建变量
#名为“zx”的上下文控制器
with tf.variable_scope("zx"):
v=tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))#在“zx”中定义名为“v”的变量
with tf.variable_scope("zx"):
v=tf.get_variable("v",[1])#通过tf.get_variable()在“zx”中创建“v”变量,失败,因为在“zx”中已经有一个了
如果上下文管理器中已经有了想要的变量,想要通过tf.get_variable()获取它,可通过设置参数reuse的值为True来获取:
with tf.variable_scope("zx",reuse=True):
v1=tf.get_variable("v",[1])
print v==v1#输出为True
(3)其他
- tf.variable_scope()只能用于获取已经创建了的变量
- 若tf.variable_scope()参数reuse=False或reuse=None创建上下文管理器,则tf.get_variable()可用于创建新变量,但不可创建已有变量(即同名变量)
4. tf.contrib.layers.xavier_initializer()
返回一个用于初始化权重的初始化程序“Xavier”,用来保持每一层梯度大小基本相同
xavier_initializer(
uniform=True,
seed=None,
dtype=tf.float32
)
参数:
- uniform:使用uniform或者normal分布进行随机初始化
- seed:用来生成随机数的种子
- dtype:只支持浮点数
返回值:
- 初始化的权重矩阵
5. tf.placeholder()
通式:tf.placeholder(dtype,shape=None,name=None)
可将这个函数中的值当作形参,在具体用到的时候再给它们赋值
参数:
- dtype::数据类型,通常是dtype=tf.float32,tf.float64浮点类型
- shape:数据形状,也就是数据维度,默认为None
- name:名称
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}))#输出成功
返回:tensor类型
6. tf.train.AdamOptimizer()
实现了Adam算法的优化器
7. tf.nn.xw_plus_b()
tf.nn.xw_plus_b((x,weights)+biases)相当于tf.matmul(x,weights)+biases
import tensorflow as tf
x=[[1, 2, 3],[4, 5, 6]]
w=[[ 7, 8],[ 9, 10],[11, 12]]
b=[[3,3],[3,3]]
res1=tf.nn.xw_plus_b(x,w,[3,3])
res2=tf.matmul(x,w)+b
init_op=tf.initializer_all_variables()
with tf.Session() as sess:
#运行初始化操作
sess.run(init_op)
print(sess.run(res1))
print(sess.run(res2))
输出:
[[ 61 67]
[142 157]]
[[ 61 67]
[142 157]]
8. feed_dict
给使用placeholder创建出来的tensor赋值。
未完待续