Tensorflow 学习笔记- tensor的声明

来源:互联网 发布:生化危机6mac 编辑:程序博客网 时间:2024/05/18 03:07
  1. tf 声明Variable变量时,在使用前需要对变量进行初始化,才可运行tensor
import tensorflow as tf// case onea = tf.Variable(4, tf.int16)b = tf.Variable([[4,5], [3,5]])c = tf.add(a,b)// init the variableinit =tf.global_variables_initializer()with tf.Session() as sess: // the session will close automatically    sess.run(init) // must do it firstly    sess.run(c)// case twostate = tf.Variable(0, name="counter")one = tf.constant(1)new_value = tf.add(state, one)update = tf.assign(state, new_value)init_op = tf.global_variables_initializer()with tf.Session() as sess:    sess.run(init_op)    print sess.run(state)    for _ in range(3):        sess.run(update)        print sess.run(state)

代码中assign() 操作是图所描绘的表达式的一部分, 正如add() 操作一样. 所以在调用run() 执行表达式
之前, 它并不会真正执行赋值操作.

2.Fetch
为了取回操作的输出内容, 可以在使用Session 对象的run() 调用 执行图时, 传入一些 tensor, 这些 tens
or 会帮助你取回结果.

input1 = tf.constant(3.0)input2 = tf.constant(2.0)input3 = tf.constant(5.0)intermed = tf.add(input2, input3)mul = tf.mul(input1, intermed)with tf.Session() as sess:    result = sess.run([mul, intermed])    print result# 输出:# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

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

3.Feed
Tensorflow 提供feed机制,该机制可以临时替代graph中任意操作中的tensor,直接插入一个tensor。可以提供feed数据作为run()调用的参数。因此,feed只有在调用它的method内有效。最常见的例子事将某些特殊的操作指定为“feed”操作,标记的方法是使用tf.placeholder()为这些操作创建占位符。

input1 = tf.placeholder(tf.float32)input2 = tf.placeholder(tf.float32)output = tf.add(input1, input2)with tf.Session() as sess:    print sess.run([output], feed_dict={input1:[7], input2:[3]})
阅读全文
1 0