tensorflow变量定义和赋值没有python那么简单,需要在session中run才能拿到结果

import tensorflow as tf

w = tf.Variable([[1.0,2.0]])
print(w)#<tf.Variable 'Variable:0' shape=(1, 2) dtype=float32_ref>
x = tf.Variable([[1.0],[0.5]])
print(x)#<tf.Variable 'Variable_1:0' shape=(2, 1) dtype=float32_ref>

y = tf.matmul(w,x)
print(y)#Tensor("MatMul:0", shape=(1, 1), dtype=float32)

#全局变量初始化
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(y.eval())#[[2.]]
    res = sess.run(y)
    print(res)#[[2.]]

洗牌

import tensorflow as tf

norm = tf.random_normal([2,3], mean=-1, stddev=4)

var_constant = tf.constant([[1,2,3],[4,5,6]])
shuff = tf.random_shuffle(var_constant)#洗牌

with tf.Session() as sess:
    var_norm = sess.run(norm)
    var_shuff = sess.run(shuff)
    print(var_norm)
    print(var_shuff)

小小的累加器

import tensorflow as tf

#累加器
state = tf.Variable(0)
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(10):
        var_update = sess.run(update)
        print(var_update)

加减乘除

import tensorflow as tf

var_1 = tf.constant(10.0)
var_2 = tf.constant(5.0)

add_op = tf.add(var_1, var_2)
div_op = tf.div(var_1, var_2)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(var_1)
    sess.run(var_2)
    var_add = sess.run(add_op)
    var_div = sess.run(div_op)
    print("add res : ", var_add)
    print("div res : ", var_div)