I'm asking you a question about a tensor dimension error while using python's pytorch.

Asked 2 years ago, Updated 2 years ago, 22 views

I just learned python and am practicing pytorch.

We are testing simple code for linear regression on GPU using pytorch.

The error "both arguments to normal need to beat least 1D, but they are 0D and 2D"

worry about no further progress after facing Post to the question.

Thank you for answering my questions through countless experiences

I sincerely ask you to share your valuable experience with me.

Thank you.

import torch

import torch.nn as nn

import torch.nn.functional as F

import torch.optim as optim

learning_rate=0.001

device=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

class Neural(nn.Module):
    def __init__(self):
        super(Neural, self).__init__()
        self.fc1=nn.Linear(1,10)
        self.fc2=nn.Linear(10,1)

        self.optimizer=optim.Adam(self.parameters(),lr=learning_rate)

        self.device=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

        self.to(self.device)

    def forward(self,x):
        x=F.relu(self.fc1(x))
        x=self.fc2(x)
        return x

    def train_net(self,X,Y):
        y_pred=self.forward(X)

        loss=MSE((y_pred-Y)**2)

        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

model=Neural()

X=torch.tensor([1,2,3,4,5,6], dtype=torch.float).to(device)
Y=torch.tensor([3,6,9,12,15,18], dtype=torch.float).to(device)
print(X[1])
model.forward(X[1])

python

2022-09-20 16:33

1 Answers

The neural net operation is, after all, matrix multiplexing, which cannot be performed if each dimension is not correct.

It seems to be a problem that X[1] was delivered when forwarding.

X=torch.tensor([[1,2,3,4,5,6]], dtype=torch.float).to(device)

Declare X like this and deliver X instead of X[1]

In addition, in phytorch, the forward function also acts as model(X) instead of model.forward(X).


2022-09-20 16:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.