1、placeholder机制:解决了在有限的输入节点上实现高效地接收大量数据的问题。
用于在会话运行时动态提供输入数据;
import tensorflow as tf
a = tf.placeholder(tf.float32, shape=(2), name='input')
b = tf.placeholder(tf.float32, shape=(2), name='input')
result = a + b
print(result)
with tf.Session() as sess:
sess.run(result, feed_dict={a:[1, 2], b:[3, 4]})
print(result)
palceholder (dtype, shape, name)
run (self, fetches, feed_dict, options, run_metadata)
2、Variable创建变量:
1)、随机数设置:常用满足正态分布的随机数来初始化神经网络中的参数。
weight = tf.Variable(tf.random_normal([3,4], stddev=1))
#random_normal(shape, mean, stddev, dtype, seed, name) #正态分布
#truncted_normal(shape, mean, stddev, dtype, seed, name) #正态分布,但随机值偏离平均值超2个标准差,则重新随机
#random_uniform(shape, mean, stddev, dtype, seed, name) #平均分布
#random_gamma(shape, mean, stddev, dtype, seed, name) #Gamma分布
2)、常用生成函数:
tf.zeros([2,3], int32)
tf.ones([2,3], int32)
tf.fill([2,3], 4) #产生数组[[4, 4, 4], [4, 4, 4]]
tf.constant([1, 2, 3]) #产生数组[1, 2, 3]
3)、初始化:
init_op = tf.global_variables_initializer()
sess.run(init_op)
具体应用:
import tensorflow as tf
x = tf.constant([[1.0, 2.0]])
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(y))
3、管理变量空间:variable_scope()
1)、get_variable()
z = tf.get_variable("a", shape=[1], initializer=tf.constant_initializer(1.0))
get_variable(name, shape, dtype, initializer, ...)
2)、variable_scope()
import tensorflow as tf
a = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.0))
print(a.name)
#a:0 0为生成这个变量运算的第一个结果
with tf.variable_scope('one'):
a2 = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.0))
print(a2.name)
#输出one/a:0
with tf.variable_scope('one'):
with tf.variable_scope('two'):
a4 = tf.get_variable('a', [1])
print(a4.name)
#one/two/a:0
b = tf.get_variable('b', [1])
print(b.name)
#退出了two的命名空间
#one/b:0
with tf.variable_scope('', reuse=True):
a5 = tf.get_variable('one/two/a', [1])
print(a5 == a4)
#True