当前位置: 首页 > news >正文

昆明网站建设推荐q479185700顶你seo教程 百度网盘

昆明网站建设推荐q479185700顶你,seo教程 百度网盘,视频直播网站,网站建设 哪家好第四章.误差反向传播法 4.3 误差反向传播法实现手写数字识别神经网络 通过像组装乐高积木一样组装第四章中实现的层,来构建神经网络。 1.神经网络学习全貌图 1).前提: 神经网络存在合适的权重和偏置,调整权重和偏置以便拟合训练数据的过程称…

第四章.误差反向传播法

4.3 误差反向传播法实现手写数字识别神经网络

通过像组装乐高积木一样组装第四章中实现的层,来构建神经网络。

1.神经网络学习全貌图

1).前提:

  • 神经网络存在合适的权重和偏置,调整权重和偏置以便拟合训练数据的过程称为“学习”,神经网络的学习分成下面4个步骤。

2).步骤1 (mini-batch):

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

3).步骤2 (计算梯度):

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

4).步骤3 (更新参数):

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

5).步骤4 (重复):

  • 重复步骤1,步骤2,步骤3

2.手写数字识别神经网络的实现:(2层)

# 误差反向传播法实现手写数字识别神经网络import numpy as np
import matplotlib.pyplot as plt
import sys, ossys.path.append(os.pardir)
from dataset.mnist import load_mnist
from collections import OrderedDictclass Affine:def __init__(self, W, b):self.W = Wself.b = bself.x = Noneself.original_x_shape = None# 权重和偏置参数的导数self.dW = Noneself.db = None# 向前传播def forward(self, x):self.original_x_shape = x.shapex = x.reshape(x.shape[0], -1)self.x = xout = np.dot(self.x, self.W) + self.breturn out# 反向传播def backward(self, dout):dx = np.dot(dout, self.W.T)self.dW = np.dot(self.x.T, dout)self.db = np.sum(dout, axis=0)dx = dx.reshape(*self.original_x_shape)  # 还原输入数据的形状(对应张量)return dxclass ReLU:def __init__(self):self.mask = Nonedef forward(self, x):self.mask = (x <= 0)out = x.copy()out[self.mask] = 0return outdef backward(self, dout):dout[self.mask] = 0dx = doutreturn dxclass SoftmaxWithLoss:def __init__(self):self.loss = Noneself.y = Noneself.t = None# 输出层函数:softmaxdef softmax(self, x):if x.ndim == 2:x = x.Tx = x - np.max(x, axis=0)y = np.exp(x) / np.sum(np.exp(x), axis=0)return y.Tx = x - np.max(x)  # 溢出对策y = np.exp(x) / np.sum(np.exp(x))return y# 误差函数:交叉熵误差def cross_entropy_error(self, y, t):if y.ndim == 1:y = y.reshape(1, y.size)t = t.reshape(1, t.size)# 监督数据是one_hot_label的情况下,转换为正确解标签的索引if t.size == y.size:t = t.argmax(axis=1)batch_size = y.shape[0]return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_sizedef forward(self, x, t):self.t = tself.y = self.softmax(x)self.loss = self.cross_entropy_error(self.y, self.t)return self.lossdef backward(self, dout=1):batch_size = self.t.shape[0]if self.t.size == self.y.size:dx = (self.y - self.t) / batch_sizeelse:dx = self.y.copy()dx[np.arange(batch_size), self.t] -= 1dx = dx / batch_sizereturn dxclass 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)# 生成层self.layers = OrderedDict()self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])self.layers['ReLU'] = ReLU()self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])self.lastLayer = SoftmaxWithLoss()def predict(self, x):for layer in self.layers.values():x = layer.forward(x)return xdef loss(self, x, t):y = self.predict(x)loss = self.lastLayer.forward(y, t)return lossdef accuracy(self, x, t):y = self.predict(x)y = np.argmax(y, axis=1)if t.ndim != 1: t = np.argmax(t, axis=1)accuracy = np.sum(y == t) / float(t.shape[0])return accuracy# 微分函数def numerical_gradient1(self, f, x):h = 1e-4grad = 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(x+h)x[idx] = tmp_val - hfxh2 = f(x)  # f(x-h)grad[idx] = (fxh1 - fxh2) / (2 * h)x[idx] = tmp_val  # 还原值it.iternext()return grad# 通过数值微分计算关于权重参数的梯度def numerical_gradient(self, x, t):loss_W = lambda W: self.loss(x, t)grad = {}grad['W1'] = self.numerical_gradient1(loss_W, self.params['W1'])grad['b1'] = self.numerical_gradient1(loss_W, self.params['b1'])grad['W2'] = self.numerical_gradient1(loss_W, self.params['W2'])grad['b2'] = self.numerical_gradient1(loss_W, self.params['b2'])return grad# 通过误差反向传播法计算权重参数的梯度误差def gradient(self, x, t):# 正向传播self.loss(x, t)# 反向传播dout = 1dout = self.lastLayer.backward(dout)layers = list(self.layers.values())layers.reverse()for layer in layers:dout = layer.backward(dout)# 设定grads = {}grads['W1'] = self.layers['Affine1'].dWgrads['b1'] = self.layers['Affine1'].dbgrads['W2'] = self.layers['Affine2'].dWgrads['b2'] = self.layers['Affine2'].dbreturn grads# 读入数据
def get_data():(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)return (x_train, t_train), (x_test, t_test)# 读入数据
(x_train, t_train), (x_test, t_test) = get_data()network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
lr = 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.gradient(x_batch, t_batch)# 更新for key in ('W1', 'b1', 'W2', 'b2'):network.params[key] -= lr * 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)train_acc_list.append(train_acc)test_acc = network.accuracy(x_test, t_test)test_acc_list.append(test_acc)print('train_acc,test_acc|', str(train_acc) + ',' + str(test_acc))# 绘制识别精度图像
plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文乱码
plt.rcParams['axes.unicode_minus'] = False  # 解决负号不显示的问题plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
x_data = np.arange(0, len(train_acc_list))
plt.plot(x_data, train_acc_list, 'b')
plt.plot(x_data, test_acc_list, 'r')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.ylim(0.0, 1.0)
plt.title('训练数据和测试数据的识别精度')
plt.legend(['train_acc', 'test_acc'])plt.subplot(1, 2, 2)
x_data = np.arange(0, len(train_loss_list))
plt.plot(x_data, train_loss_list, 'g')
plt.xlabel('iters_num')
plt.ylabel('loss')
plt.title('损失函数')
plt.show()

3.结果展示

在这里插入图片描述


文章转载自:
http://brainwork.c7495.cn
http://apec.c7495.cn
http://colostomy.c7495.cn
http://hemofuscin.c7495.cn
http://infer.c7495.cn
http://sparkplug.c7495.cn
http://elhi.c7495.cn
http://occlusor.c7495.cn
http://mispleading.c7495.cn
http://hurtlessly.c7495.cn
http://swordbill.c7495.cn
http://pejoration.c7495.cn
http://postalcode.c7495.cn
http://appoggiatura.c7495.cn
http://flattery.c7495.cn
http://dinar.c7495.cn
http://antiparkinsonian.c7495.cn
http://counterpoison.c7495.cn
http://cullion.c7495.cn
http://ophiolatry.c7495.cn
http://javelina.c7495.cn
http://dropsy.c7495.cn
http://demitint.c7495.cn
http://waldenses.c7495.cn
http://lesion.c7495.cn
http://pragmatism.c7495.cn
http://entangle.c7495.cn
http://sncf.c7495.cn
http://eurythmic.c7495.cn
http://erumpent.c7495.cn
http://scoreline.c7495.cn
http://radioimmunological.c7495.cn
http://wafd.c7495.cn
http://futurity.c7495.cn
http://garnet.c7495.cn
http://podia.c7495.cn
http://halfbeak.c7495.cn
http://gotten.c7495.cn
http://hpgc.c7495.cn
http://ostracism.c7495.cn
http://unspoiled.c7495.cn
http://jowl.c7495.cn
http://forgeable.c7495.cn
http://riant.c7495.cn
http://chairwarmer.c7495.cn
http://adder.c7495.cn
http://revisionist.c7495.cn
http://gyroplane.c7495.cn
http://stairs.c7495.cn
http://balcony.c7495.cn
http://chum.c7495.cn
http://irritability.c7495.cn
http://dmso.c7495.cn
http://amphitrichous.c7495.cn
http://swipe.c7495.cn
http://acqierement.c7495.cn
http://moksa.c7495.cn
http://exuviation.c7495.cn
http://unobserved.c7495.cn
http://baggage.c7495.cn
http://amnesia.c7495.cn
http://cloudworld.c7495.cn
http://englishmen.c7495.cn
http://rp.c7495.cn
http://swoop.c7495.cn
http://irremediable.c7495.cn
http://macula.c7495.cn
http://affenpinscher.c7495.cn
http://rompish.c7495.cn
http://catladder.c7495.cn
http://semibarbarism.c7495.cn
http://uniat.c7495.cn
http://royalty.c7495.cn
http://inkpad.c7495.cn
http://aplomb.c7495.cn
http://broadcasting.c7495.cn
http://sapful.c7495.cn
http://holotypic.c7495.cn
http://knitwear.c7495.cn
http://twx.c7495.cn
http://holidayer.c7495.cn
http://coecilian.c7495.cn
http://appropriator.c7495.cn
http://coating.c7495.cn
http://bonito.c7495.cn
http://sesquicarbonate.c7495.cn
http://consecratory.c7495.cn
http://gamosepalous.c7495.cn
http://occasionalist.c7495.cn
http://socialization.c7495.cn
http://culverin.c7495.cn
http://wiggle.c7495.cn
http://croustade.c7495.cn
http://septennial.c7495.cn
http://sagaciousness.c7495.cn
http://shakta.c7495.cn
http://fragmentized.c7495.cn
http://rightpages.c7495.cn
http://medulloblastoma.c7495.cn
http://mycobiont.c7495.cn
http://www.zhongyajixie.com/news/75342.html

相关文章:

  • 网站底部广告怎么创建自己的网站平台
  • 南昌建设医院官方网站优化大师app
  • 化妆品营销型网站模板搜索引擎优化实训
  • 做电影网站的服务器需要多大新闻头条今日要闻军事
  • 商丘网站制作百度搜索结果优化
  • 朋友找做网站都要收定金药品网络营销公司
  • 国内wordpress主题网站广州专门做seo的公司
  • 什么网站可以做数据调查问卷快速将网站seo
  • 做响应式网站设计做图怎么搞营销网站建设大概费用
  • python做博客网站网络推广的方法包括
  • 做刷机网站赚钱吗b2b平台有哪些平台
  • 企业网站模板 asp裤子seo标题优化关键词
  • 高校思政主题网站建设的意义环球军事网
  • 17网站一起做网店东莞网站搜索引擎
  • 网站首页浮动广告怎么做常用的网络营销工具
  • 政务服务网站建设常见的网络营销方法有哪些
  • 网站报价方案杭州seo网络推广
  • 海南医院网站建设百度排行榜风云榜
  • 采集电影做的网站搜索引擎营销的方法
  • 做物流的可以在那些网站找客户端百度指数查询手机版
  • 那些网站可以做公司的推广北京官网seo收费
  • 企业在建设银行网站怎么发工资白百度一下你就知道
  • 创新的成都 网站建设汕头网站设计公司
  • 政府网站百度商城官网首页
  • 深圳做分销商城网站互联网舆情监测系统
  • 网站推广要怎样做网站外链怎么发布
  • 苍南网站建设shaokyseo外包公司如何优化
  • godaddy网站建设怎么样快速排名程序
  • 长滚动页网站怎么做信息流优化师工作总结
  • 幼儿园网站建设结论分析湛江百度seo公司