我的 theano 程序中有一个导致 NaN 值的错误。文档建议使用 nanguardmode 来追踪问题的根源。
当我从文档网页复制/粘贴这一行时:
from theano.compile.nanguardmode import NanGuardMode
我得到:
ImportError: No module named nanguardmode
当我输入时找不到任何 nanguardmode 的标志:
help(theano.compile)
知道为什么没有 nanguardmode 吗?我该如何解决这个问题?
编辑:
感谢您的回复。
关于我的 Theano 版本,我找不到如何检查它。但我认为它是最新的:大约一个月前我从安装网页安装了它。我在 Windows 64 位上。
关于 detect_nan hack:事情变得更奇怪了!
首先:如果我尝试使用:
post_func=theano.compile.monitormode.detect_nan
我得到:
File "C:\SciSoft\WinPython-64bit-2.7.9.4\python-2.7.10.amd64\lib\site-packages\theano\compile\monitormode.py", line 87, in detect_nan
if (not isinstance(numpy.random.RandomState, output[0]) and
NameError: global name 'numpy' is not defined
确实,numpy 没有导入到 monitormode 模块中……这是一个已知错误吗?
第二:如果我尝试使用 detect_nan 的复制/粘贴,NaN 会神奇地消失。其他一切保持不变,在我的 theano 函数(迭代训练模型)中没有 detect_nan,我在第 5 次迭代时得到 NaN:
epoch 1, valid 28.582677 %, train 27.723320 % 0.546633
epoch 2, valid 27.814961 %, train 25.681751 % 0.500522
epoch 3, valid 27.263780 %, train 24.262972 % 0.478799
epoch 4, valid 26.938976 %, train 23.209021 % 0.463017
epoch 5, valid 50.000000 %, train 50.000000 % nan
(最后一个数字是成本值)
当我添加
mode=theano.compile.MonitorMode(post_func=detect_nan)
对于函数,至少迭代 100 次(可能更多)没有出现 NaN。
epoch 1, valid 28.582677 %, train 27.723320 % 0.546633
epoch 2, valid 27.814961 %, train 25.681751 % 0.500522
epoch 3, valid 27.263780 %, train 24.262972 % 0.478799
epoch 4, valid 26.938976 %, train 23.209021 % 0.463017
epoch 5, valid 26.289370 %, train 22.320902 % 0.450454
... etc ...
这是怎么回事???
请您参考如下方法:
NanGuardMode 已于 5 月 1 日移至 Theano 的前沿版本(来自 PyLearn2)。这是在 3 月 26 日发布 0.7 版之后,因此您需要 upgrade to the bleeding edge version从 GitHub 使用 NanGuardMode。
或者,您可以使用 debug FAQ 中的 detect_nan 示例:
import numpy
import theano
# This is the current suggested detect_nan implementation to
# show you how it work. That way, you can modify it for your
# need. If you want exactly this method, you can use
# ``theano.compile.monitormode.detect_nan`` that will always
# contain the current suggested version.
def detect_nan(i, node, fn):
for output in fn.outputs:
if (not isinstance(output[0], numpy.random.RandomState) and
numpy.isnan(output[0]).any()):
print '*** NaN detected ***'
theano.printing.debugprint(node)
print 'Inputs : %s' % [input[0] for input in fn.inputs]
print 'Outputs: %s' % [output[0] for output in fn.outputs]
break
x = theano.tensor.dscalar('x')
f = theano.function([x], [theano.tensor.log(x) * x],
mode=theano.compile.MonitorMode(
post_func=detect_nan))
