【自学】深度学习入门 基于python的理论与实现 LESSON6 <神经网络的学习3>


前言

神经网络的学习步骤如下:

1. mini-batch:

从训练数据中随机选出一部分数据,这部分数据称为mini-batch。我们的目标是减小mini-batch的损失函数值

2. 计算梯度:

为了减小mini-batch的损失函数值,需要求出各个权重参数的梯度。梯度表示损失函数的值减小最多的方向。

3. 更新参数:

将权重参数沿梯度方向进行微小更新

4. 重复123步骤。


一、两层神经网络的类

代码示例:

# coding: utf-8
import sys, os
sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定
from common.functions import *
from common.gradient import numerical_gradient


class TwoLayerNet:

    def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
        # 初始化权重
        self.params = {}
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)

    def predict(self, x):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
    
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)
        
        return y
        
    # x:输入数据, t:监督数据
    def loss(self, x, t):
        y = self.predict(x)
        
        return cross_entropy_error(y, t)
    
    def accuracy(self, x, t):
        y = self.predict(x)
        y = np.argmax(y, axis=1) #找y矩阵每行的最大值,并输出其所在位置
        t = np.argmax(t, axis=1) #找t矩阵每行的最大值,并输出其所在位置
        
        accuracy = np.sum(y == t) / float(x.shape[0])
        #np.sum(y == t):先判断y矩阵与t矩阵的每个元素是否相同,相同输出1,不同输出0,然后把结果加起来
        #float(x.shape[0]):输出为x矩阵的行数
        #accuracy表示平均每行相同的个数,但是为什么用accuracy这个单词还不明白
        return accuracy
        
    # x:输入数据, t:监督数据
    def numerical_gradient(self, x, t):
        #求梯度
        loss_W = lambda W: self.loss(x, t)
        
        grads = {}
        grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
        #损失函数是loss_W, self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
        grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
        grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
        
        return grads
        
    def gradient(self, x, t):
        #计算权重参数的梯度,是numerical_gradient的高速版,将在后续进一步研究
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
        grads = {}
        
        batch_num = x.shape[0]
        
        # forward
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)
        
        # backward
        dy = (y - t) / batch_num
        grads['W2'] = np.dot(z1.T, dy)
        grads['b2'] = np.sum(dy, axis=0)
        
        da1 = np.dot(dy, W2.T)
        dz1 = sigmoid_grad(a1) * da1
        grads['W1'] = np.dot(x.T, dz1)
        grads['b1'] = np.sum(dz1, axis=0)

        return grads

解析:

(1)numpy.random.randn(d0,d1,…,dn)

  • randn函数返回一个或一组样本,具有标准正态分布。

  • dn表示每个维度

  • 返回值为指定维度的array

import numpy as np

a = np.random.randn(2,4)
print(a)
[[-1.6603249   0.98062458  1.54753599 -1.43962466]
 [ 0.98204966  0.38925058 -0.02572875 -1.36475084]]

(2)numpy.zeros(shape,dtype = float,order ='C')

返回具有输入形状和类型的零数组。(生成相应大小的零矩阵)

import numpy as np

a = np.zeros(5)
print(a)
[0. 0. 0. 0. 0.]

(3)numpy.argmax(array, axis)

用于返回一个numpy数组中最大值的索引值。

多维数组np.argmax(a, axis=1)

在列方向比较,此时就是指在每个矩阵内部的列方向上进行比较

a = np.array([
[
[1, 5, 5, 2],
[9, -6, 2, 8],
[-3, 7, -9, 1]
],

[
[-1, 7, -5, 2],
[9, 6, 2, 8],
[3, 7, 9, 1]
],

[
[21, 6, -5, 2],
[9, 36, 2, 8],
[3, 7, 79, 1]
]
])
c=np.argmax(a, axis=1)#对于三维度矩阵,a有三个方向a[0][1][2]
#当axis=1时,是在a[1]方向上找最大值,即在列方向比较,此时就是指在每个矩阵内部的列方向上进行比较
#(1)看第一个矩阵
# [1, 5, 5, 2],
# [9, -6, 2, 8],
# [-3, 7, -9, 1]
#比较每一列的最大值,可以看出第一列1,9,-3最大值为9,,索引值为1
#第2列5,-6,7最大值为7,,索引值为2
# 因此对第一个矩阵,找出索引结果为[1,2,0,1]
#再拿出2个,按照上述方法,得出比较结果 [1 0 2 1]
#一共有三个,所以最终得到的结果b就为3行4列矩阵
print(c)
#[[1 2 0 1]
# [1 0 2 1]

(4)loss_W = lambda W: self.loss(x, t)

利用lambda匿名函数定义了一个函数f,匿名函数转正,有名字了,函数形参为x,函数体是冒号后面的部分。注意这里只是定义了函数f,没有进行调用。

f = lambda x:my_test(x) # 代码1
等价于
def f(x):
return my_test(x)

输出分析:

net = TwoLayerNet(input_size=784, hidden_size=100, output_size=10)
a = net.params['W1'].shape
b = net.params['b1'].shape
c = net.params['W2'].shape
d = net.params['b1'].shape
print(a)
print(b)
print(c)
print(d)

输出:

(784, 100)
(100,)
(100, 10)
(100,)

二、mini-batch的实现

# coding: utf-8
import sys, os
sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from two_layer_net import TwoLayerNet

# 读入数据
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)

network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)

iters_num = 10000  # 适当设定循环的次数
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1

train_loss_list = []
train_acc_list = []
test_acc_list = []

iter_per_epoch = max(train_size / batch_size, 1)

for i in range(iters_num):
    batch_mask = np.random.choice(train_size, batch_size)
    x_batch = x_train[batch_mask]
    t_batch = t_train[batch_mask]
    
    # 计算梯度
    #grad = network.numerical_gradient(x_batch, t_batch)
    grad = network.gradient(x_batch, t_batch)
    
    # 更新参数
    for key in ('W1', 'b1', 'W2', 'b2'):
        network.params[key] -= learning_rate * grad[key]
    
    loss = network.loss(x_batch, t_batch)
    train_loss_list.append(loss)
    
    if i % iter_per_epoch == 0:
        train_acc = network.accuracy(x_train, t_train)
        test_acc = network.accuracy(x_test, t_test)
        train_acc_list.append(train_acc)
        test_acc_list.append(test_acc)
        print("train acc, test acc | " + str(train_acc) + ", " + str(test_acc))

# 绘制图形
markers = {'train': 'o', 'test': 's'}
x = np.arange(len(train_acc_list))
plt.plot(x, train_acc_list, label='train acc')
plt.plot(x, test_acc_list, label='test acc', linestyle='--')
plt.xlabel("epochs")
plt.ylabel("accuracy")
plt.ylim(0, 1.0)
plt.legend(loc='lower right')
plt.show()

 图中实线表示训练数据的识别精度,虚线表示测试数据的识别精度。随着epoch(学习的进行),训练数据和测试数据评价的识别精度都提高了,并且两个线基本冲别再一起。因此可以说,此次学习过程没有发生过拟合现象。


总结

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rachel MuZy

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值