Skip to main content
 首页 » 编程设计

python之我如何使用 Tensorflow 的调试器来解决 "Getting Started"示例中的分歧

2024年12月31日27wayfarer

我正在关注 TF 的 Getting Started ,我们在线性模型上进行简单的梯度下降,对其进行小的调整会导致一个问题,我将其用作学习 TF 调试器的测试用例。这是来自 Getting Started 的代码:

import tensorflow as tf 
from tensorflow.python import debug as tf_debug 
 
sess = tf.Session() 
# sess = tf_debug.LocalCLIDebugWrapperSession(sess) 
 
W = tf.Variable([.3], tf.float32) 
b = tf.Variable([-.3], tf.float32) 
x = tf.placeholder(tf.float32) 
model = W * x + b 
y = tf.placeholder(tf.float32) 
sq_deltas = tf.square(model - y) 
loss = tf.reduce_sum(sq_deltas) 
 
init = tf.global_variables_initializer() 
sess.run(init) 
 
optimizer = tf.train.GradientDescentOptimizer(0.01) 
train = optimizer.minimize(loss) 
 
for i in range(1000): 
    sess.run(train, {x: list(range(1, 8)), 
                     y: list(range(0, -7, -1))}) 
 
out = sess.run([W, b]) 

现在 W 和 b 已经 fork 了:

>>> print(out) 
[array([nan], dtype=float32), array([nan], dtype=float32)] 

注意 sess.run(train, ...) 我的示例使用了 7 个示例的数据集,而他们的示例使用了 4 个示例:

{ 
  x : np.array([1., 2., 3., 4.]), 
  y : np.array([0., -1., -2., -3.]) 
} 

梯度发散,所以如果我使用它,它可以再次正确解决问题,尽管速度很慢:

optimizer = tf.train.GradientDescentOptimizer(0.001) 

这样我就可以进入 Debug模式了:

python -m mything.py --debug 
> run # runs sess.run(init) 
> run -f has_inf_or_nan # runs gradient descent, filters for inf/nan 
  # Square:0 was found to have inf 
> pt Square:0 # all at or approaching inf 
> ni Square # I'm not sure what do do with this 
> ni -t Square # buried in the output, my code line: 
  # sq_deltas = tf.square(model - y) 

但此时我迷路了,调试器对我来说仍然有点难以捉摸。

1) 我如何追踪这些 inf 的来源,重要的是,2) 对于这个简单的线性模型无法扩展到更大的数据集,我做错了什么?

请您参考如下方法:

1) How do I track down the source of these infs,

你不会的。除了实际的错误,优化的分歧就是您所说的“紧急行为”。它不会在代码中的单个错误步骤中发生。参数只是离它们的最佳值越来越远。

2) what am I doing wrong for this simple linear model to not be able to scale to a larger dataset?

对于学习率的某些值,SGD 通常会发散。这是算法的本质。这些值取决于模型、初始值和数据集。您只是在观察后者。

在您的案例中,数据的规模发生了变化。