数据为一个文件夹数据,文件夹里面有100excle数据 excle里面有行车的速度和油耗数据,基于pytroch写一个LSTM预测油耗代码
时间: 2024-02-12 11:04:49 浏览: 59
pytorch搭建CNN+LSTM+Attention网络实现行车速度预测项目代码加数据
好的,以下是基于PyTorch实现的LSTM油耗预测代码:
```python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# 读取数据
data = pd.read_excel('/path/to/data/folder/*.xlsx', sheet_name=None)
df = pd.concat(data.values())
# 数据处理
data = df['油耗'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(-1, 1))
data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
test_size = len(data) - train_size
train_data, test_data = data[:train_size, :], data[train_size:, :]
# 创建数据集
def create_dataset(dataset, look_back=1):
data_X, data_Y = [], []
for i in range(len(dataset) - look_back):
data_X.append(dataset[i:(i + look_back), 0])
data_Y.append(dataset[i + look_back, 0])
return np.array(data_X), np.array(data_Y)
look_back = 10
train_X, train_Y = create_dataset(train_data, look_back=look_back)
test_X, test_Y = create_dataset(test_data, look_back=look_back)
# 转换为PyTorch张量
train_X = torch.from_numpy(train_X).float()
train_Y = torch.from_numpy(train_Y).float()
test_X = torch.from_numpy(test_X).float()
# 定义LSTM模型
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(1, x.size(1), self.hidden_size)
c0 = torch.zeros(1, x.size(1), self.hidden_size)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[-1, :, :])
return out
input_size = 1
hidden_size = 32
output_size = 1
model = LSTM(input_size, hidden_size, output_size)
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 100
for epoch in range(num_epochs):
outputs = model(train_X)
loss = criterion(outputs, train_Y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch + 1) % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch + 1, num_epochs, loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
test_predict = model(test_X)
test_predict = scaler.inverse_transform(test_predict.numpy())
test_Y = scaler.inverse_transform(test_Y.numpy())
rmse = np.sqrt(np.mean((test_predict - test_Y) ** 2))
print('RMSE: {:.2f}'.format(rmse))
```
以上代码将数据文件夹中的所有Excel文件合并,然后进行数据预处理和LSTM模型的训练和测试。请将`/path/to/data/folder/*.xlsx`替换为你的数据文件夹路径。
阅读全文