Fee*_*les 0 python python-3.x tensorflow
当我尝试在自定义命名图中构造一个简单表达式时,出现了一个关于堆栈的奇怪错误。
下面的代码工作正常:
tf.reset_default_graph()
# The basic model
X = tf.placeholder(tf.float32, [None, MnistDim], "X")
W = tf.get_variable(
name="W",
shape=[MnistDim, DigitCount],
dtype=np.float32,
initializer=tf.zeros_initializer()
)
b = tf.get_variable(
name="b",
shape=[DigitCount],
dtype=np.float32,
initializer=tf.zeros_initializer()
)
a = tf.matmul(X, W, name="a") + b
y = tf.nn.softmax (a, name="y")
# The training elements
t = tf.placeholder (tf.float32, [None, 10], "t")
cross_entropy = tf.reduce_mean(-tf.reduce_sum(t * tf.log(y), reduction_indices=[1]))
# I know about tf.nn.softmax_cross_entropy_with_logits(a)
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
Run Code Online (Sandbox Code Playgroud)
但是,如果我通过添加以下内容将该代码放入自定义图表中:
mnist_train_graph = tf.Graph()
with mnist_train_graph.as_default():
tf.reset_default_graph()
# The basic model
X = tf.placeholder(tf.float32, [None, MnistDim], "X")
etc.
etc.
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
Run Code Online (Sandbox Code Playgroud)
然后我收到以下错误。
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-23-13b0e3c5f232> in <module>()
30 # More stable to use the following
31 # tf.nn.softmax_cross_entropy_with_logits(a)
---> 32 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__(self, type, value, traceback)
87 if type is None:
88 try:
---> 89 next(self.gen)
90 except StopIteration:
91 return
/opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in get_controller(self, default)
3626 finally:
3627 if self._enforce_nesting:
-> 3628 if self.stack[-1] is not default:
3629 raise AssertionError(
3630 "Nesting violated for default stack of %s objects"
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
谁能解释一下吗?我在Python 3.6上使用tensorflow-gpu版本1.1.0,在Mac OS 10.12上使用Pip安装。我在 Jupyter 会话中运行它。
谢谢
所以我继续寻找,在发布这篇文章 30 分钟后我找到了答案(典型!)。tf.reset_default_graph()
本质上,使用自定义图表是不安全的as_default()
。删除它可以解决问题。更多详细信息请参见:http://github.com/tensorflow/tensorflow/issues/11121