深度学习入门(二):神经网络的学习
神经网络的学习
这里所说的“学习”是指从训练数据中自动获取最优权重参数的过程。
损失函数
神经网络的学习通过某个指标表示现在的状态,然后,以这个指标维基准,寻找最优权重参数,神经网络的学习中所用的指标称为损失函数
均方误差
E
=
1
2
∑
k
(
y
k
−
t
k
)
2
E = \frac{1} {2}\sum_k(y_k-t_k)^2
E=21k∑(yk−tk)2
这里,
y
k
y_k
yk 表示神经网络的输出,
t
k
t_k
tk表示监督数据,k表示数据的维度
def mean_squared error(y, t):
return 0.5 * np.sum((y-t)**2)
交叉熵误差
E
=
−
∑
k
t
k
l
o
g
e
y
k
E = -\sum_kt_klog_{e}y_k
E=−k∑tklogeyk
y
k
y_k
yk是神经网络的输出,
t
k
t_k
tk是正确解标签
由于
t
k
t_k
tk中只有正确解标签的索引为1,其他均为0(one_hot表示)。因此,式实际上只计算对于正确标签的输出的自然对数。
交叉熵误差的值是由正确标签所对应的输出结果决定的。
def cross_entropy_error(y, t):
delta = le-7
return -np.sum(t * np.log(y + delta))
函数内部在计算np.log时,加上了一个微小值delta。这是因为,当出现np.log(0)时,np.log(0)会变为负无限大的-inf,这样一来就会导致后续计算无法进行,作为保护性对策,添加一个微小值防止负无限大的发生。
mini-batch学习
当数据集的训练数据很大的情况下,如果以全部数据为对象求损失函数的和,则计算过程需要花费较长的时间。因此,我们从全部数据中选出一部分,作为全部数据的“近似”。神经网络的学习也是从训练数据中选出一批数据(称为mini-batch,小批量)。然后对每个mini-batch进行学习。称为mini-batch学习。
那么,如何从训练数据中抽取数据呢。
np.random.choice()
train_size = x_train.shape[0]
batch_size = 10
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
y_batch = y_train[batch_mask]
使用**np.random.choice()**可以从指定的数字中随机选择想要的数字
mini-batch版交叉熵误差的实现
def cross_entropy_error(y, t):
delta = le-7
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
batch_size = y.shape[0]
return -np.sum(t * np.log(y + delta)) / batch_size
当t中的标签不是以one-hot形式储存的时候,需要改变一下
def cross_entropy_error(y, t):
delta = 1e-7
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
if y.size == t.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + delta)) / batch_size
为何要设定损失函数
有些人要问“为什么要导入损失函数呢?”。以数字识别任务为例,我们想获得的是能提高识别精度的参数。那为什么不直接把“识别精度”作为指标呢?
之所以不能用识别精度作为指标。是因为这样一来绝大多数地方的导数为0,导数无法更新。换句话说,就是如果以识别精度作为指标,即使稍微改变权重参数的值,识别精度也仍将保持在原来的地方,不会出现变化。它的值不会连续变化,而如果把损失函数作为指标,则当前损失函数的值可以表示连续的值。如果稍微改变参数的值,对应得损失函数也会发生连续性的变化。
学习算法的实现
步骤:
- 从训练数据中随机选出一部分数据,这部分数据称为mini-batch。我们的目标是减少mini-batch的损失函数的值。
- 为了减少mini-batch的损失函数的值,需要求出各个权重参数的梯度。梯度表示损失函数的值减少最多的方向。
- 将权重参数沿梯度方向进行微小更新
- 重复步骤1,2,3
这个方法通过梯度下降更新参数,称为随机梯度下降法。由一个名为SGD的函数来实现
2层神经网络的类
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x) # 溢出对策
return np.exp(x) / np.sum(np.exp(x))
def cross_entropy_error(y, t):
if y.ndim == 1:
y.reshape(1,y.size)
t.reshape(1,t.size)
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = t.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
def numerical_gradient(f, x):
h = 1e-4
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi-index'],op_flags=['readwrite'])
with not it.finished:
idx = it.multi_index
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x)
x[idx] = float(tmp_val) - h
fxh2 = f(x)
grad[idx] = (fxh1-fxh2) / (2 * h)
x[idx] = tmp_val
it.iternext()
return grad
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)
t = np.argmax(t, axis=1)
accuracy = np.sum(y == t) / float(x.shape[0])
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'])
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
对于np.nditer()函数不了解的可以看
https://blog.csdn.net/weixin_46013817/article/details/111461441
mini-batch的实现
import numpy as np
from cp3.mnist import load_mnist
from two_layer_net import TwoLayerNet
import matplotlib.pyplot as plt
(x_train, y_train), (x_test, y_test) = load_mnist(normalize=True, one_hot_label=True)
train_loss_list = []
# 超参数
iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1
network = TwoLayerNet(input_size=784,hidden_size=50,output_size=10)
for i in range(iters_num):
# 获取mini-batch
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
y_batch = y_train[batch_mask]
grad = network.numerical_gradient(x_batch, y_batch)
for key in ('W1','b1','W2','b2'):
network.params[key] -= learning_rate * grad[key]
loss = network.loss(x_batch, y_batch)
train_loss_list.append(loss)
print(loss)
x = np.arange(iters_num)
plt.plot(x,train_loss_list)
plt.show()

基于测试数据的评价
根据图所示我们确认了通过反复学习可以使损失函数的值逐渐减小这一事实。神经网络的最初目标是掌握泛化能力,因此,要评价神经网络的泛化能力,就必须使用不包含在训练数据中的数据。下面的代码在进行学习的过程中,会定期地对训练数据和测试数据记录识别精度。
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的前进,使用训练数据和测试数据评价的识别精度都提高了,并且这两个识别精度基本上没有差异,可以说这次学习中没有发生过拟合的现象。
如果对epoch的概念不是很了解的话,可以看我的另一篇博客epoch的描述。
说明
此为本人学习《深度学习入门》的学习笔记,详情请阅读原书