[theano]入门-计算梯度

2022-11-19,,,

python计算梯度非常简单,最重要的是一个函数grad,这个函数在theano.tensor里边。

这个函数提供了多套机制 1计算单个自变量的梯度 2计算一个数据矩阵的梯度 3计算一个向量的梯度。

针对不同的数据结构返回不同的结果(单个数值,向量,矩阵),顺序是一一对应的。

走到这里感觉python是面向对象的一门语言,具体操作时不是直接操作数值,而是声明变量。在计算表达式的时候直接调用函数,当然函数也需要自己去写。

 同时,theano也提供了计算hesse矩阵、雅各比矩阵的函数,具体见:

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

 

#!/usr/bin/env python
# coding=utf-8
import theano
from theano import pp
import theano.tensor as T
x=T.dscalar('x')
y=x**2
gygx=T.grad(y,x)
pp(gygx)
grad=theano.function([x],gygx)

print grad(2.344)


x=T.dmatrix('x')
s=T.sum(1/(1+T.exp(-x)))
gsgx=T.grad(s,x)
dlogistic=theano.function([x],gsgx)

print dlogistic([[2,3],[5,7]])