有一个DataFrame名叫Data,它有列time_id、veh_n、v_avg,其中 time_id 表示的是时间序列(整数),veh_n 是车辆数(整数),v_avg 是车辆平均速度(float)。我希望你能帮我写一个 LSTM 的代码,输入是 time_id、veh_n、v_avg,预测得到的结果是veh_n,v_avg,预测步长为2。
时间: 2024-02-29 21:54:50 浏览: 66
好的,我可以帮你写一个基于 PyTorch 的 LSTM 模型来进行预测。以下是代码示例:
```python
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
# 加载数据
data = pd.read_csv('data.csv')
n_features = 3 # 特征个数
# 将数据划分为训练集和测试集
test_size = int(len(data) * 0.2) # 测试集占比为20%
train_data = data[:-test_size]
test_data = data[-test_size:]
# 将数据转换成LSTM模型的输入格式
def create_dataset(X, y, time_steps=1):
Xs, ys = [], []
for i in range(len(X) - time_steps):
Xs.append(X.iloc[i:(i+time_steps)].values)
ys.append(y.iloc[i+time_steps])
return np.array(Xs), np.array(ys)
time_steps = 2 # 预测步长为2,即输入2个时间序列预测未来2个时间序列的车辆数和平均速度
X_train, y_train = create_dataset(train_data[['time_id', 'veh_n', 'v_avg']], train_data[['veh_n', 'v_avg']], time_steps)
X_test, y_test = create_dataset(test_data[['time_id', 'veh_n', 'v_avg']], test_data[['veh_n', 'v_avg']], time_steps)
# 定义LSTM模型
class LSTM(nn.Module):
def __init__(self, n_features, hidden_size, time_steps):
super(LSTM, self).__init__()
self.n_features = n_features
self.hidden_size = hidden_size
self.time_steps = time_steps
self.lstm = nn.LSTM(n_features, hidden_size, batch_first=True)
self.fc1 = nn.Linear(hidden_size * time_steps, 32)
self.fc2 = nn.Linear(32, 2)
def forward(self, x):
h0 = torch.zeros(1, x.size(0), self.hidden_size)
c0 = torch.zeros(1, x.size(0), self.hidden_size)
out, _ = self.lstm(x, (h0, c0))
out = out.reshape(out.size(0), -1)
out = self.fc1(out)
out = torch.relu(out)
out = self.fc2(out)
return out
# 训练LSTM模型
hidden_size = 32 # 隐藏层神经元数目
learning_rate = 0.001
n_epochs = 100
model = LSTM(n_features, hidden_size, time_steps)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(n_epochs):
inputs = torch.autograd.Variable(torch.Tensor(X_train))
targets = torch.autograd.Variable(torch.Tensor(y_train))
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print(f'Epoch {epoch+1}/{n_epochs}, Loss: {loss.item():.4f}')
# 测试LSTM模型
model.eval()
X_test = torch.Tensor(X_test)
y_pred = model(X_test)
# 将预测结果转换为DataFrame格式
y_pred = y_pred.detach().numpy()
y_test = y_test.reshape(-1, 2)
y_pred = pd.DataFrame(y_pred, columns=['veh_n', 'v_avg'])
y_test = pd.DataFrame(y_test, columns=['veh_n', 'v_avg'])
# 输出预测结果
print("Actual:")
print(y_test)
print("Predicted:")
print(y_pred)
```
注意,以上代码只是一个示例,实际应用中可能需要对模型进行更多的调整和优化,以达到更好的预测效果。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)