theano学习--theano.function

theano.function()函数用于定义一个函数的自变量、因变量。

标量的运算:

import theano.tensor as T
x0 = T.dscalar('x0')
x1 = T.dscalar('x1')
aver = (x0 + x1)/2
f = theano.function([x0, x1], aver)
y = f(1,2)
print y
print type(f)
print type(x0)

输出:

1.5
<class 'theano.tensor.var.TensorVariable'>
<class 'theano.compile.function_module.Function'>
<class 'theano.tensor.var.TensorVariable'>

矩阵运算:

import theano.tensor as T
x = T.fmatrix('x')
y = T.fmatrix('y')
z = T.fmatrix('z')
su = x + y + z
f = theano.function([x, y, z], su)
a = f([[1,2,3]], [[4,5,6]], [[4,5,6]])
print a
print type(a)

输出:

[[  9.  12.  15.]]
<type 'numpy.ndarray'>

多输入/多输出:

# double型矩阵
import theano.tensor as T
a, b = T.dmatrices('a', 'b')
diff = a - b
diff_abs = abs(diff)
diff_squared = diff**2
f = theano.function([a, b], [diff, diff_abs, diff_squared])
freturn = f([[1, 1], [1, 1]], [[0, 1], [2, 3]])
print freturn

输出:

[array([[ 1.,  0.],[-1., -2.]]), 
 array([[ 1.,  0.],[ 1.,  2.]]),
 array([[ 1.,  0.],[ 1.,  4.]])]

updates参数:

function()中updates=[old_w,new_w],当函数被调用的时候,这个会用new_w替换old_w

# 共享变量,累加器,共享变量主要用于gpu中,提高性能
import theano.tensor as T
# 使变量为共享变量
state = shared(0)
# 定义一个标量('name')
inc = T.iscalar('inc')
# state = state + inc / updates=[old_w,new_w],当函数被调用的时候,这个会用new_w替换old_w
f = theano.function([inc], state, updates=[(state, state+inc)])
print 'state:\n', state.get_value()

# 传一个5进去,state被state+inc更新后 state=5
f(5)
print 'f(5):\n', state.get_value()

# 传一个100进去,state被state+inc更新后 state=105
f(100)
print 'f(100):\n', state.get_value()

# 利用set_value将state的设置为-1000
state.set_value(-1000)
print 'state.set_value(-1000):\n', state.get_value()
# 传一个-1000进去 state=-1000
print 'f(-1000):\n', state.get_value()
# 传一个800进去,state被state+inc更新后 state=800-1000=-200
f(800)
print 'f(800):\n', state.get_value()

输出:

state:
0
f(5):
5
f(100):
105
state.set_value(-1000):
-1000
f(-1000):
-1000
f(800):
-200

given参数:

function()中given参数,保留之前的state不改变,记录当前的结果

import theano.tensor as T
# 定义一个int类型的变量
# iscalar = TensorType('int32', ())
inc = T.iscalar('inc')
# 返回共享变量变量,使用“value”的副本或引用初始化
# 该函数迭代构造函数以找到合适的共享变量子类,合适的是接受给定值的第一个构造函数
# shared(value, name=None, strict=False, allow_downcast=None, **kwargs)
state = shared(0)
fn_of_state = state * 2 + inc
# 定义一个标量
# scalar(name=None, dtype=None) /int64
foo = T.scalar(dtype=state.dtype)

print "foo is :", foo
f = theano.function([inc, foo], fn_of_state, givens=[(state, foo)])
print f(5, 2)
print 'state :\n', state.get_value()

输出:

foo is : <TensorType(int64, scalar)>
9
state :
0
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值