Theano基础

Theano是python的一个开源库,其解决大量数据问题时性能更好。

 

首先,给一个关于theano.function的demo:

 1 import theano
 2 from theano import tensor as T
 3 from theano import shared
 4 from theano import function
 5 
 6 x = T.iscalar('x')  # x 为自变量,开头的 i 表示类型,如果开头为'd'则为 double
 7 y, z = T.iscalars('y', 'z')  # 当声明多个字变量时,最后要加's'
 8 '''
 9 scalar  标量
10 vector  向量
11 matrix  矩阵
12 row     行
13 col     列
14 '''
15 
16 w = shared(0)  # w 为共享变量,其值可以修改
17 m = x + y + z  # m 为因变量,由 x+y+z 得到
18 
19 f = function([x, y, z], m, updates=[(w, w + m)])
20 '''典型的theano.function函数
21 function([自变量],因变量,updates=[])
22 其中[x,y,z]代表function的自变量,通常以列表形式出现
23 m为因变量,也是输出outputs
24 updates指数据更新,源数据为w,改变之后变为w+m
25 '''
26 print(f(1, 2, 3))
27 
28 print(w.get_value())

 

Theano中的条件判断:

Theano是一种符号语言,他的条件判断与Python语句中的不同

总共有两种形式,一种为switch(condition,iff,ift),当condition满足时,既执行iff,也执行ift

另一种为if condition then iff else ift,即一个条件判断,为真则执行iff,否则执行ift

 

用Theano实现求导数:

1 import theano
2 from theano import tensor
3 
4 x=theano.tensor.dscalar('x')
5 y=1/(1+theano.tensor.exp(-x))
6 dx=theano.grad(y,x)         #偏导数函数
7 f=theano.function([x],dx)   #输入为 x ,输出为 y 在 x 处的偏导数
8 print(f(3))

 

 

posted on 2019-09-08 19:15  rebel3  阅读(167)  评论(0编辑  收藏  举报

导航