建设网站导航怎么盈利,网站建设行业的前景,龙岩天宫山旅游攻略,wordpress评论翻页基于随机梯度下降法的手写数字识别、epoch是什么、python实现一、普通的随机梯度下降法的手写数字识别1.1 学习流程1.2 二层神经网络类1.3 使用MNIST数据集进行学习注#xff1a;关于什么是epoch二、基于误差反向传播算法求梯度的手写数字识别2.1 学习流程2.2 实现与结果分析一…
基于随机梯度下降法的手写数字识别、epoch是什么、python实现一、普通的随机梯度下降法的手写数字识别1.1 学习流程1.2 二层神经网络类1.3 使用MNIST数据集进行学习注关于什么是epoch二、基于误差反向传播算法求梯度的手写数字识别2.1 学习流程2.2 实现与结果分析一、普通的随机梯度下降法的手写数字识别
1.1 学习流程
1.从训练数据中随机选择一部分数据
2.计算损失函数关于各个权重参数的梯度
这里面用数值微分方法求梯度
3.将权重参数沿梯度方向进行微小的更新
4.重复前三个步骤
1.2 二层神经网络类
params保存神经网络参数的字典型变量
grads保存梯度的字典型变量
def __init__(self, input_size, hidden_size, output_size, weight_init_std0.01):input_size输入层神经元个数
hidden_size隐藏层神经元个数
output_size输出层神经元个数
def predict(self, x):进行识别x图像数据 def loss(self, x, t):求损失函数x图像数据t正确解标签
def accuracy(self, x, t):计算识别精度 def numerical_gradient(self, x, t):计算权重参数梯度
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 为了导入父目录的文件而进行的设定
from common.functions import *
from common.gradient import numerical_gradientclass TwoLayerNet:def __init__(self, input_size, hidden_size, output_size, weight_init_std0.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) b1z1 sigmoid(a1)a2 np.dot(z1, W2) b2y 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, axis1)t np.argmax(t, axis1)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 def numerical_gradient(f, x):h 1e-4 # 0.0001grad np.zeros_like(x)it np.nditer(x, flags[multi_index], op_flags[readwrite])while not it.finished:idx it.multi_indextmp_val x[idx]x[idx] float(tmp_val) hfxh1 f(x) # f(xh)x[idx] tmp_val - h fxh2 f(x) # f(x-h)grad[idx] (fxh1 - fxh2) / (2*h)x[idx] tmp_val # 还原值it.iternext() return grad1.3 使用MNIST数据集进行学习
这里面用的是数值微分方法求梯度速度超级慢。
iters_num是梯度法的更新次数。
batch_size 100说明每次从60000个训练数据中随机取出100个数据。
对这100个数据求梯度然后用梯度下降法更新参数更新iters_num次。
最后可以画出来一个损失函数的图的确是下降的。
注关于什么是epoch
什么是epoch我们在代码里可以很清楚理解。
先来一段源码分析
这个代码中可看出epochs是len(train_acc_list)。
x np.arange(len(train_acc_list))
plt.plot(x, train_acc_list, labeltrain acc)
plt.xlabel(epochs)我们看train_acc_list它其实是在进行if i % iter_per_epoch 0判断后才添加的。
也就是说每经过一个epoch就对所有训练数据和测试数据计算识别精度。
那么就可以知道了epoch的作用就是不那么频繁的记录识别精度毕竟只要从大方向上大致把握识别精度即可。
train_acc_list []
test_acc_list []
#平均每个epoch的重复次数
iter_per_epoch max(train_size / batch_size, 1)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))那现在就知道epoch是什么了吧其实它就是网络里面经过多少次数据学习之后再求整体的网络精度。
# 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(normalizeTrue, one_hot_labelTrue)network TwoLayerNet(input_size784, hidden_size50, output_size10)iters_num 10000 # 适当设定循环的次数
train_size x_train.shape[0]
batch_size 100
learning_rate 0.1train_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)#计算每个epoch的识别精度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, labeltrain acc)
plt.plot(x, test_acc_list, labeltest acc, linestyle--)
plt.xlabel(epochs)
plt.ylabel(accuracy)
plt.ylim(0, 1.0)
plt.legend(loclower right)
plt.show()
x np.arange(len(train_loss_list))
plt.plot(x, train_loss_list, labeltrain lost)
plt.xlabel(iteration)
plt.ylabel(loss)
plt.ylim(0, 3)
plt.show()二、基于误差反向传播算法求梯度的手写数字识别
2.1 学习流程
1.从训练数据中随机选择一部分数据
2.计算损失函数关于各个权重参数的梯度
这里面用误差反向传播算法求梯度
3.将权重参数沿梯度方向进行微小的更新
4.重复前三个步骤
2.2 实现与结果分析
和第一个类似只不过改动了求梯度的函数 def gradient(self, x, t):W1, W2 self.params[W1], self.params[W2]b1, b2 self.params[b1], self.params[b2]grads {}batch_num x.shape[0]# forwarda1 np.dot(x, W1) b1z1 sigmoid(a1)a2 np.dot(z1, W2) b2y softmax(a2)# backwarddy (y - t) / batch_numgrads[W2] np.dot(z1.T, dy)grads[b2] np.sum(dy, axis0)da1 np.dot(dy, W2.T)dz1 sigmoid_grad(a1) * da1grads[W1] np.dot(x.T, dz1)grads[b1] np.sum(dz1, axis0)return grads然后调用的时候调用下面这句话
grad network.gradient(x_batch, t_batch)最终结果
下面这个图是随着网络对训练数据和测试数据训练次数的增加网络识别精度的变化。 下面这个图表示朝着梯度下将方向走10000次过程中loss逐渐减小。