深度学习过程反向传播有关sigmoid的求导

原文链接:https://www.jianshu.com/p/338f59196ef8

反向传播算法,简称BP算法,适合于多层神经元网络的一种学习算法,它建立在梯度下降法的基础上。BP网络的输入输出关系实质上是一种映射关系:一个n输入m输出的BP神经网络所完成的功能是从n维欧氏空间向m维欧氏空间中一有限域的连续映射,这一映射具有高度非线性。它的信息处理能力来源于简单非线性函数的多次复合,因此具有很强的函数复现能力。这是BP算法得以应用的基础。

BP算法的学习过程由正向传播过程和反向传播过程组成。在正向传播过程中,输入信息通过输入层经隐含层,逐层处理并传向输出层。如果在输出层得不到期望的输出值,则取输出与期望的误差的平方和作为目标函数,转入反向传播,逐层求出目标函数对各神经元权值的偏导数,构成目标函数对权值向量的梯量,作为修改权值的依据,网络的学习在权值修改过程中完成。误差达到所期望值时,网络学习结束。

在深度学习的反向传播过程中,我们需要对激活函数进行求偏导,这里写一点如果激活函数是sigmoid函数的时候,其求导过程。
在这里插入图片描述

在经历一次前向传播后,我们会得到一个输出yi,同时我们利用mse作为损失函数,计算预测值和标签值之间的误差。
在反向传播时,以误差对w进行偏导计算为例子,根据求得的偏导再对w进行参数更新,这一步骤和梯度下降法更新是一个原理。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
感谢您的提问!我可以为您解答以下几点问题: 1. 使用 NUMPY 工具包读取和预处理数据,包括划分数据集为训练数据集和测试数据集。 可以使用以下代码进行数据读取和划分: ```python import numpy as np from sklearn.model_selection import train_test_split # 读取数据 data = np.loadtxt('data.txt', delimiter=',') X = data[:, :-1] y = data[:, -1] # 划分数据集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 其中,`data.txt` 为数据文件,`test_size` 参数为测试集占比,`random_state` 为随机数种子,保证每次随机划分结果一致。 2. 手写代码,利用 numpy,实现感知机,前三层前馈神经网络,利用反向传播算法梯度求导更新网络参数。 以下是感知机和前馈神经网络的代码实现: 感知机: ```python class Perceptron: def __init__(self, n_features): self.w = np.zeros(n_features) self.b = 0 def fit(self, X, y, learning_rate=0.1, max_epochs=100): for epoch in range(max_epochs): for i in range(X.shape[0]): xi = X[i] yi = y[i] if yi * (np.dot(xi, self.w) + self.b) <= 0: self.w += learning_rate * yi * xi self.b += learning_rate * yi def predict(self, X): return np.sign(np.dot(X, self.w) + self.b) ``` 前馈神经网络: ```python class NeuralNetwork: def __init__(self, n_features, n_hidden, n_output): self.weights1 = np.random.rand(n_features, n_hidden) self.bias1 = np.random.rand(n_hidden) self.weights2 = np.random.rand(n_hidden, n_output) self.bias2 = np.random.rand(n_output) def sigmoid(self, x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(self, x): return x * (1 - x) def fit(self, X, y, learning_rate=0.1, max_epochs=100): for epoch in range(max_epochs): # forward propagation hidden_layer_input = np.dot(X, self.weights1) + self.bias1 hidden_layer_output = self.sigmoid(hidden_layer_input) output_layer_input = np.dot(hidden_layer_output, self.weights2) + self.bias2 output_layer_output = self.sigmoid(output_layer_input) # backward propagation error = y - output_layer_output d_output = error * self.sigmoid_derivative(output_layer_output) error_hidden = d_output.dot(self.weights2.T) d_hidden = error_hidden * self.sigmoid_derivative(hidden_layer_output) # update weights and biases self.weights2 += learning_rate * hidden_layer_output.T.dot(d_output) self.bias2 += learning_rate * np.sum(d_output, axis=0) self.weights1 += learning_rate * X.T.dot(d_hidden) self.bias1 += learning_rate * np.sum(d_hidden, axis=0) def predict(self, X): hidden_layer_input = np.dot(X, self.weights1) + self.bias1 hidden_layer_output = self.sigmoid(hidden_layer_input) output_layer_input = np.dot(hidden_layer_output, self.weights2) + self.bias2 output_layer_output = self.sigmoid(output_layer_input) return np.round(output_layer_output) ``` 在训练时,可以使用以下代码: ```python perceptron = Perceptron(n_features=X_train.shape[1]) perceptron.fit(X_train, y_train) nn = NeuralNetwork(n_features=X_train.shape[1], n_hidden=4, n_output=1) nn.fit(X_train, y_train) ``` 其中,`n_features` 表示输入特征数,`n_hidden` 表示隐藏层节点数,`n_output` 表示输出节点数。在 `fit` 函数中,`learning_rate` 表示学习率,`max_epochs` 表示最大迭代次数。 3. 利用 sklearn 库或深度学习库,实现 MNIST 数据集的前馈神经网络。比较测试结果,对比自己手写代码和机器学习 sklearn 库算法结果。 以下是使用 sklearn 库实现的前馈神经网络: ```python from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score mlp = MLPClassifier(hidden_layer_sizes=(4,), max_iter=1000) mlp.fit(X_train, y_train) y_pred = mlp.predict(X_test) acc_sklearn = accuracy_score(y_test, y_pred) print('sklearn accuracy:', acc_sklearn) ``` 其中,`hidden_layer_sizes` 表示隐藏层节点数,`max_iter` 表示最大迭代次数。 使用深度学习库 PyTorch 实现前馈神经网络: ```python import torch import torch.nn as nn import torch.optim as optim class Net(nn.Module): def __init__(self, n_features, n_hidden, n_output): super(Net, self).__init__() self.fc1 = nn.Linear(n_features, n_hidden) self.fc2 = nn.Linear(n_hidden, n_output) def forward(self, x): x = torch.sigmoid(self.fc1(x)) x = torch.sigmoid(self.fc2(x)) return x net = Net(n_features=X_train.shape[1], n_hidden=4, n_output=1) optimizer = optim.Adam(net.parameters(), lr=0.01) criterion = nn.BCELoss() for epoch in range(1000): optimizer.zero_grad() inputs = torch.from_numpy(X_train).float() labels = torch.from_numpy(y_train.reshape(-1, 1)).float() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() outputs = net(torch.from_numpy(X_test).float()) y_pred = np.round(outputs.detach().numpy()) acc_pytorch = accuracy_score(y_test, y_pred) print('pytorch accuracy:', acc_pytorch) ``` 其中,`n_features` 表示输入特征数,`n_hidden` 表示隐藏层节点数,`n_output` 表示输出节点数。在训练时,使用 Adam 优化器和二元交叉熵损失函数。 最后,可以使用以下代码对比自己手写代码和机器学习库算法的结果: ```python y_pred = perceptron.predict(X_test) acc_perceptron = accuracy_score(y_test, y_pred) print('perceptron accuracy:', acc_perceptron) y_pred = nn.predict(X_test) acc_nn = accuracy_score(y_test, y_pred) print('nn accuracy:', acc_nn) print('sklearn accuracy:', acc_sklearn) print('pytorch accuracy:', acc_pytorch) ``` 其中,`accuracy_score` 函数用于计算分类准确率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值