tensorflow学习(3)variable和placeholder使用.

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31214097/article/details/85062135

在tensorflow中,定义了某字符串是变量,它才是变量

定义的语法

state = tf.Variable()

import tensorflow as tf

state = tf.Variable(0, name='counter')

# 定义常量 one
one = tf.constant(1)

# 定义加法步骤 (注: 此步并没有直接计算)
new_value = tf.add(state, one)

# 将 State 更新成 new_value
update = tf.assign(state, new_value)

如果在tensorflow中设定了变量,那么变量的初始化是非常重要的!!!,所以定义了变量之后,一定要进行初始化操作.,

 init = tf.initialize_all_variables() .

到这里变量还是没有被激活,需要在sess里面,sess.run(init)后,进一步激活init这一步.

# 如果定义 Variable, 就一定要 initialize
# init = tf.initialize_all_variables() # tf 马上就要废弃这种写法
init = tf.global_variables_initializer()  # 替换成这样就好
 
# 使用 Session
with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

注意:print(state)是不起任何作用的!

一定要把sess的指针指向state后再进行print 才能得到想要的值.

placeholder的使用.

placeholder是tensorflow中的占位符,是用于暂时存储变量的.

tensorflow如果想要从外部传入data,那就需要使用tf.placeholder(),然后以如下形式将数据进行传入.

sess.run(***, feed_dict={input: **}).

示例:首先定义占位符和参数值:

import tensorflow as tf

#在 Tensorflow 中需要定义 placeholder 的 type ,一般为 float32 形式
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

# mul = multiply 是将input1和input2 做乘法运算,并输出为 output 
ouput = tf.multiply(input1, input2)

接下来,传值的工作交给了sess.run(),需要传入的值放在了feed_dict = {}里面,并一一对应input的placeholder的值.

with tf.Session() as sess:
    print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))

猜你喜欢

转载自blog.csdn.net/qq_31214097/article/details/85062135