Theano(3):Theano【数据类型】与【代码初尝试】

本文介绍了Theano的基本数据类型,包括不同位宽的整型、浮点型和复数型,并强调用户需选择32位或64位。通过示例展示了如何进行加法操作,定义dscalar变量并使用pp函数打印计算过程。Theano的tensor模块专注于张量运算,而function模块中的scan用于处理数据和循环计算。在Theano中,运算涉及符号变量的定义和函数的延迟执行,所有计算需先定义为符号表达式,然后通过function进行编译和执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://deeplearning.net/software/theano/tutorial/adding.html


常见的数据类型:

  • bytebscalar, bvector, bmatrix, brow, bcol, btensor3, btensor4
  • 16-bit integerswscalar, wvector, wmatrix, wrow, wcol, wtensor3, wtensor4
  • 32-bit integersiscalar, ivector, imatrix, irow, icol, itensor3, itensor4
  • 64-bit integerslscalar, lvector, lmatrix, lrow, lcol, ltensor3, ltensor4
  • floatfscalar, fvector, fmatrix, frow, fcol, ftensor3, ftensor4
  • doubledscalar, dvector, dmatrix, drow, dcol, dtensor3, dtensor4
  • complexcscalar, cvector, cmatrix, crow, ccol, ctensor3, ctensor4
a guide to all types compatible with NumPy arrays may be found here:  tensor creation .

注意:You, the user—not the system architecture—have to choose whether your program will use 32- or 64-bit integers (i prefix vs. the l prefix) and floats (f prefix vs. the d prefix).



add两个dscalar:

定义两个dscalar变量:

>>> import numpy
>>> import theano.tensor as T
>>> from theano import function
>>> x = T.dscalar('x')
>>> y = T.dscalar('y')


定义另一个表示x+y的和的变量:

>>> z = x + y

可以使用 pp function to pretty-print out the computation associated to z:

>>> from theano import pp
>>> print(pp(z))
(x + y)


定义一个 以x、y为输入变量 以z为输出变量的 函数:

>>> f = function([x, y], z)
function第一个参数为输入,第二个参数为输出: The first argument to  function  is a list of Variables that will be provided as inputs to the function. The second argument is a single Variable  or  a list of Variables. For either case, the second argument is what we want to see as output when we apply the function.  f  may then be used like a normal Python function.


调用定义的函数,进行加法运算:

>>> a=f(2, 3)
array(5.0)





回顾整个代码:

>>> import numpy
>>> import theano.tensor as T
>>> from theano import function
>>> x = T.dscalar('x')
>>> y = T.dscalar('y')
>>> z = x + y
>>> f = function([x, y], z)

theano中tensor下的内容,以张量处理为主,操作对象是符号变量。比如,T.grad处理的是一个代数式,得到的也是一个代数式。

theano目录下的function,scan处理的是数据,如function定义了输入数据,输出数据,运算公式。scan可以看做对做循环计算的function函数。

最后,总结代码风格:

由于是符号运算,所以不会出现我们常见的x=2,y=3这样的直接赋值,以及z=2+3这样的直接运算;必须:

【首先】将  想要运算的quantity  定义成对应的符号(symbol,或者称variable),x=T.dscalar('x')

【其次】将  在这些quantity上进行的运算  同样定义成相应的符号,z=x+y

【最后】通过定义function,将  结果变量(符号)  和  需要运算的变量(符号)  关联起来,f=function([x,y], z)

【最最后】调用定义的function,将实际的数值传递进去,进行相应运算,a=f(2,3)

讲到function,再提一点关于【延迟执行】的做法:If you are following along and typing into an interpreter, you may have noticed that there was a slight delay in executing the function instruction. Behind the scene, f was being compiled into C code.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值