码迷,mamicode.com
首页 > 其他好文 > 详细

Tensorflow Variable&Constant

时间:2019-07-01 00:51:10      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:ref   variable   全局变量   变量   res   简单   with   constant   shuf   

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)

Tensorflow Variable&Constant

标签:ref   variable   全局变量   变量   res   简单   with   constant   shuf   

原文地址:https://blog.51cto.com/5669384/2415624

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!