python3+TensorFlow 2.x(四)反向传播

server/2025/2/2 1:32:43/

目录

反向传播算法

反向传播算法基本步骤:

反向中的参数变化

总结


反向传播算法

反向传播算法(Backpropagation)是训练人工神经网络时使用的一个重要算法,它是通过计算梯度并优化神经网络的权重来最小化误差。反向传播算法的核心是基于链式法则的梯度下降优化方法,通过计算误差对每个权重的偏导数来更新网络中的参数。

反向传播算法基本步骤:

前向传播:将输入数据传递通过神经网络的各层,计算每一层的输出。
计算损失:根据输出和实际标签计算损失(通常使用均方误差或交叉熵等作为损失函数)。
反向传播:根据损失函数对每个参数(如权重、偏置)计算梯度。梯度的计算通过链式法则进行反向传播,直到达到输入层。
更新权重:使用梯度下降算法来更新每一层的权重和偏置,使得损失函数最小化。

链式推到:https://blog.csdn.net/dingyahui123/category_6945552.html?spm=1001.2014.3001.5482

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()# 归一化数据并将其形状调整为 (N, 784),因为每张图片是 28x28 像素
train_images = train_images.reshape(-1, 28*28) / 255.0
test_images = test_images.reshape(-1, 28*28) / 255.0# 转换标签为 one-hot 编码
train_labels = np.eye(10)[train_labels]
test_labels = np.eye(10)[test_labels]
# 定义激活函数
def sigmoid(x):return 1 / (1 + np.exp(-x))# 定义激活函数的导数
def sigmoid_derivative(x):return x * (1 - x)# 网络架构参数
input_size = 28 * 28  # 输入层的大小
hidden_size = 128     # 隐藏层的大小
output_size = 10      # 输出层的大小# 初始化权重和偏置
W1 = np.random.randn(input_size, hidden_size)  # 输入层到隐藏层的权重
b1 = np.zeros((1, hidden_size))  # 隐藏层的偏置
W2 = np.random.randn(hidden_size, output_size)  # 隐藏层到输出层的权重
b2 = np.zeros((1, output_size))  # 输出层的偏置
# 设置超参数
epochs = 20
learning_rate = 0.1
batch_size = 64# 训练过程
for epoch in range(epochs):for i in range(0, len(train_images), batch_size):# 选择当前batch的数据X_batch = train_images[i:i+batch_size]y_batch = train_labels[i:i+batch_size]# 前向传播z1 = np.dot(X_batch, W1) + b1a1 = sigmoid(z1)z2 = np.dot(a1, W2) + b2a2 = sigmoid(z2)# 计算损失的梯度output_error = a2 - y_batch  # 损失函数的梯度output_delta = output_error * sigmoid_derivative(a2)hidden_error = output_delta.dot(W2.T)hidden_delta = hidden_error * sigmoid_derivative(a1)# 更新权重和偏置W2 -= learning_rate * a1.T.dot(output_delta)b2 -= learning_rate * np.sum(output_delta, axis=0, keepdims=True)W1 -= learning_rate * X_batch.T.dot(hidden_delta)b1 -= learning_rate * np.sum(hidden_delta, axis=0, keepdims=True)# 每10轮输出一次损失if epoch % 10 == 0:loss = np.mean(np.square(a2 - y_batch))print(f"Epoch {epoch}, Loss: {loss}")
# 测试模型
z1 = np.dot(test_images, W1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, W2) + b2
a2 = sigmoid(z2)# 计算准确率
predictions = np.argmax(a2, axis=1)
true_labels = np.argmax(test_labels, axis=1)
accuracy = np.mean(predictions == true_labels)print(f"Test Accuracy: {accuracy * 100:.2f}%")
# 可视化前5个测试图像及其预测结果
for i in range(5):plt.imshow(test_images[i].reshape(28, 28), cmap='gray')plt.title(f"Predicted: {predictions[i]}, Actual: {true_labels[i]}")plt.show()

 

反向中的参数变化

python">import numpy as np
import matplotlib.pyplot as plt
import imageio# 激活函数和其导数
def sigmoid(x):return 1 / (1 + np.exp(-x))def sigmoid_derivative(x):return x * (1 - x)# 生成一些示例数据
np.random.seed(0)
X = np.array([[0, 0],[0, 1],[1, 0],[1, 1]])
y = np.array([[0], [1], [1], [0]])  # XOR 问题# 初始化参数
input_layer_neurons = 2
hidden_layer_neurons = 2
output_neurons = 1
learning_rate = 0.5
epochs = 10000# 初始化权重
weights_input_hidden = np.random.uniform(size=(input_layer_neurons, hidden_layer_neurons))
weights_hidden_output = np.random.uniform(size=(hidden_layer_neurons, output_neurons))# 存储权重和图像
weights_history = []
losses = []
images = []# 训练过程
for epoch in range(epochs):# 前向传播hidden_layer_input = np.dot(X, weights_input_hidden)hidden_layer_output = sigmoid(hidden_layer_input)output_layer_input = np.dot(hidden_layer_output, weights_hidden_output)predicted_output = sigmoid(output_layer_input)loss = np.mean((y - predicted_output) ** 2)losses.append(loss)# 反向传播error = y - predicted_outputd_predicted_output = error * sigmoid_derivative(predicted_output)error_hidden_layer = d_predicted_output.dot(weights_hidden_output.T)d_hidden_layer = error_hidden_layer * sigmoid_derivative(hidden_layer_output)# 更新权重weights_hidden_output += hidden_layer_output.T.dot(d_predicted_output) * learning_rateweights_input_hidden += X.T.dot(d_hidden_layer) * learning_rate# 保存权重weights_history.append((weights_input_hidden.copy(), weights_hidden_output.copy()))# 每1000次迭代保存一次图像if epoch % 1000 == 0:plt.figure(figsize=(8, 6))plt.subplot(1, 2, 1)plt.title('Weights Input-Hidden')plt.imshow(weights_input_hidden, cmap='viridis', aspect='auto')plt.colorbar()plt.subplot(1, 2, 2)plt.title('Weights Hidden-Output')plt.imshow(weights_hidden_output, cmap='viridis', aspect='auto')plt.colorbar()# 保存图像plt.savefig(f'weights_epoch_{epoch}.png')plt.close()if epoch % 1000 == 0:plt.figure(figsize=(8, 6))plt.plot(losses, label='Loss')plt.title('Loss over epochs')plt.xlabel('Epochs')plt.ylabel('Loss')plt.xlim(0, epochs)plt.ylim(0, np.max(losses))plt.grid()plt.legend()# 保存图像plt.savefig(f'loss_epoch_{epoch}.png')plt.close()
# 创建 GIF
with imageio.get_writer('weights_update.gif', mode='I', duration=0.5) as writer:for epoch in range(0, epochs, 1000):image = imageio.imread(f'weights_epoch_{epoch}.png')writer.append_data(image)
# 创建 GIF
with imageio.get_writer('training_loss.gif', mode='I', duration=0.5) as writer:for epoch in range(0, epochs, 1000):image = imageio.imread(f'loss_epoch_{epoch}.png')writer.append_data(image)
# 清理生成的图像文件
import os
for epoch in range(0, epochs, 1000):os.remove(f'weights_epoch_{epoch}.png')os.remove(f'loss_epoch_{epoch}.png')print("GIF 已生成:training_loss.gif")
print("GIF 已生成:weights_update.gif")

 

总结

反向传播算法是神经网络训练中的核心技术,它通过计算损失函数相对于每个权重和偏置的梯度,利用梯度下降算法优化网络的参数。理解了反向传播的基本过程,可以进一步扩展到更复杂的网络结构,如卷积神经网络(CNN)和循环神经网络(RNN)。


http://www.ppmy.cn/server/164218.html

相关文章

vue中的el是指什么

简介: 在Vue.js中,el指的是Vue实例的挂载元素。 具体来说,el是一个选项,用于指定Vue实例应该挂载到哪个DOM元素上。通过这个选项,Vue可以知道应该从哪个元素开始进行模板编译和渲染。它可以是一个CSS选择器字符串&…

AD电路仿真

目录 0 前言 仿真类型 仿真步骤 仿真功能及参数设置 仿真模型 应用优势 1 新建原理图 2 放置元器件及布线 3 放置探头 4 实验结果 Operating Point 分析的作用 DC Sweep 的主要功能 Transient Analysis 的主要功能 AC Analysis 的功能 5 总结 1. 直流工作点分析…

docker desktop使用ollama在GPU上运行deepseek r1大模型

一、安装docker 安装WSL打开Hyper V 可以参考:用 Docker 快速安装软件_哔哩哔哩_bilibili 二、拉取ollama镜像 在powershell中运行如下命令,即可拉取最新版本的ollama镜像: docker pull ollama/ollama 如果需要指定版本,可以…

【2024年华为OD机试】 (C卷,200分)- 矩阵匹配(JavaScriptJava PythonC/C++)

一、问题描述 问题描述 给定一个大小为 ( N \times M )(( N \leq M ))的矩阵,从中选出 ( N ) 个数,要求任意两个数字不能在同一行或同一列。求选出来的 ( N ) 个数中第 ( K ) 大的数字的最小值。 输入描述 输入矩阵要求:( 1 \leq K \leq N \leq M \leq 150 )输入格式:…

CAP 定理的 P 是什么

分布式系统 CAP 定理 P 代表什么含义 作者之前在看 CAP 定理时抱有很大的疑惑,CAP 定理的定义是指在分布式系统中三者只能满足其二,也就是存在分布式 CA 系统的。作者在网络上查阅了很多关于 CAP 文章,虽然这些文章对于 P 的解释五花八门&am…

基础项目实战——学生管理系统(c++)

目录 前言一、功能菜单界面二、类与结构体的实现三、录入学生信息四、删除学生信息五、更改学生信息六、查找学生信息七、统计学生人数八、保存学生信息九、读取学生信息十、打印所有学生信息十一、退出系统十二、文件拆分结语 前言 这一期我们来一起学习我们在大学做过的课程…

【算法】经典博弈论问题——斐波那契博弈 + Zeckendorf 定理 python

目录 斐波那契博弈(Fibonacci Nim)齐肯多夫(Zeckendorf)定理示例分析实战演练 斐波那契博弈(Fibonacci Nim) 先说结论:当初始石子数目 n 是斐波那契数时,先手必败;否则&a…

[EAI-029] RoboVLMs,基于VLM构建VLA模型的消融研究

Paper Card 论文标题:Towards Generalist Robot Policies: What Matters in Building Vision-Language-Action Models 论文作者:Xinghang Li, Peiyan Li, Minghuan Liu, Dong Wang, Jirong Liu, Bingyi Kang, Xiao Ma, Tao Kong, Hanbo Zhang, Huaping L…