import tensorflow as tf #建立一個常量 op 一行二列 m1 = tf.constant([[3, 3]]) #建立一個常量 op 二行一列 m2 = tf.constant([[2], [3]]) # 建立一個矩陣乘法 op, 把 m1,m3 傳入 prod = tf.matmul(m1, m2) print(prod) # 調用 session 方法來執行矩陣乘法 op # sess = tf.Session() # res = sess.run(prod) # print(res) # sess.close() with tf.Session() as sess: res = sess.run(prod) print(res)
Tensor("MatMul_6:0", shape=(1, 1), dtype=int32) [[15]]
變量的使用python
import tensorflow as tf # 定義個變量 x = tf.Variable([1, 2]) # 定義個常量 a = tf.constant([3, 3]) # 增長個減法 op sub = tf.subtract(x, a) # 增長個加法 op add = tf.add(x, sub) # 初始化全局變量 init = tf.global_variables_initializer() with tf.Session() as sess: # 變量初始化 sess.run( init ) print('sub 的值',sess.run(sub)) print('add 的值',sess.run(add))
sub 的值 [-2 -1] add 的值 [-1 1]
用 for 循環,給一個值自增 1session
import tensorflow as tf # 能夠給變量定名字 state = tf.Variable(0, name='coun') # 自動加 1 new_value = tf.add(state, 1) # 賦值:把 new_value 的值給 state update = tf.assign(state, new_value) # 初始化全局變量 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run( init ) print( 'state 的值' ) print( sess.run(state) ) for _ in range(5): sess.run( update ) print( 'state 的值' ) print( sess.run(state) )
state 的值 0 state 的值 1 state 的值 2 state 的值 3 state 的值 4 state 的值 5