TensorFlow 基础(一)
2018-08-05 本文已影响0人
酷酷滴小爽哥
1 . 两种使用 Session 的方法:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
matrix1 = tf.constant([[3, 3]])
matrix2 = tf.constant([[2], [2]])
product = tf.matmul(matrix1, matrix2)
# method1 需要 close
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# method2 不需要 close
with tf.Session() as sess:
result2 = sess.run(product)
print(result2)
2 . 使用 placeholder 传入值
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
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:[[2,3]], input2:[[3], [4]]}))
3 . 变量的使用 Variable
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
state = tf.Variable(3, name='counter')
print(state.name)
one = tf.constant(1)
new_value = tf.add(state, one)
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))