在学习后关于神经网络基础知识,如损失函数,梯度法,数值微分等内容之后,在最后我们搭建一个二层网络,来实现网络的学习算法。
下面展示整体代码。
import sys,os
sys.path.append(os.pardir)
import numpy as np
def sigmoid(x):
return 1/(1 + np.exp(-x))
def softmax(a):
c = np.max(a)
exp_a = np.exp(a -c) #溢出对策
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
#因为出现np.log(0)时,np.log(0)会变成负无限大的-inf,添加一个微小值delta可以防止此现象发生
def cross_entropy_error(y,t):
delta = 1e-7
return -np.sum(t * np.log(y + delta))
#数值微分计算梯度法
def numerical_gradient(f,x):
h = 1e-4
grad = np.zeros_like(x) #生成和x形状相同的数组
for idx in range(x.size):
tmp_val = x[idx]
#f(x + h)的计算
x[idx] = tmp_val + h
fxh1 = f(x)
#f(x -h)的计算
x[idx] = tmp_val - h
fxh2 = f(x)
grad[idx] = (fxh1 - fxh2) / (2*h)
x[idx] =tmp_val #还原值
return grad
class TwoLayerNet():
def __init__(self,input_size,hidden_size,output_size,weight_init_std = 0.01):
self.params = {}
self.paramas['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[''] = 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
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
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
此代码为书中(111页)代码的改写,将sigmoid,交叉熵损失函数和梯度计算法(数值微分)用函数的方式写处,不再使用import的方式引入。让整体代码更加容易理解。
下面说说对激活函数和损失函数的理解和用python实现时的注意事项。
1.sigmoid函数:
h(x)=
1
1
+
e
x
p
(
−
x
)
\frac{1}{1+exp(-x)}
1+exp(−x)1
其中exp(-x)表示e^(-x)。e即为纳皮尔常数2.7182…
在实现sigmoid函数时的python代码为
def sigmoid(x):
return 1/(1 + np.exp(-x))
其中注意np.exp(-x),这里对应的是原式中的exp(-x)。当用np.exp(-x)表示时,参数x若为Numpy数组也可以正确计算。
注意为什么要使用sigmoid这样的非线性函数作为激活函数:因为当使用线性函数时,不管怎样加深层数,总是存在与之等效的“无隐藏层的神经网络”
举个例子:若将h(x) = cx作为激活函数,把y(x) = h(h(h(x)))作为一个对应的三层神经网络。同样的若令一个a = c * c * c,即存在一个a = c**3,使y(x)=ax与之等效(即为一个没有隐藏层的神经网络)
2.softmax函数:
我们先引入一个关于softmax函数的推导
我们现在分子和分母上都乘上C这个任意常数(分母和分子同时乘以一个相同常数结果不变)然后再把C移动进入exp,记为logC。最后将logC替换为一个新的常数C’(C’ = logC)
这个推导过程说明进行softmax函数的运算时,加上或者减去某个常数并不会改变运算结果。
我们便可以用这种方法解决使用sofxmax函数时的溢出问题。
什么是溢出问题?
当计算e10时,结果就会超过20000,而e100的值便会达到一个10的四十次方以上的超大数值。e**1000时便会返回表示无穷大的inf。这时便是一种溢出。(超大值无法表示的问题)
此时np数组输出的结果中元素为 nan(not a number,不确定)
为了解决这个问题我们使用上述推导出的方法表示softmax函数:
def softmax(a):
c = np.max(a)
exp_a = np.exp(a -c) #解决溢出问题
sum_exp_a = np.sum(exp_a)
y = exp_a / sum_exp_a
return y
3.交叉熵损失函数(cross_entropy_error)
交叉熵误差的值是由正确解标签所对应的输出结果决定的。
下面是python的实现
def cross_entropy_error(y,t):
delta = 1e-7
return -np.sum(t * np.log(y + delta))
此时注意,因为出现np.log(0)时,np.log(0)会变成负无限大的-inf,添加一个微小值delta可以防止此现场发生。
下面用mini—batch实现学习过程:
我们引入一个epoch的概念,epoch是一个单位,一个epoch表示学习中所有训练数据均被使用过以此时的更新次数。例如,对于10000笔训练数据,用大小为100笔数据的mini-batch进行学习时,重复随机梯度下降法(SGD)100次,所有数据就都遍历过了,此时100便为一个epoch。
代码如下
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 为了导入父目录的文件而进行的设定
import numpy as np
from mnist import load_mnist
from TwoLayerNet import TwoLayerNet
import matplotlib.pyplot as plt
# 读入数据
(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 = []
#平均每个epoch的重复次数
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))