machine-learning - 尝试训练数据时使用 pytorch 的大小不匹配
问题描述
我对 pytorch 真的很陌生,只是想用我自己的数据集来做一个简单的线性回归模型。我也只使用数字值作为输入。
我已从 CSV 导入数据
dataset = pd.read_csv('mlb_games_overview.csv')
我将数据分成四部分 X_train, X_test, y_train, y_test
X = dataset.drop(['date', 'team', 'runs', 'win'], 1)
y = dataset['win']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=True)
我已将数据转换为 pytorch 张量
X_train = torch.from_numpy(np.array(X_train))
X_test = torch.from_numpy(np.array(X_test))
y_train = torch.from_numpy(np.array(y_train))
y_test = torch.from_numpy(np.array(y_test))
我创建了一个线性回归模型
class LinearRegressionModel(torch.nn.Module):
def __init__(self):
super(LinearRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
我已经初始化了优化器和损失函数
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
现在,当我开始训练数据时,我得到运行时错误不匹配
EPOCHS = 500
for epoch in range(EPOCHS):
pred_y = model(X_train) # RUNTIME ERROR HERE
loss = criterion(pred_y, y_train)
optimizer.zero_grad() # zero out gradients to update parameters correctly
loss.backward() # backpropagation
optimizer.step() # update weights
print('epoch {}, loss {}'. format(epoch, loss.data[0]))
错误日志:
RuntimeError Traceback (most recent call last)
<ipython-input-40-c0474231d515> in <module>
1 EPOCHS = 500
2 for epoch in range(EPOCHS):
----> 3 pred_y = model(X_train)
4 loss = criterion(pred_y, y_train)
5 optimizer.zero_grad() # zero out gradients to update parameters correctly
RuntimeError: size mismatch, m1: [3540 x 8], m2: [1 x 1] at
C:\w\1\s\windows\pytorch\aten\src\TH/generic/THTensorMath.cpp:752
解决方案
在您的线性回归模型中,您有:
self.linear = torch.nn.Linear(1, 1)
但是您的训练数据 ( X_train
) 形状3540 x 8
意味着您有 8 个特征来代表每个输入示例。因此,您应该如下定义线性层。
self.linear = torch.nn.Linear(8, 1)
PyTorch 中的线性层W
具有参数,并且b
. 如果将 设置in_features
为 8 和out_features
1,则W
矩阵的形状将为1 x 8
,向量的长度b
将为 1。
由于您的训练数据形状为3540 x 8
,您可以执行以下操作。
linear_out = X_train W_T + b
我希望它能澄清你的困惑。
推荐阅读
- string - 如何在 SQLite3 命令行中将字符串拆分为新列?
- java - Android 中新的 PDF 页面创建产生的页面比预期的要多
- java - 如何解决 Android 运行时预期“无法获取文件列表 xyz.geshkii.weather”?
- r - ggplot中的百分比而不是计数
- python - 使用 Codeforces API 通过 discord bot (discord.py) 获取有关用户在 CF 问题上的所有 AC 的信息 - python 中的 json 文件处理错误
- alibaba-cloud - 阿里云是否支持文本转录?
- c++ - 使用 libclang 解析 windows С++ 项目文件(带有 VC 代码库)
- xml - 如何将线性布局分成四个相等的部分?
- python - 在 dataframe.time 上运行自相关,包括小时和分钟
- java - 在多模块 java 项目中使用 lib commons-dbcp2(BasicDataSource 类)时出错