python - 如何解决输入和批量大小的 RunTimeError?

**

我的输入(特征)包含 1 列和 12454 行,而我的目标(标签)包含 2 列和 12454 行,这是我的完整代码:

**

import pandas as pd
import numpy as np
from numpy import genfromtxt
import torch.nn as nn
import torch
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
import tensorflow as tf
import matplotlib as plt

inputs = genfromtxt('C:/Users/HP2015/Desktop/prog/data/elec_data_inputs.csv', delimiter=',')

target = genfromtxt('C:/Users/HP2015/Desktop/prog/data/elec_data_target.csv', delimiter=',')

inputs = torch.from_numpy(inputs)

target = torch.from_numpy(target)

train_ds = TensorDataset(inputs.float(), target)

batch_size = 100
train_dl = DataLoader(train_ds, batch_size, shuffle=True)

model = nn.Linear(1, 2)

preds = model(inputs.float())
preds

当我尝试实现此代码时,我收到此错误:

RuntimeError Traceback (most recent call last)
    ~\AppData\Local\Temp/ipykernel_16984/1006819693.py in
    ----> 1 preds = model(inputs.float())
    2 preds

~\anaconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, *kwargs) 1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1109 or _global_forward_hooks or _global_forward_pre_hooks): -> 1110 return forward_call(input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []

~\anaconda3\lib\site-packages\torch\nn\modules\linear.py in forward(self, input)
101
102 def forward(self, input: Tensor) -> Tensor:
--> 103 return F.linear(input, self.weight, self.bias)
104
105 def extra_repr(self) -> str:

RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x12454 and 1x2)

如何设置批量大小和模型以满足要求?

回答1

查询是基于矩阵乘法过程中因维度不匹配而导致的错误。

因此,在将输入放入模型之前尝试对其进行整形。

import pandas as pd
import numpy as np
from numpy import genfromtxt
import torch.nn as nn
import torch
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
import tensorflow as tf
import matplotlib as plt

inputs = genfromtxt('C:/Users/HP2015/Desktop/prog/data/elec_data_inputs.csv', delimiter=',')

target = genfromtxt('C:/Users/HP2015/Desktop/prog/data/elec_data_target.csv', delimiter=',')

inputs = torch.from_numpy(inputs)
inputs=torch.reshape(inputs,(12454,1))
target = torch.from_numpy(target)
target=torch.reshape(target,(12454,2))

train_ds = TensorDataset(inputs.float(), target)

batch_size = 100
train_dl = DataLoader(train_ds, batch_size, shuffle=True)

model = nn.Linear(1, 2)

preds = model(inputs.float())
preds

那么到底发生了什么,您的输入张量应该是带有输入数据的单列张量,但它是带有所有输入点的单行张量,因此当您在 Linear() 上运行它时,因为尺寸不t 匹配,它会引发错误。

因此可以通过添加这两行代码来改变它,我们已经重新调整了输入和目标

inputs = torch.from_numpy(inputs)
inputs=torch.reshape(inputs,(12454,1))
target = torch.from_numpy(target)
target=torch.reshape(target,(12454,2))

相似文章

最新文章