tensorflow中计算流图的一些性质

目的:

想要给tensor中的slice赋值。以numpy为例,对一个np对象,的第二行赋值

import numpy as np
mat = np.zeros((3, 3))
print(mat)
""" 输出
[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
"""

mat[1,:] = [1, 2, 3]
print(mat)
"""输出
[[ 0.  0.  0.]
 [ 1.  2.  3.]
 [ 0.  0.  0.]]
"""

实验:

主体程序:为了为变量tensor a 赋值

import tensorflow as tf

a = tf.Variable(tf.truncated_normal([2, 2]))
b = tf.Variable(tf.truncated_normal([2, 2]))
init = tf.global_variables_initializer()

执行(1):

with tf.Session() as sess:
    sess.run(init)
    print('原始的A--------\n', sess.run(a))
    print('原始的B--------\n', sess.run(b))
    for i in range(0, 2):
        a = b[i,:].assign([1,1])

    print("赋值后的A\n",sess.run(a))
    print("赋值后的B------\n", sess.run(b))

输出(1)

原始的A--------
 [[ 1.20395005  0.30196008]
 [ 1.71405303 -1.02960014]]
原始的B--------
 [[-0.71166104  0.11106157]
 [ 1.71907723 -0.10479059]]
赋值后的A
 [[-0.71166104  0.11106157]
 [ 1.          1.        ]]
赋值后的B------
 [[-0.71166104  0.11106157]
 [ 1.          1.        ]]

执行(2):

a = tf.Variable(tf.truncated_normal([2, 2]))
b = tf.Variable(tf.truncated_normal([2, 2]))
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print('原始的A--------\n', sess.run(a))
    print('原始的B--------\n', sess.run(b))
    for i in range(0, 2):
        a = b[i,:].assign([1,1])
        print("a的第%d次赋值\n" %i, sess.run(a))#实际上多了这一句 ,想追踪赋值的状态的

    print("赋值后的A------\n", sess.run(b)) 
    print("赋值后的B------\n", sess.run(b))

输出(2):

原始的A--------
 [[-0.71950132  0.41336513]
 [-1.46993792 -0.04229261]]
原始的B--------
 [[ 1.2437402  -0.86287254]
 [ 1.62888718  0.50955206]]
a的第0次赋值
 [[ 1.          1.        ]
 [ 1.62888718  0.50955206]]
a的第1次赋值
 [[ 1.  1.]
 [ 1.  1.]]
赋值后的A------
 [[ 1.  1.]
 [ 1.  1.]]
赋值后的B------
 [[ 1.  1.]
 [ 1.  1.]]

结果分析

两次执行的结果并不相同。关键在于sess.run()

从官方文档复制得到:
Session.run()

run(
    fetches,
    feed_dict=None,
    options=None,
    run_metadata=None
)

简介:Runs operations and evaluates tensors in fetches.

详解:This method runs one “step” of TensorFlow computation,

by running the necessary graph fragment to execute every Operation and evaluate every Tensor in fetches _
, substituting the values in feed_dict for the corresponding input values.

扫描二维码关注公众号,回复: 2665196 查看本文章

注意划线的重点. 因为Session.run()运行且仅运行与 fetches 必要的op

猜你喜欢

转载自blog.csdn.net/qq_29007291/article/details/81074941
今日推荐