以下是一个完整的 Python 实现,展示如何使用 BP 神经网络(Backpropagation Neural Network)对时间序列数据进行分类。我们将使用 PyTorch
来实现 BP 神经网络。
1. 数据准备
假设我们有一些时间序列数据,每条时间序列的长度相同,并且已经被标注了类别标签。我们将这些时间序列输入到神经网络中进行分类。
(1) 示例数据
生成一些示例时间序列数据:
import numpy as np
# 随机生成 3 类时间序列数据,每类 100 条,每条长度为 20
np.random.seed(42)
time_series_data = []
labels = []
# 类别 0: 正弦波
for _ in range(100):
time_series_data.append(np.sin(np.linspace(0, 2 * np.pi, 20)) + np.random.normal(0, 0.1, 20))
labels.append(0)
# 类别 1: 锯齿波
for _ in range(100):
time_series_data.append(np.linspace(-1, 1, 20) + np.random.normal(0, 0.1, 20))
labels.append(1)
# 类别 2: 方波
for _ in range(100):
time_series_data.append(np.where(np.linspace(0, 2 * np.pi, 20) % (2 * np.pi) < np.pi, 1, -1) + np.random.normal(0, 0.1, 20))
labels.append(2)
# 转换为 NumPy 数组
time_series_data = np.array(time_series_data)
labels = np.array(labels)
2. 数据预处理
将数据划分为训练集和测试集,并转换为 PyTorch 张量格式。
from sklearn.model_selection import train_test_split
import torch
from torch.utils.data import DataLoader, TensorDataset
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(time_series_data, labels, test_size=0.2, random_state=42)
# 转换为 PyTorch 张量
X_train_tensor = torch.tensor(X_train, dtype=torch.float32).unsqueeze(-1) # 添加通道维度 [样本数, 时间步, 特征数]
y_train_tensor = torch.tensor(y_train, dtype=torch.long)
X_test_tensor = torch.tensor(X_test, dtype=torch.float32).unsqueeze(-1)
y_test_tensor = torch.tensor(y_test, dtype=torch.long)
# 创建数据加载器
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
test_dataset = TensorDataset(X_test_tensor, y_test_tensor)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
3. 定义 BP 神经网络模型
BP 神经网络是一种多层感知器(MLP),由全连接层组成。我们可以将其视为一个简单的前馈神经网络。
import torch.nn as nn
import torch.optim as optim
class BPNeuralNetwork(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(BPNeuralNetwork, 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):
x = x.view(x.size(0), -1) # 展平时间序列数据 [batch_size, input_size]
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
4. 训练模型
定义损失函数和优化器,并训练模型。
# 初始化模型、损失函数和优化器
input_size = X_train_tensor.shape[1] * X_train_tensor.shape[2] # 输入特征数(时间步 × 特征数)
hidden_size = 64 # 隐藏层大小
output_size = len(np.unique(labels)) # 输出类别数
model = BPNeuralNetwork(input_size, hidden_size, output_size)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
epochs = 20
for epoch in range(epochs):
model.train()
total_loss = 0
correct = 0
total = 0
for batch_X, batch_y in train_loader:
optimizer.zero_grad()
outputs = model(batch_X)
loss = criterion(outputs, batch_y)
loss.backward()
optimizer.step()
total_loss += loss.item()
_, predicted = torch.max(outputs, 1)
total += batch_y.size(0)
correct += (predicted == batch_y).sum().item()
print(f"Epoch [{epoch+1}/{epochs}], Loss: {total_loss:.4f}, Accuracy: {correct / total:.4f}")
5. 测试模型
在测试集上评估模型性能。
model.eval()
correct = 0
total = 0
with torch.no_grad():
for batch_X, batch_y in test_loader:
outputs = model(batch_X)
_, predicted = torch.max(outputs, 1)
total += batch_y.size(0)
correct += (predicted == batch_y).sum().item()
print(f"Test Accuracy: {correct / total:.4f}")
6. 结果示例
运行上述代码后,您将看到类似以下的输出:
Epoch [1/20], Loss: 1.0987, Accuracy: 0.4875
Epoch [2/20], Loss: 0.8765, Accuracy: 0.6750
...
Epoch [20/20], Loss: 0.1234, Accuracy: 0.9750
Test Accuracy: 0.9500
7. 可选改进
(1) 增加隐藏层
可以增加更多的隐藏层以提高模型的表达能力:
self.fc3 = nn.Linear(hidden_size, hidden_size)
x = self.fc3(x)
x = self.relu(x)
(2) 使用正则化
为了防止过拟合,可以添加 Dropout 或 L2 正则化:
self.dropout = nn.Dropout(0.5)
x = self.dropout(x)
(3) 调整学习率
如果模型收敛较慢,可以调整学习率或使用学习率调度器:
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
scheduler.step()
8. 总结
- 上述代码展示了如何使用 BP 神经网络对时间序列数据进行分类。
- 我们通过展平时间序列数据并使用全连接层实现了 BP 神经网络。
- 如果您的数据规模较大或需要更高的性能,可以考虑使用更复杂的模型(如 LSTM 或 Transformer)。