【问题标题】:Tensorflow variable initialization in a loop循环中的 TensorFlow 变量初始化
【发布时间】:2020-08-30 15:12:05
【问题描述】:

我正在尝试一个 Tensorflow 示例:

import tensorflow as tf
x = tf.Variable(0, name='x')
model = tf.global_variables_initializer()
with tf.Session() as session:
    for i in range(5):
        session.run(model)
        x = x + 1
        print(session.run(x))

但是输出是出乎意料的。我预计它会输出:

1 1 1 1 1

但实际输出是:

1 2 3 4 5

这是为什么? session.run(model) 每次都会初始化变量,这个说法正确吗?

【问题讨论】:

  • 好问题。取决于实施。对我来说,初始化在会话中只进行一次似乎是有效的。

标签: tensorflow


【解决方案1】:

session.run(model) 每次都会初始化变量

没错。问题是每次x = x + 1 都会在图表中创建一个新添加项,从而解释您获得的结果。

第一次迭代后的图表:

第二次迭代后:

第三次迭代后:

第四次迭代后:

第五次迭代后:

我使用的代码,大部分取自 Yaroslav Bulatov 在How can I list all Tensorflow variables a node depends on? 中的回答:

import tensorflow as tf

import matplotlib.pyplot as plt
import networkx as nx

def children(op):
  return set(op for out in op.outputs for op in out.consumers())

def get_graph():
  """Creates dictionary {node: {child1, child2, ..},..} for current
  TensorFlow graph. Result is compatible with networkx/toposort"""

  ops = tf.get_default_graph().get_operations()
  return {op: children(op) for op in ops}

def plot_graph(G):
    '''Plot a DAG using NetworkX'''        
    def mapping(node):
        return node.name
    G = nx.DiGraph(G)
    nx.relabel_nodes(G, mapping, copy=False)
    nx.draw(G, cmap = plt.get_cmap('jet'), with_labels = True)
    plt.show()


x = tf.Variable(0, name='x')
model = tf.global_variables_initializer()
with tf.Session() as session:
    for i in range(5):
        session.run(model)
        x = x + 1
        print(session.run(x))

        plot_graph(get_graph())

【讨论】:

  • 您想在每张图之后添加几个 cmets 吗?
【解决方案2】:

看来你必须在循环中初始化它

import tensorflow as tf

for i in range(5):
    X = tf.Variable(0, name='x')
    model = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(model)
        X += 1
        print(X.eval())

【讨论】:

    【解决方案3】:
    session.run(model) 
    

    每次都会初始化变量(因为它调用model = tf.global_variables_initializer()), 但是用于初始化的x 的值对于循环中的每个条目都会增加1。例如,

    对于i=0x 被初始化为它在该实例中拥有的值,即0。当i=1x 已经递增到1,这就是初始化器将使用的值,以此类推。

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 2012-01-02
      • 2019-01-23
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-16
      相关资源
      最近更新 更多