Python-深度学习入门记录#1

Python-深度学习入门的代码记录-(第5章)

提示:注重Python中class对象的使用方法
问题:训练集文件加载


Relu激活函数的实现:

Relu非线性函数

class RULE:
    def __init__(self):
        self.mask=None
    def forward(self,input): #函数运算
        self.mask=(input<=0)
        out=input.copy()
        out[self.mask]=0
        return out
    def backward(self,dout): #函数求导
        dout[self.mask]=0
        doutput=dout
        return doutput

Sigmoid函数:

Sigmoid函数
在这里插入图片描述

class Sigmoid:
    def __init__(self):
        self.out=None
    def forward(self,input):
        out=1/(1+np.exp(-input))
        self.out=out
        return out
    def backward(self,dout):
        doutput=dout*(1.0-self.out)*self.out
        return doutput

神经网络-隐含层&Softmax输出层:

提示:包含矩阵表示,矩阵运算,Y=WX +b

隐含层

class Affine:
    def __init__(self,W,b):
        self.W=W
        self.b=b
        self.x=None
        self.dW=None
        self.db=None
    def forward(self,x):
        self.x=x
        out=np.dot(x,self.W)+self.b
        return out
    def backward(self,dout):
        dx=np.dot(x,self.W.T) # 转置
        self.dW=np.dot(self.x.T,dout) # 转置
        self.db=np.sum(dout,axis=0)
        return dx

Softmax输出层

class SoftmaxWithLoss:
    def __init__(self):
        self.loss=None
        self.y=None
        self.t=None
    def forward(self,x,t):
        self.t=t
        self.y=softmax(x)
        self.loss=cross_entropy_errot(self.y,self.t)
        return self.loss
    def backward(self,dout=1):
        bacth_size=self.t.shape[0]
        dx=(self.y-self.t)/bacth_size
        return dx

Softmax代码

def softmax(input):
    exp_input=np.exp(input)
    sum_exp=np.sum(exp_input)
    output=exp_input/sum_exp
    return output

损失函数代码

y是输出,t是监督数据

def cross_entropy_error(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)
    # 监督数据是one-hot-vector的情况下,转换为正确解标签的索引
    if t.size == y.size:
        t = t.argmax(axis=1)
    batch_size = y.shape[0]
    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size

Softmax&loss-function

def softmax_loss(input, t):
    y = softmax(input)
    return cross_entropy_error(y, t)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值