How should I fix the code in order to make the linear regression model using train data properly work?
What I should do is to collect height and weight information from 5 people and use it as train data to learn the linear regression model in Colab.
There is an example code, so I fixed it, but it doesn’t work from the first place.
How should I fix the code in order to make the linear regression model using train data properly work? The code I have fixed so far is the following. The height and weight data below are the values I randomly chose.
import torch
import torch.optim as optim

# Defining data
x_train=torch.Float Tensor([48],[52],[60],[65],[73])
y_train=torch.Float Tensor([158],[162],[170],[175],[183])

# Hypothesis initiaization
W=torch.zeros(1,requires_grad=True)
b=torch.zeros(1,requires_grad=True)

# Defining Optimizer 
optimizer=torch.optim.SGD([W,b],Ir=0.01)

nb_epochs=1000
for epoch in range(nb_epochs+1):
  # Calculating H(x)
  hypothesis=x_train*W+b
  # Calculating cost
  cost=torch.mean((hypothesis-y_train)**2)
  # Learning with Optimizer
  optimizer.zero_grad()
  cost.backward()
  optimizer.step()


  # Log output every 100 times
  if epoch % 100 ==0:
    print('Epoch{:4d}/{}W:{:.3f},b:{:.3f}Coast:{:.6f}'.format(
        epoch,nb_epochs,W.item(),b.item(),cost.item()
    ))


There are several minor mistakes in the code snippet, and actually you can read these from error messages

torch.Tensor(), and &quot;torch.Tensor is an alias for the default tensor type (torch.FloatTensor)&quot;
the data you feed in should be a Python list or sequence
Ir-&gt;lr (not ir, but Lr)
try lower learning rate (lr) for the nan problem
training with enough epochs

Given the least modification, it works
import torch
import torch.optim as optim

# Defining data
x_train=torch.Tensor([[48],[52],[60],[65],[73]])
y_train=torch.Tensor([[158],[162],[170],[175],[183]])

# Hypothesis initiaization
W=torch.zeros(1,requires_grad=True)
b=torch.zeros(1,requires_grad=True)

# Defining Optimizer 
optimizer=torch.optim.SGD([W,b],lr=0.0001)

nb_epochs=1000000
for epoch in range(nb_epochs+1):
  # Calculating H(x)
  hypothesis=x_train*W+b
  # Calculating cost
  cost=torch.mean((hypothesis-y_train)**2)
  # Learning with Optimizer
  optimizer.zero_grad()
  cost.backward()
  optimizer.step()


  # Log output every 200 times
  if epoch % 200 ==0:
    print('Epoch{:4d}/{}W:{:.3f},b:{:.3f}Coast:{:.6f}'.format(
        epoch,nb_epochs,W.item(),b.item(),cost.item()
    ))

reference:
https://pytorch.org/docs/stable/tensors.html
