tensorflow中Session,Variable,PlaceHolder

Session 会话控制

import tensorflow as tf

#相当于定义两个常量
matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],[2]])

#矩阵相乘(matrix multiply),相当于 np.dot(m1,m2)
product = tf.matmul(matrix1,matrix2)

#第一种用Session
# sess = tf.Session()
# result = sess.run(product)
# print(result)

#第二种Session
with tf.Session() as sess:
    result = sess.run(product)
    print(result)

Variable变量

import tensorflow as tf
state = tf.Variable(0,name='counter')
one = tf.constant(1)

new_value = tf.add(state,one)
update = tf.assign(state,new_value)

#如果用到变量的话,一定要对所有变量进行出初始化
init = tf.initialize_all_variables()

with tf.Session() as sess:
    #一定要写
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

PlaceHolder传入值

import tensorflow as tf

#想在运行时再给他输入的值用placeholder,和feed_dict相连
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:[1]}))

猜你喜欢

转载自blog.csdn.net/weixin_43328054/article/details/106028359
今日推荐