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]]
变量的使用
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 循环,给一个值自增 1
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