Theano学习笔记(四)——导数
来源:互联网 发布:淘宝商城入驻流程 编辑:程序博客网 时间:2024/05/22 00:05
导数使用T.grad计算。
这里使用pp()打印梯度的符号表达式。
第3行输出是打印了经过优化器简化的符号梯度表达式,与第1个输出相比确实简单多了。
fill((x** TensorConstant{2}), TensorConstant{1.0})指创建一个x**2大小的矩阵,并填充1。
importtheano.tensor as Tfromtheano import ppfromtheano import functionx= T.dscalar('x')y= x ** 2gy= T.grad(y, x)printpp(gy)f= function([x], gy)printf(4)printpp(f.maker.fgraph.outputs[0])>>> ((fill((x** TensorConstant{2}), TensorConstant{1.0}) * TensorConstant{2}) * (x **(TensorConstant{2} - TensorConstant{1})))8.0(TensorConstant{2.0}* x)
T.grad的第1个参数必须是标量
例如计算逻辑函数sigmoid的导数:
importtheano.tensor as Tfromtheano import functionx= T.dmatrix('x')s= T.sum(1 / (1 + T.exp(-x)))gs= T.grad(s, x)dlogistic= function([x], gs)printdlogistic([[0, 1], [-1, -2]])>>> [[0.25 0.19661193] [ 0.19661193 0.10499359]]
计算雅克比(Jacobian)矩阵
雅克比矩阵是向量的一阶偏导数:
用T.arrange生成从0到y.shape[0]的序列。循环计算。
scan可以提高创建符号循环效率。
lambda~是python内建的magicfunction.
x= T.dvector('x')y = x ** 2J, updates = theano.scan(lambdai, y,x : T.grad(y[i], x), sequences=T.arange(y.shape[0]), non_sequences=[y,x])f = function([x], J,updates=updates)f([4, 4])>>> [[ 8. 0.] [ 0. 8.]]
计算海森(Hessian)矩阵
海森矩阵是多元函数的二阶偏导数方阵。
只要用T.grad(cost,x)替换雅克比矩阵的一些y即可。
x= T.dvector('x')y = x** 2cost= y.sum()gy =T.grad(cost, x)H,updates = theano.scan(lambda i, gy,x : T.grad(gy[i], x),sequences=T.arange(gy.shape[0]), non_sequences=[gy, x])f =function([x], H, updates=updates)f([4,4])>>> [[2. 0.] [ 0. 2.]]
雅克比右乘
x可以由向量扩展成矩阵。雅克比右乘使用Rop:
W = T.dmatrix('W')V =T.dmatrix('V')x =T.dvector('x')y =T.dot(x, W)JV =T.Rop(y, W, V)f =theano.function([W, V, x], JV)printf([[1, 1], [1, 1]], [[2, 2], [2, 2]], [0,1])>>> [2. 2.]
雅克比左乘
雅克比左乘使用Lop:
import theanoimport theano.tensor as Tfrom theano import functionx = T.dvector('x')v =T.dvector('v')x =T.dvector('x')y =T.dot(x, W)VJ =T.Lop(y, W, v)f =theano.function([v,x], VJ)print f([2, 2], [0, 1])>>> [[0. 0.] [ 2. 2.]]
海森矩阵乘以向量
可以使用Rop
import theanoimport theano.tensor as Tfrom theano import functionx= T.dvector('x')v= T.dvector('v')y= T.sum(x ** 2)gy= T.grad(y, x)Hv= T.Rop(gy, x, v)f= theano.function([x, v], Hv)printf([4, 4], [2, 2])>>> [4. 4.]
0 0
- Theano学习笔记(四)——导数
- Theano学习笔记(四)——导数
- Theano学习笔记(四)——导数
- 【theano-windows】学习笔记三——theano中的导数
- 【theano-windows】学习笔记四——theano中的条件语句
- 【theano-windows】学习笔记一——theano中的变量
- 数学笔记——导数4(反函数的导数)
- Theano学习笔记(一)——代数
- Theano学习笔记(三)——图结构
- Theano学习笔记(一)——代数
- Theano学习笔记(三)——图结构
- Theano学习笔记(一)——scan函数
- Theano学习笔记(一)——代数
- Theano学习笔记(三)——图结构
- theano学习笔记(1)—代数
- Theano学习四----Theano shared
- 【theano-windows】学习笔记二——theano中的函数和共享参数
- 【theano-windows】学习笔记五——theano中张量部分函数
- Theano学习笔记(二)——逻辑回归函数解析
- Theano学习笔记(三)——图结构
- 简单几招,提高你的行动力
- hiho刷题日记——第十一天树中的最长路
- Java Base64加密、解密原理
- Theano学习笔记(四)——导数
- 嵌入式系统的含义
- Theano学习笔记(五)——配置设置与编译模型
- Git笔记
- iOS -App主流框架UINavigationController && UITabBarController的简单使用
- 黑马程序员_JavaSe基础知识总结六:super、final关键字
- 容器存储数据_迭代器JAVA112-115
- 执着总会有所收获
- 在UIScrollView中使用Autolayout布局