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]])

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-27
  • 2021-04-12
猜你喜欢
  • 2021-12-03
  • 2022-01-23
  • 2021-10-21
  • 2021-12-03
  • 2021-08-16
  • 2021-12-03
相关资源
相似解决方案