将上述代码进行提取整合
时间: 2024-10-29 12:12:16 浏览: 4
为了简化代码并将其整合在一起,你可以创建一个名为`main.py`的文件,按照以下结构编写:
```python
# 导入所需的库
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from sklearn.model_selection import train_test_split
# 定义二进制标签函数
def binary_label(temp):
return format(int(temp), '08b')
# 加载数据
df = pd.read_excel('weather_data.xlsx')
# 数据预处理
df['binary_label'] = df['temperature'].apply(binary_label)
features = df.iloc[:, :-1]
labels = df['binary_label']
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
# 数据张量化
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
X_train = torch.tensor(X_train.values, dtype=torch.float32).to(device)
y_train = torch.tensor(y_train.values, dtype=torch.long).to(device)
X_test = torch.tensor(X_test.values, dtype=torch.float32).to(device)
y_test = torch.tensor(y_test.values, dtype=torch.long).to(device)
# 神经网络模型
input_dim = features.shape[1]
hidden_dim = 64
output_dim = 8
model = BinaryTemperaturePredictor(input_dim, hidden_dim, output_dim).to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练循环
num_epochs = 100
for epoch in range(num_epochs):
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
# 打印训练进度
if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.item()}")
# 预测并验证
model.eval() # 设置为评估模式
with torch.no_grad():
predictions = model(X_test)
predicted_temps = [int(''.join(str(p) for p in pred.argmax(dim=1)), 2) for pred in predictions]
accuracy = sum(predicted_temps == y_test.tolist()) / len(y_test)
print(f"Final Accuracy: {accuracy}")
# 结果保存
torch.save(model.state_dict(), 'temperature_predictor.pth')
```
在这个版本的代码中,我们已经整合了数据加载、预处理、模型定义、训练、预测以及最终准确性的计算。记得替换`'weather_data.xlsx'`为你实际的数据路径。
阅读全文