深度学习_Affine&Softmax-Loss层

  1. Affine层:神经网络在传播时,进行的矩阵乘积运算。
import numpy as np


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(dout, self.w.T)     # self.w.T为self.w矩阵的转置
        self.dw = np.dot(self.x.T, dout)
        self.db = np.sum(dout, axis=0)      # 每一列的值进行相加,结果只有一行
        return dx

  1. Softmax-with-Loss
    (1)Softmax层:将输入值正规化(输入值和调整为1,反映概率)后输出。
    (2)Loss层:cross entropy error(交叉熵误差,一种损失函数)接收Softmax的输出(y1, y2, y3)和监督标签(t1, t2, t3), 输出损失L。
    深度学习_Affine&Softmax-Loss层_第1张图片
import os
import sys
sys.path.append(os.pardir)
from common.functions import *


class SoftmaxWithLoss:
    def __init__(self):
        self.loss = None        # 损失
        self.y = None       # softmax的输出
        self.t = None       # 监督数据(one-hot vector)

    def forward(self, x, t):
        self.t = t
        self.y = softmax(x)
        self.loss = cross_entropy_error(self.y, self.t)
        return self.loss

    def backward(self, dout=1):
        batch_size = self.t.shape[0]        # t的行数,批的大小
        dx = (self.y - self.t) / batch_size
        return dx


你可能感兴趣的:(深度学习)