使用pytorch训练数据时出现尺寸不匹配

我对pytorch非常新手,仅尝试使用自己的数据集进行简单的线性回归模型。我只使用数字值作为输入。

我导入的CSV文件

我已经从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))

我已经创建了一个LinearRegressionModel

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 = 500for epoch in range(EPOCHS):    pred_y = model(X_train) # 这里出现运行时错误    loss = criterion(pred_y, y_train)    optimizer.zero_grad() # 清零梯度以正确更新参数    loss.backward() # 反向传播    optimizer.step() # 更新权重    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() # 清零梯度以正确更新参数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中的线性层有参数Wb。如果你将in_features设置为8,out_features设置为1,那么W矩阵的形状将是1 x 8b向量的长度将是1。

由于你的训练数据形状是3540 x 8,你可以执行以下操作。

linear_out = X_train W_T + b

希望这能解答你的疑惑。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注