0. 变量与常量
单元 | 定义 | 示例 |
---|---|---|
占位符 | 相当于先占用内存中相应大小的单元,会话Session中计算时使用feed_dict传入数据 | train_labels = tf.placeholder ( tf.int32,shape = [batch_size, 1]) |
常量 | `定义一个常量有着恒定不变的值 | valid_data = tf.constant( valid_example, dtype = tf.int32) |
变量 | 变量的值在设置完成后可改变,但其数据类型和形状无法改变,如CNN中权重参数 | embedding = tf.Variable( tf.random_uniform( [vocabulary_size, embedding_size] -1.0, 1.0) |
1. 常见数据的初始化
(1)tf.zeros()
(2) tf.ones()
(3)tf.random_normal()
(4)tf.truncated_normal()
(5)tf.random_uniform()
上述变量初始化函数的使用在我的另一篇博文 TensorFlow常见变量初始化中有具体描述
2. Graph
所有不同的变量及对变量的操作均定义保存在图(Graph)中。
graph = tf.Graph() #定义一个图(Graph)
with graph.as_default(): #设置这个图作为默认图
#定义Graph中的数据和对数据的操作(如:特征的矩阵乘法、loss的计算、优化等操作)
#tf.placeholder定义的变量须在Session对数据进行操作的时候利用feed_dict传入值(如:训练数据、训练数据的标记等均需在session.run()的时候使用feed_dict传入)
train_input = tf.placeholder(tf.int32, shape = [batch_size])
train_label = tf.placeholder(tf.int32, shape = [batch_size, 1])
valid_data = tf.constant( valid_example, dtype = tf.int32)
embedding = tf.Variable( tf.random_uniform( [vocabulary_size, embedding_size] -1.0, 1.0)
loss = tf.reduce_mean(
tf.nn.nce_loss(weights =nce_weights,
biases=nce_bbiases,
labels = train_labels,
inputs = embed,
num_sampled = num_sampled,
num_classes = vocabublary_size))
optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
init = tf.global_variables_initializer()
3. Session
定义好图(Graph)中的变量和操作后,在会话(Session)中运行即真正执行图(Graph)中定义的某些操作l来运行整个计算图。
会话开启的两种方式
(1)session = tf.Session()
(2)with tf.Session() as session:
with tf.Session(graph = graph) as session:
#变量在运行前先进行初始化操作
init.run()
#通过tf.placeholder定义的数据,通过feed_dict以字典形式传入值
feed_dict = {train_inputs: batch_inputs, train_labels:batch_labels}
_, loss_val = session.run([optimizer, loss],feed_dict=feed_dict)