Theano学习笔记(五)——配置设置与编译模型

配置

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


例如,修改笔记(二)中的逻辑回归函数,设置精度为float32

 

#!/usr/bin/envpython
#Theano tutorial
#Solution to Exercise in section 'Configuration Settings and Compiling Modes'
 
importnumpy
importtheano
importtheano.tensor as tt
 
theano.config.floatX= 'float32'
 
rng= numpy.random
 
N= 400
feats= 784
D= (rng.randn(N, feats).astype(theano.config.floatX),
rng.randint(size=N,low=0, high=2).astype(theano.config.floatX))
training_steps= 10000
 
#Declare Theano symbolic variables
x= tt.matrix("x")
y= tt.vector("y")
w= theano.shared(rng.randn(feats).astype(theano.config.floatX),name="w")
b= theano.shared(numpy.asarray(0., dtype=theano.config.floatX),name="b")
x.tag.test_value= D[0]
y.tag.test_value= D[1]
#print"Initial model:"
#printw.get_value(), b.get_value()
 
#Construct Theano expression graph
p_1= 1 / (1 + tt.exp(-tt.dot(x, w) - b))  #Probability of having a one
prediction= p_1 > 0.5  # The prediction that isdone: 0 or 1
xent= -y * tt.log(p_1) - (1 - y) * tt.log(1 - p_1) # Cross-entropy
cost= tt.cast(xent.mean(), 'float32') + \
       0.01 * (w ** 2).sum()  # The cost to optimize
gw,gb = tt.grad(cost, [w, b])
 
#Compile expressions to functions
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="predict")
 
ifany([x.op.__class__.__name__ in ['Gemv', 'CGemv', 'Gemm', 'CGemm'] for x in
train.maker.fgraph.toposort()]):
    print 'Used the cpu'
elifany([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 theanoused the cpu or the gpu'
    print train.maker.fgraph.toposort()
 
fori in range(training_steps):
    pred, err = train(D[0], D[1])
#print"Final model
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值