theano tutorial(九)Configuration Settings and Compiling Modes(译)

Configuration

     config 模块包含了几个属性用于修改Theano的行为,其中许多性质在导入Theano模块的时候就进行来检查,还有一些是只读的

     我们规定,用户代码不能用于修改config里面的属性

     Theano的代码给这些属性赋予来默认值,但是你可以在,theanorc文件里面重写这些属性,也可以依次用 THEANO_FLAGS 的环境变量重写这些值

优先顺序为:

1.配置 theano.config.<property>
2.配置 THEANO_FLAGS
3.配置 .theanorc 文件 (或者  THEANORC文件)


你可以在任何时候通过打印 theano.config来输出当前有效的配置情况。例如,如果你想看所有的配置参数,输入以下命令行

python -c 'import theano; print(theano.config)' | less
练习
#coding=utf-8

import numpy
import theano
import theano.tensor as T
rng=numpy.random

N=400
feats=784
#astype:复制一个矩阵,映射到特定的类型
# AddConfigVar('floatX',
#              "Default floating-point precision for python casts.\n"
#              "\n"
#              "Note: float16 support is experimental, use at your own risk.",
#              EnumStr('float64', 'float32', 'float16',
#                      convert=floatX_convert, ),
#              )
D=(rng.randn(N,feats).astype(theano.config.floatX),rng.randint(size=N,low=0,high=2).astype(theano.config.floatX))
training_steps=10000

x=T.matrix("x")
y=T.vector("y")
w=theano.shared(rng.randn(feats).astype(theano.config.floatX),name="w")
# asarray:Convert the input to an array
b=theano.shared(numpy.asarray(0,dtype=theano.config.floatX),name="b")
x.tag.test_value=D[0]
y.tag.test_value=D[1]

p_1=1/(1+T.exp(-T.dot(x,w)-b))
prediction=p_1>0.5
xent=-y*T.log(p_1)-(1-y)*T.log(1-p_1)
cost=xent.mean()+0.01*(w**2).sum()
gw,gb=T.grad(cost,[w,b])
train=theano.function(inputs=[x,y],outputs=[prediction,xent],updates=[(w,w-0.01*gw),(b,b-0.01*gb)],name="train")
predict=theano.function(inputs=[x],outputs=prediction,name="predic")
if any([x.op.__class__.__name__ in ['Gemv', 'CGemv', 'Gemm', 'CGemm'] for x in
        train.maker.fgraph.toposort()]):
    print('Used the cpu')
elif any([x.op.__class__.__name__ in ['GpuGemm', 'GpuGemv'] for x in
          train.maker.fgraph.toposort()]):
    print('Used the gpu')
else:
    print('ERROR, not able to tell if theano used the cpu or the gpu')
    print(train.maker.fgraph.toposort())
for i in range(training_steps):
    pred, err = train(D[0], D[1])

print("target values for D")
print(D[1])

print("prediction on D")
print(predict(D[0]))

注意:

        在你的代码里面加上floatX=float32(通过theano.config.floatX)

        在将输入存进一个共享变量之前,进行类型转换

        避免自动转换为int32,也不要从float32转换为float64

Mode

      每次调用theano.function的时候,都会对输入输出的表达式进行编译和优化。进行编译的方式是通过 mode 参数值进行编译的
  • 'FAST_COMPILE': Apply just a few graph optimizations and only use Python implementations. So GPU is disabled.使用一些graph优化,只使用Python实现:所有不能使用GPU

  • 'FAST_RUN': Apply all optimizations and use C implementations where possible.应用所有的优化并且在可能的地方使用C进行实现

  • 'DebugMode': Verify the correctness of all optimizations, and compare C and Python验证所有优化的正确性,比较C和Python

    implementations. This mode can take much longer than the other modes, but can identify several kinds of problems.的实现,这种模式耗费的时间比其他模式长,但能够确定几类问题

  • 'NanGuardMode': Same optimization as FAST_RUN, but check if a node generate nans.和FAST_RUN差不多,但会对是否产生NaN(无穷大)进行检查

The default mode is typically FAST_RUN, but it can be controlled via the configuration variableconfig.mode, which can be overridden by passing the keyword argument to theano.function.默认的模式是 FAST_RUN,但可以通过配置参数config.mode进行控制,config.mode可以通过传递键值参数给theano.function来进行重写

short name Full constructor What does it do?
FAST_COMPILE compile.mode.Mode(linker='py',optimizer='fast_compile') Python implementations only, quick and cheap graph transformations
FAST_RUN compile.mode.Mode(linker='cvm',optimizer='fast_run') C implementations where available, all available graph transformations.
DebugMode compile.debugmode.DebugMode() Both implementations where available, all available graph transformations.

      如果是为了进行调试,还有一种MonitorMode.它可以被用来追踪一个函数的执行

Linkers

       一个mode通常由两部分组成,一个optimezer和一个linker。一些模式,例如NanGuardMode和DebugMode,add logic around the optimizer and linker,NanGuardMode和DebugMode使用自己的linker
       你可以通过config.linker选择使用哪个linker。
linker gc[1] Raise error by op Overhead Definition
cvm yes yes “++” As c|py, but the runtime algo to execute the code is in c
cvm_nogc no yes “+” As cvm, but without gc
c|py [2] yes yes “+++” Try C code. If none exists for an op, use Python
c|py_nogc no yes “++” As c|py, but without gc
c no yes “+” Use only C code (if none available for an op, raise an error)
py yes yes “+++” Use only Python code
NanGuardMode no no “++++” Check if nodes generate NaN
DebugMode no yes VERY HIGH Make many checks on what Theano computes

Using DebugMode

一般情况下,你应该使用FAST_RUN或者FAST_COMPILE模式,但首先使用DebugMode来运行你的代码是非常有用的(尤其是当你在定一个一些信的表达式或者oprimizationde 时候,mode='DebugMode')DebugMode是用来运行一些自我检查和断言来帮助你发现程序中的错误。注意DebugMode模式比FUST_RUN或者FAST_COMPILE要慢很多,所以在应该在小数据集上使用
      如果检测出来任何问题,DebugMode将会抛出根据错误异常,不过是在调用f([5])的时候还在在编译的时候,这种异常都不应该被忽视
      有一些错误只能在某些特别的输入值下被检测出来。在下面的例子中,我们没有办法保证有人会调用f(-1)
       如果你使用来构造函数而不是关键字DebugMode,你可以通过构造函数的参数来陪著它的行为。而关键字DebugMode(可以通过使用mode='DebugMode'获得)是非常严格的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值