深度学习框架DeZero之自动微分

import numpy as np
def as_array(x):
    if np.isscalar(x):
        return np.array(x)
    return x
class Variable:
    def __init__(self,data):
        if data is not None:
            if not isinstance(data,np.ndarray):
                raise TypeError('{} is not supported'.format(type(data)))
        self.data=data
        self.grad=None
        self.creator=None
    def set_creator(self,func):
        self.creator=func
    def backward(self):
        if self.grad is None:
            self.grad=np.ones_like(self.data)
        funcs=[self.creator]
        while funcs:
            f=funcs.pop()
            x,y=f.input,f.output
            x.grad=f.backward(y.grad)
            if x.creator is not None:
                funcs.append(x.creator)       
 
class Function:
    def __call__(self,input):
        x=input.data
        y=self.forward(x)
        output=Variable(as_array(y))
        output.set_creator(self)
        self.input=input
        self.output=output
        return output
    def forward(self,x):
        raise NotImplementedError()
    def backward(self,gy):
        raise NotImplementedError()

class Square(Function):
    def forward(self,x):
        y=x**2
        return y
    def backward(self,gy):
        x=self.input.data
        gx=2*x*gy
        return gx

class Exp(Function):
    def forward(self,x):
        y=np.exp(x)
        return y
    def backward(self,gy):
        x=self.input.data
        gx=np.exp(x)*gy
        return gx

def square(x):
    return Square()(x)

def exp(x):
    return Exp()(x)

x=Variable(np.array(0.5))
y=square(exp(square(x)))
y.backward()
print(x.grad)

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值