I am trying to build a neural network with one neuron using the pytorch library. It keeps giving me an error
I am trying to build a neural network with one neuron using the pytorch library. This is my code (the error is at the bottom)

import numpy as np
import random
import matplotlib.pyplot as plt

x_train = np.array([random.randint(1,1000) for x in range(1000)], dtype = np.float32)
y_train = np.array([int(num*3+1) for num in x_train], dtype = np.float32)

x_test = np.array([random.randint(1,1000) for x in range(1000)], dtype = np.float32)
y_test = np.array([int(num*3+1) for num in x_train], dtype = np.float32)

X_train = torch.from_numpy(x_train)
Y_train = torch.from_numpy(y_train)

plt.figure(figsize = (8,8))
plt.scatter(X_train, Y_train)
plt.show()

X_test = torch.from_numpy(x_test)
Y_test = torch.from_numpy(y_test)

input_size = 1
hidden_size = 1
output_size = 1
learning_rate = 0.1


w1 = torch.rand(input_size, hidden_size, requires_grad = True)
b1 = torch.rand(hidden_size, output_size, requires_grad = True)



for i in range(100):
    y_pred = X_train.mm(w1).clamp(min = 0).add(b1)
    loss = (Y_train-y_pred).pow(2).sum()

    loss.backward()

    with torch.no_grad():
        w1-=w1.grad*learning_rate
        b1 -= b1.grad*learning_rate
        w1.grad.zero_()
        b1.grad.zero_()


When I run this code, it gives me a runtime error:

RuntimeError                              Traceback (most recent call last)
&lt;ipython-input-84-5142b17ecfff&gt; in &lt;module&gt;
     32 
     33 for i in range(100):
---&gt; 34     y_pred = X_train.mm(w1).clamp(min = 0).add(b1)
     35     loss = (Y_train-y_pred).pow(2).sum()
     36 

RuntimeError: matrices expected, got 1D, 2D tensors at C:\w\1\s\windows\pytorch\aten\src\TH/generic/THTensorMath.cpp:192


What is wrong with that line of code and how to make it work as planned.

torch expects 2D input, so you need to add a new dimension to your inputs tensors.

X_train = torch.from_numpy(x_train[..., np.newaxis])
X_test = torch.from_numpy(x_test[..., np.newaxis])


As someone commented above, you can also use torch.unsqueeze:

for i in range(100):
    y_pred = torch.unsqueeze(X_train, 1).mm(w1).clamp(min = 0).add(b1)
    loss = (Y_train-y_pred).pow(2).sum()


Both do the same. The former applies it to the numpy arrays, and the latter does it on the torch tensors. Both will result in this shape, which is the correct format for torch:

Out[13]: torch.Size([1000, 1])

