一、神经元模型
神经网络是由具有适应性的简单单元组成的广泛并行互连的网络,它的组织能够模拟生物神经系统对真实世界体所作出的交互反应。
如果某经元的电位超过了 个"阔值" (激活函数)那么它就会被激活兴奋起来,向其他神经元发送化学物质.
神经元的机理:
带权重的连接(connection) 进行传 ,神经 接收到的总输入值将与神经元的阀值进行比较,然后通过"激活函数" (activation function 处理以产生神经元的输出
二、感知机和多层网络(对比学习)
前置知识
误分类样本:
超平面:
感知机(对比(感知机与逻辑回归))
1. 基本原理
感知机
- 线性分类器:感知机是一种线性分类器,通过一个线性决策边界将数据分为两类。
- 激活函数:感知机使用的是阶跃函数(Step Function),输出要么是1(正类),要么是-1或0(负类)。
- 损失函数:感知机没有显式的损失函数,而是通过误分类样本的梯度下降来更新权重。
逻辑回归
- 概率模型:逻辑回归是一种概率模型,不仅给出分类结果,还给出每个类别的概率。
- 激活函数:逻辑回归使用的是Sigmoid函数(也称为Logistic函数),输出是一个介于0和1之间的概率值。
- 损失函数:逻辑回归使用对数损失函数(Log Loss),通过最大化似然估计来优化模型参数。
2. 输出形式
感知机
- 输出是一个二进制值(1或-1/0),直接表示类别。
逻辑回归
- 输出是一个概率值,表示样本属于正类的概率。通常设定一个阈值(例如0.5),将概率值转换为类别。
3. 学习过程
感知机
- 更新规则:感知机通过误分类样本的梯度下降来更新权重。如果预测错误,则更新权重和偏置项。
逻辑回归
- 梯度下降:逻辑回归通过梯度下降法最小化对数损失函数来更新权重。
4.适用场景
感知机
- 适用于线性可分问题,且对噪声较为敏感。
- 适用于简单的二分类任务,尤其是在数据量较小的情况下。
逻辑回归
- 适用于线性可分和部分非线性可分问题。
- 适用于需要概率输出的场景,例如风险评估、医疗诊断等。
- 适用于大规模数据集,因为其优化过程较为稳定。
5. 扩展性
感知机
- 感知机只能处理二分类问题,对于多分类问题需要扩展为多层感知机或多分类器组合。
逻辑回归
- 逻辑回归可以通过“一对多”(One-vs-Rest, OvR)或多分类逻辑回归(Multinomial Logistic Regression)扩展到多分类问题。
6. 模型解释性
感知机
- 感知机的模型解释性较好,权重可以直接反映特征的重要性。
逻辑回归
- 逻辑回归同样具有较好的解释性,权重和系数可以直接解释为特征对目标变量的影响程度。
多层网络(使用PyTorch框架)
多层网络由多个层次组成,包括输入层、一个或多个隐藏层和输出层。
import torch
import torch.nn as nn
import torch.optim as optim
# 定义多层网络模型
class MLP(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
# 数据准备
input_size = 10
hidden_size = 5
output_size = 2
batch_size = 32
# 创建随机输入和标签
X = torch.randn(batch_size, input_size)
y = torch.randint(0, output_size, (batch_size,))
# 实例化模型
model = MLP(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 100
for epoch in range(num_epochs):
# 前向传播
outputs = model(X)
loss = criterion(outputs, y)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f'Epoch [{
epoch+1}/{
num_epochs}], Loss: {
loss.item():.4f}')
# 测试模型
with torch.no_grad():
test_output = model(X)
_, predicted = torch.max(test_output, 1)
accuracy = (predicted == y).sum().item() / y.size(0)
print(f'Test Accuracy: {
accuracy:.4f}')
三、误差逆传播算法(对比(标准BP与累计BP))
1.对比
- 更新频率:
- 标准BP:每次处理一个样例后更新。
- 累计BP:处理完一个批量或整个训练集后更新。
- 稳定性:
- 标准BP:更新频繁,容易出现“抵消”现象,训练过程可能不稳定。
- 累计BP:更新基于多个样例的平均梯度,更加稳定。
- 适用场景:
- 标准BP:适合小数据集或需要实时更新的场景。
- 累计BP:适合大规模数据集,尤其是需要稳定性和高质量解的场景。
- 收敛速度:
- 标准BP:在训练初期收敛速度快。
- 累计BP:在训练后期通常能获得更好的解,但初期收敛较慢。
2.类似性
- 标准BP与随机梯度下降(SGD):标准BP算法类似于随机梯度下降(SGD),因为都是每次处理一个样例后更新参数。
- 累计BP与批量梯度下降:累计BP算法类似于批量梯度下降,因为都是在处理完所有样例后更新参数。
3.实践中的选择
在实际应用中,可以根据具体需求选择合适的算法:
- 如果数据集较小或需要快速响应,可以选择标准BP算法。
- 如果数据集较大或需要更稳定的训练过程,可以选择累计BP算法。
四、全局最小与局部最小
1.概念
范围:
全局最小值是在整个定义域内最优的解。
局部最小值是在某个局部区域内最优的解
2.方法(感兴趣可以深度了解)
1)随机重启:
在优化过程中,一旦陷入局部极小值,可以重新开始搜索过程,从一个新的随机初始点开始。这种方法简单有效,但可能会增加计算成本。
2)模拟退火:
模拟退火算法通过引入一个温度参数,允许算法以一定的概率接受较差的解。随着温度逐渐降低,算法逐渐收敛到全局最优解。这种方法有助于避免陷入局部极小值。
import numpy as np
def simulated_annealing(objective_func, initial_solution, initial_temp, cooling_rate, max_iterations):
current_solution = initial_solution
current_energy = objective_func(current_solution)
best_solution = current_solution
best_energy = current_energy
temperature = initial_temp
for iteration in range(max_iterations):
# 生成新解
new_solution = current_solution + np.random.uniform(-1, 1) * 0.1
new_energy = objective_func(new_solution)
# 计算能量变化
delta_energy = new_energy - current_energy
# 决定是否接受新解
if delta_energy < 0 or np.random.rand() < np.exp(-delta_energy / temperature):
current_solution = new_solution
current_energy = new_energy
# 更新最佳解
if new_energy < best_energy:
best_solution = new_solution
best_energy = new_energy
# 降温
temperature *= cooling_rate
return best_solution, best_energy
# 示例目标函数
def objective_func(x):
return x**2 + 10 * np.sin(x)
# 参数设置
initial_solution = 10
initial_temp = 100
cooling_rate = 0.95
max_iterations = 1000
# 运行模拟退火
best_solution, best_energy = simulated_annealing(objective_func, initial_solution, initial_temp, cooling_rate, max_iterations)
print(f"Best solution: {
best_solution}, Best energy: {
best_energy}")
3)遗传算法:
遗传算法通过模拟自然选择和遗传机制,维护一个解的群体,并通过选择、交叉和变异操作逐步进化。这种方法可以探索更大的解空间,有助于找到全局最优解。
4)粒子群优化 (PSO):
粒子群优化通过模拟鸟群或鱼群的行为,每个粒子在解空间中移动,并根据自身和群体的最佳位置调整速度。这种方法可以有效地探索解空间,避免陷入局部极小值
import numpy as np
def pso(objective_func, n_particles, n_iterations, w, c1, c2, bounds):
n_dimensions = len(bounds)
particles = np.random.uniform(bounds[:, 0], bounds[:, 1], (n_particles, n_dimensions))
velocities = np.zeros_like(particles)
personal_best_positions = particles.copy()
personal_best_scores = np.array([objective_func(p) for p in particles])
global_best_position = particles[np.argmin(personal_best_scores)]
global_best_score = np.min(personal_best_scores)
for _ in range(n_iterations):
for i in range(n_particles):
# 更新速度
r1, r2 = np.random.rand(2)
velocities[i] = (w * velocities[i] +
c1 * r1 * (personal_best_positions[i] - particles[i]) +
c2 * r2 * (global_best_position - particles[i]))
# 更新位置
particles[i] += velocities[i]
# 评估新位置
score = objective_func(particles[i])
# 更新个人最佳
if score < personal_best_scores[i]:
personal_best_scores[i] = score
personal_best_positions[i] = particles[i]
# 更新全局最佳
if score < global_best_score:
global_best_score = score
global_best_position = particles[i]
return global_best_position, global_best_score
# 示例目标函数
def objective_func(x):
return x[0]**2 + x[1]**2
# 参数设置
n_particles = 30
n_iterations = 1000
w = 0.7
c1 = 1.5
c2 = 1.5
bounds = np.array([[-10, 10], [</