TensorFlow学习-- 变量Variables/ Fetch/ Feed

来源:互联网 发布:js获取style属性值 编辑:程序博客网 时间:2024/06/07 06:04

Variables:

参数是在图中有其固定的位置的,不能像普通数据那样正常流动。TensorFlow中将变量/Variables作为一个特殊的算子,可以返回它所保存的可变tensor的句柄。

#!/usr/bin/python# coding:utf-8# 变量Variablesimport tensorflow as tf# 创建一个变量,初始化为标量0state = tf.Variable(0, name="counter")# 创建一个op,其作用是使state增加1one = tf.constant(1)new_value = tf.add(state, one)# 调用run()执行表达式之前,assign并不会真正执行赋值操作update = tf.assign(state, new_value)# 变量必须先初始化init_op = tf.initialize_all_variables()with tf.Session() as sess:    sess.run(init_op)    print sess.run(state)    # 运行op,更新state,并打印state    for i in range(5):        sess.run(update)        print sess.run(state)

输出:

012345

Fetch:

为取回操作的输出内容, 可以在使用 Session 对象的 run() 调用 执行图时, 传入一些 tensor:

#!/usr/bin/python# coding:utf-8# Fetch 取回节点的输出内容import tensorflow as tfinput1 = tf.constant(2.0)input2 = tf.constant(6.0)input3 = tf.constant(8.0)add = tf.add(input3, input2)mul = tf.multiply(input1, add)with tf.Session() as sess:    result = sess.run([mul, add])    print result

输出:

[28.0, 14.0]

Feed:

Feed机制可以直接在图中插入一个 tensor,feed只在调用它的方法内有效,方法结束 feed 就会消失.

#!/usr/bin/python# coding:utf-8# feed 使用一个 tensor 值临时替换一个操作的输出结果import tensorflow as tfinput1 = tf.placeholder(tf.float32)input2 = tf.placeholder(tf.float32)input3 = tf.placeholder(tf.float32)add = tf.add(input3, input2)mul = tf.multiply(input1, add)# output = tf.multiply(input1, input2)with tf.Session() as sess:    print sess.run([mul, add], feed_dict={input1: [2.], input2: [6.], input3: [8.]})

输出:

[array([ 28.], dtype=float32), array([ 14.], dtype=float32)]
原创粉丝点击