TensorFlow Session&&Variable&&PlaceHolder

Session

会话持有并管理tensorflow程序运行时的所有资源

session 是 Tensorflow 为了控制,和输出文件的执行的语句. 运行 session.run() 可以获得你要得知的运算结果。

import tensorflow as tf
import numpy as np

#定义常量矩阵
matrix1 = tf.constant([[3, 4]])
matrix2 = tf.constant([[5], [5]])
result = tf.matmul(matrix1,matrix2)

#使用上下文管理器方式不需要写sess.close()函数
with tf.Session() as sess:
    print(sess.run(result))


Variable

import tensorflow as tf
import numpy as np

#定义变量和常量
state = tf.Variable(0, name='counter')
one = tf.constant(1)

# 定义加法步骤 (注: 此步并没有直接计算)
new_value = tf.add(one, state)
# 将 State 更新成 new_value
update = tf.assign(state, new_value)



#激活所有变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)

    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
#输出:
#1
#2
#3

PlaceHolder

placeholder 是 Tensorflow 中的占位符,暂时储存变量.
Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(***, feed_dict={input: **}).
需要传入的值放在了feed_dict={} 并一一对应每一个 input. placeholder 与 feed_dict={} 是绑定在一起出现的。
import tensorflow as tf

#需要定义placeholder的type,一般为float32
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

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

import tensorflow as tf

#需要定义placeholder的type,一般为float32
input1 = tf.placeholder(tf.float32, [2, 2])
input2 = tf.placeholder(tf.float32, [2, 2])
output = tf.multiply(input1, input2)

with tf.Session() as sess:
    print(sess.run(output, feed_dict={input1: [[1, 2], [3, 4]], input2: [[2, 9], [5, 6]]}))
[[  2.  18.]
 [ 15.  24.]]




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值