Theano - 代数(Algebra)

两个标量的加法

为了让我们开始使用Theano,以及感受theano是如何工作的。接下来,我们构造一个简单的函数:加法。

 两个标量的加法

import numpy
import theano.tensor as T
import theano
from theano import function

# 定义两个符号(变量)x, y来表示你想实施加法的数。
# 换句话说, x,y,z均为变量对象。
# 在Theano中,所有的符号必须定义类型。
# T.dscalar: 表示双精度(doubles)的0维数组(标量),他是Theano中的类型(Type)
x = T.dscalar('x')
y = T.dscalar('y')
z = x + y
# dscalar不是一个类(class)。因此,事实上x,y都不是dscalr的实例。
# 它们是TensorVariable的实例。
# 然而,x,y被赋值为theano的dscalar类型。
type(x)  # theano.tensor.var.TensorVariable
x.type  # TensorType(float64, scalar)
T.dscalar   # TensorType(float64, scalar)
x.type is T.dscalar # True

# 在你运行f时,你会注意到有些延迟
# 因为f正在被编译为C代码
f = function([x, y], z)
f(2, 3)
numpy.allclose(f(16.3, 12.1), 28.4)
numpy.allcolse(z.eval({x: 16.3, y: 12.1}), 28.4)

两个矩阵的加法

x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
f([[1, 2], [3, 4]], [[10, 20], [30, 40]])

可以用到的类型(type):

  • byte: bscalar, bvector, bmatrix, brow, bcol, btensor3, btensor4, btensro5

  • 16-bit intergers: wscalar, wvector, wmatrix, wrow, wcol, wtensor3, wtensor4, wtensor5

  • 32-bit intergers: iscalar, ivector, imatrix, irow, icol, itensor3, itensor4, itensor5

  • 64-bit intergers: lscalar, lvector, lmatrix, lrow, lcol, ltensor3, ltensor4, ltensor5

  • float: fscalar, fvector, fmatrix, frow, fcol, ftensor3, ftensor4, ftensor5

  • double: dscalar, dvector, dmatrix, drow, dcol, dtensor3, dtensor4, dtensor5

  • complex: cscalar, cvector, cmatrix, crow, ccol, ctensor3, ctensor4, ctensor5

练习

a = theano.tensor.vector()  # 声明一个变量
out = a + a ** 10   # 构造一个符号表达式
f = theano.function([a], out)   # 编译一个函数
print(f([0, 1, 2]))

修正并执行上面的代码,使得其能够计算:a ^ 2 + b ^ 2 + 2ab

a = theano.tensor.vector()
b = theano.tensor.vector()
out1 = a ** 2 + b ** 2 + 2 * a * b
out2 = (a + b) ** 2
f1 = theano.function([a, b], out1)
f2 = theano.function([a, b], out2)
print(f1([0, 1], [1, 2]))
print(f2([0, 1], [1, 2]))
    原文作者:xiao蜗牛
    原文地址: https://segmentfault.com/a/1190000009964441
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞