在尝试写一个简单的神经网络训练代码,出现了这个报错信息。孩子被困住好几天了,有没有好心的大佬帮帮忙,在此先感谢了555
代码如下:
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
file_path = 'test_file\\excel.xlsx'
train_day=7
pred_day=3
# train_num = train_day*24*60
# pre_num = pre_day*24*60
# 使用pandas的read_excel函数读取Excel文件
df = pd.read_excel(file_path,sheet_name='Sheet2')
x = df.iloc[:, 1].values
#x = x.reshape(-1, 1)
flow_data = torch.tensor(x, dtype=torch.float32)
print(len(flow_data))
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
# 第一层:输入层到第一个隐藏层
self.layer1 = nn.Linear(train_day, 10)
# 第二层:第一个隐藏层到第二个隐藏层
self.layer2 = nn.Linear(10, 5)
# 第三层:第二个隐藏层到输出层
self.output_layer = nn.Linear(5, pred_day)
# 激活函数
self.relu = nn.ReLU()
def forward(self, x):
# 前向传播
x = self.layer1(x)
x = self.relu(x)
x = self.layer2(x)
x = self.relu(x)
y_pred = self.output_layer(x)
return y_pred
# 创建模型实例
flow_pre_model = SimpleNN()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(flow_pre_model.parameters())
# 初始化存储预测结果的列表
predictions = []
x_trains = []
y_trains = []
for i in range(0, len(flow_data) - pred_day, train_day): # 每次迭代移动7个索引
a = len(flow_data) - pred_day
# 获取当前训练集和目标集
x_train = torch.tensor(flow_data[i:i+train_day]).float()
#y_train = torch.tensor(flow_data[i+train_day:i+train_day+pred_day]).float()
y_train = torch.tensor(flow_data[i + train_day:i + train_day + pred_day]).float()
#x_trains.append(x_train)
#y_trains.append(y_train)
# 训练模型
for _ in range(100): # 假设我们训练100个迭代
optimizer.zero_grad()
output = flow_pre_model(x_train)
loss = criterion(output, y_train)
loss.backward()
optimizer.step()
predictions.append(output.data.numpy())
print(predictions)
报错信息:
C:\Users\hhl\.conda\envs\hhlpytorch\python.exe F:\Nonnetta\05code\flow_pre_hhl\flow_pre_hhl\data_loader.py
100
F:\Nonnetta\05code\flow_pre_hhl\flow_pre_hhl\data_loader.py:59: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
x_train = torch.tensor(flow_data[i:i+train_day]).float()
F:\Nonnetta\05code\flow_pre_hhl\flow_pre_hhl\data_loader.py:61: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
y_train = torch.tensor(flow_data[i + train_day:i + train_day + pred_day]).float()
C:\Users\Raye\.conda\envs\hhlpytorch\Lib\site-packages\torch\nn\modules\loss.py:535: UserWarning: Using a target size (torch.Size([2])) that is different to the input size (torch.Size([3])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
return F.mse_loss(input, target, reduction=self.reduction)
Traceback (most recent call last):
File "F:\Nonnetta\05code\flow_pre_hhl\flow_pre_hhl\data_loader.py", line 72, in <module>
loss = criterion(output, y_train)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hhl\.conda\envs\hhlpytorch\Lib\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hhl\.conda\envs\hhlpytorch\Lib\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hhl\.conda\envs\hhlpytorch\Lib\site-packages\torch\nn\modules\loss.py", line 535, in forward
return F.mse_loss(input, target, reduction=self.reduction)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hhl\.conda\envs\hhlpytorch\Lib\site-packages\torch\nn\functional.py", line 3338, in mse_loss
expanded_input, expanded_target = torch.broadcast_tensors(input, target)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hhl\.conda\envs\hhlpytorch\Lib\site-packages\torch\functional.py", line 76, in broadcast_tensors
return _VF.broadcast_tensors(tensors) # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 0
进程已结束,退出代码为 1