简体   繁体   English

如何解决 Python (Pytorch) 中的大小不匹配错误

[英]How to solve size mismatch error in Python (Pytorch)

I am currently working on multivariate linear regression using PyTorch and I am getting the following error, I did search a lot about this error and the only thing I got to know is that there is a size mismatch between data and labels.我目前正在使用 PyTorch 进行多元线性回归,我收到以下错误,我确实搜索了很多关于这个错误的信息,我唯一知道的是数据和标签之间存在大小不匹配。 But how to solve this error.但是如何解决这个错误。 Please help me or show me the right way to solve this problem.请帮助我或告诉我解决此问题的正确方法。

size mismatch, m1: [824 x 1], m2: [8 x 8]尺寸不匹配,m1:[824 x 1],m2:[8 x 8]

import torch
import torch.nn as nn
import numpy as np


Xtr = np.loadtxt("TrainData.csv")
Ytr = np.loadtxt("TrainLabels.csv")


X_train = torch.FloatTensor(Xtr)
Y_train = torch.FloatTensor(Ytr)

#### MODEL ARCHITECTURE #### 

class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = torch.nn.Linear(8,8)
        self.lin2 = torch.nn.Linear(8,1)

    def forward(self, x):
        x = self.lin2(x)
        y_pred = self.linear(x)
        return y_pred

model = Model()

loss_func = nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
#print(len(list(model.parameters())))
def count_params(model): 
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

### TRAINING 
for epoch in range(2):
    y_pred = model(X_train)

    loss = loss_func(y_pred, Y_train)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    count = count_params(model)
    print(count)

test_exp = torch.FloatTensor([[6.0]])

It looks like the order of operations in your forward pass is incorrect.看起来您的前向传递中的操作顺序不正确。 The short answer is swap them as shown below.简短的回答是交换它们,如下所示。 More context on the various shapes below.以下各种形状的更多背景信息。

    def forward(self, x):
        x = self.lin2(x)
        y_pred = self.linear(x)
        return y_pred

Should be:应该:

    def forward(self, x):
        x = self.linear(x)
        y_pred = self.lin2(x)
        return y_pred

Assuming that you have 8 features and some batch size N your input data to the forward pass will have size (N x 8) .假设您有 8 个特征和一些批量大小N ,您前向传递的输入数据将具有大小(N x 8) After you pass it through lin2 it will have shape (N x 1) .将它通过lin2后,它将具有形状(N x 1) The linear node expects an input with shape (N x 8) but it's getting (N x 1) hence the error. linear节点需要一个形状为(N x 8)的输入,但它得到(N x 1)因此出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM