介绍

人工神经元

人工神经元概念

带权重的函数

  • Sigmoid函数——S型
  • th函数——双曲正切函数
  • ReLU函数——整流线性单元

单个人工神经元

模拟布尔运算
alt text
alt text
alt text
alt text

多个人工神经元

解决XOR问题(不是所有的布尔运算都可以通过单个神经元实现)
alt text

多层网络——即深度学习

梯度流

介绍

梯度流游乐场网站:https://playground.tensorflow.org/
梯度流2(TensorFlow2)软件库介绍——由谷歌大脑http://research.googleblog.com/出品的深度学习框架
官网:http://www.tensorflow.org/

概念

import tensorflow as tf

  • 张量(Tensor):在运算之间流动的数据单元。向量,矩阵,由矩阵组成的向量
  • 计算图(Graph):包含一组计算单元,和张量在计算单元之间流动的数据结构
  • 自动微分(AD):自动求导AD, 优化权重参数,使损失函数最小

多层神经网络的表述

输入层——n层隐藏层——输出层——softmax

softmax处理

alt text

logit函数

alt text

多层神经网络的训练

损失函数

损失(loss):输出值与标签值的差异

补充:
线性回归模型的损失函数是均方误差(MSE)
逻辑回归模型的损失函数是对数损失函数(如交叉熵(CE))

  1. L1损失函数
    基于模型预测和标签实际值之差的绝对值
  2. L2损失函数
    基于模型预测和标签实际值之差的平方
    所以离群值比L1更剧烈
  • 对于回归任务,用均方误差(MSE)的公式来计算误差
    均方误差:各个数据偏离真实值差值的平方和的平均数
    均方根误差:均方误差的开方——注意:不同于标准差(均方差)
    alt text
  • 对于分类任务,用交叉熵(CE)的公式来计算误差
    alt text
    alt text

alt text
alt text

反向传播算法

网络权重的自动化更新

alt text
alt text

alt text
alt text
alt text

alt text
alt text
alt text
避免中间的梯度的损失。会保存所有中间变量,以备后续传播时计算导数使用
自动微分(AD)与反向传播算法等价

梯度下降法的权重更新过程

alt text

随机梯度下降法

每次选取一个随机样本输入网络,调整一次权重
alt text

批量训练

使用整个数据集输入网络,调整一次权重

小批量训练——mini-batch
训练完一个迷你批次,称为一次迭代。当训练集中的所用样本都被送入网络,完成一次训练过程,称为一个时代
——当迷你批次大小为1时,退化为普通的随机梯度下降

正则化(regularization)

模型训练出现过拟合(Overfitting)的解决方法
alt text

L1正则化

根据权重的绝对值的总和来惩罚权重
——有助于直接移除不相关的特征

L2正则化

与L1正则化相对
根据权重的平方和来惩罚权重

有助于使离群值权重接近于0,又不为0
——改进泛化推广能力

丢弃正则化

在一个梯度步长中移除从神经网络层中随机选择的固定数量的单元
丢弃的单元越多,正则化效果越强

深度学习解决实际问题的流程

alt text
alt text

练习

用多个神经元完成XOR运算

回答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import torch
import torch.nn as nn
import torch.optim as optim

# 定义输入数据和标签
x = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)

# 定义神经网络模型
class XORNet(nn.Module):
def __init__(self):
super(XORNet, self).__init__()
self.fc1 = nn.Linear(2, 2) # 输入层到隐藏层
self.relu = nn.ReLU()
self.fc2 = nn.Linear(2, 1) # 隐藏层到输出层
self.sigmoid = nn.Sigmoid()

def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
out = self.sigmoid(out)
return out

# 实例化模型、定义损失函数和优化器
model = XORNet()
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)

# 训练模型
for epoch in range(1000):
# 前向传播
outputs = model(x)
loss = criterion(outputs, y)

# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()

if (epoch + 1) % 100 == 0:
print(f'Epoch [{epoch+1}/1000], Loss: {loss.item():.4f}')

# 测试模型
with torch.no_grad():
test_outputs = model(x)
predicted = (test_outputs >= 0.5).float()
print(f'Predicted: {predicted.squeeze().tolist()}')

建立多层神经网络

题目:
使用 TensorFlow 构建一个简单的多层神经网络,对 MNIST 数据集进行分类,并可视化训练过程中的损失和准确率变化。
作业要求
使用 TensorFlow 构建一个包含输入层、两个隐藏层和输出层的神经网络训练神经网络并记录训练过程中的损失和准确率
可视化训练过程中的损失和准确率变化输出测试集的预测结果(前10个就行)和准确率作业提交
回答:
【奇怪,最后这里有的函数要换掉。而且程序能在pycharm运行,不能在notebook运行,不知道为什么,明明是一样的配置】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
import matplotlib.pyplot as plt

# 加载 MNIST 数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 数据预处理
x_train, x_test = x_train / 255.0, x_test / 255.0

# 构建神经网络模型
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])

# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# 训练模型并记录训练过程
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))

# 可视化训练过程中的损失和准确率变化
plt.figure(figsize=(12, 4))

plt.subplot(1, 2, 1)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

plt.show()

# 输出测试集的预测结果(前 10 个)和准确率
predictions = model.predict(x_test[:10])
predicted_labels = tf.argmax(predictions, axis=1)
print("前 10 个测试样本的预测结果:", predicted_labels.numpy())

test_loss, test_accuracy = model.evaluate(x_test, y_test)
print("测试集准确率:", test_accuracy)