How to change the number of inputs with Linear Regression

here is the number of parameters that I want to change

# input_size = 1
input_size = 2  # 3, 4, 5,...
output_size = 1
num_epochs = 60
learning_rate = 0.001

This is training set

x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], 
                    [9.779], [6.182], [7.59], [2.167], [7.042], 
                    [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)

y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573], 
                    [3.366], [2.596], [2.53], [1.221], [2.827], 
                    [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)

This is a training model of linear


for epoch in range(num_epochs):
    # Convert numpy arrays to torch tensors
    inputs = torch.from_numpy(x_train)
    targets = torch.from_numpy(y_train)

    # Forward pass
    outputs = model(inputs)
    loss = criterion(outputs, targets)
    
    # Backward and optimize
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if (epoch+1) % 5 == 0:
        print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))

This is the error I got:


RuntimeError Traceback (most recent call last)
in ()
6
7 # Forward pass
----> 8 outputs = model(inputs)
9 loss = criterion(outputs, targets)
10

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in call(self, *input, **kwargs)
489 result = self._slow_forward(*input, **kwargs)
490 else:
–> 491 result = self.forward(*input, **kwargs)
492 for hook in self._forward_hooks.values():
493 hook_result = hook(self, input, result)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/linear.py in forward(self, input)
53
54 def forward(self, input):
—> 55 return F.linear(input, self.weight, self.bias)
56
57 def extra_repr(self):

/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
990 if input.dim() == 2 and bias is not None:
991 # fused op is marginally faster
–> 992 return torch.addmm(bias, input, weight.t())
993
994 output = input.matmul(weight.t())

RuntimeError: size mismatch, m1: [15 x 1], m2: [2 x 1] at /pytorch/aten/src/TH/generic/THTensorMath.c:2033

This error is generalized when I increased the number of inputs.
What I want to do here is to make a general case to adapt module linear without any errors or how change make training set without error?

As far as I understand your question, you would like to create your model based on different input data.
You could get the number of features from your input and create the model afterwards:

in_features = x_train.shape[1]

model = nn.Sequential(
    nn.Linear(in_features, 2)
)

x = torch.from_numpy(x_train)
output = model(x)
1 Like