PyTorch Linear Regression
Linear regression is one of the most basic machine learning algorithms, used to predict a continuous value. It is a simple and common regression analysis method that aims to predict output by fitting a linear function.
For a simple linear regression problem, the model can be expressed as:

- y is the predicted value (target value).
- (x_1), (x_2), (x_n) are input features.
- (w_1), (w_2), (w_n) are the weights to be learned (model parameters).
- b is the bias term.

In PyTorch, a linear regression model can be implemented by inheriting from nn.Module a class. We will explain in detail how to implement a linear regression model with PyTorch through a simple example.
Data preparation
We first prepare some fake data to train our linear regression model. Here we can generate a simple dataset with a linear relationship, where each sample has two features (x_1), (x_2).
Example
import
torch
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
Random seed to ensure consistent results across runs
torch.
manual_seed
(
42
)
Generate training data
X
=
torch.
randn
(
100
,
2
)
100 samples, each with 2 features
true_w
=
torch.
tensor
(
[
2.0
,
3.0
]
)
Assume true weights
true_b
=
4.0
Bias Term
Y
=
X
@
true_w + true_b + torch.
randn
(
100
)
0.1
Add some noise
Print part of the data
(
X
[
:
5
]
)
(
Y
[
:
5
]
)
The output is as follows:
tensor([[ 1.9269, 1.4873],
[ 0.9007, -2.1055],
[ 0.6784, -1.2345],
[-0.0431, -1.6047],
[-0.7521, 1.6487]])
tensor([12.4460, -0.4663, 1.7666, -0.9357, 7.4781])
This code creates a linear dataset with noise.
- The input X is a 100x2 matrix, with two features per sample.
- The output Y is generated from the true weights and bias, with some random noise added.
- Use
torch.manual_seed(42)Ensures consistent results across runs, making debugging and reproduction easier.
Define the linear regression model
We can define a simple linear regression model by inheriting from nn.Module . In PyTorch, the core of linear regression is the nn.Linear() layer, which automatically handles weight and bias initialization.
Example
import
torch.
nn
as
nn
Define the linear regression model
class
LinearRegressionModel
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
LinearRegressionModel
,
self
)
.
init
(
)
Define a linear layer with 2 input features and 1 output prediction
self
.
linear
=
nn.
Linear
(
2
,
1
)
Input dimension 2, output dimension 1
def
forward
(
self
,
x
)
:
return
self
.
linear
(
x
)
Forward pass, returning the prediction
Create a model instance
model
=
LinearRegressionModel
(
)
Here, nn.Linear(2, 1) represents a linear layer with 2 input features and 1 output.forward method defines how to perform the forward pass through this layer.
Note:
nn.Linearautomatically creates the weight matrix and bias vector, no manual definition needed.
Define the loss function and optimizer
A common loss function for linear regression isMean Squared Error loss (MSELoss), used to measure the difference between predictions and true values. PyTorch provides a ready-made MSELoss function.
We will useSGD (Stochastic Gradient Descent)orAdamoptimizer to minimize the loss function.
Example
Loss function (mean squared error)
criterion
=
nn.
MSELoss
(
)
Optimizer (using SGD or Adam)
optimizer
=
torch.
optim
.
SGD
(
model.
parameters
(
)
,
lr
=
0.01
)
Set learning rate to 0.01
You can also use the Adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
| Component | Description |
|---|---|
MSELoss |
Compute the mean squared error between predictions and true values, with the formula (\frac{1}{n}\sum(y_{pred} - y_{true})^2) |
SGD |
Update parameters using stochastic gradient descent; the learning rate controls the step size |
Adam |
Adaptive learning rate optimizer, usually converges faster |
Train the model
During training, we will perform the following steps:
- Perform a forward pass with input data X to get predictions.
- Compute the loss (the difference between predictions and actual values).
- Compute gradients using backpropagation.
- Update model parameters (weights and bias).
We will train the model for 1000 epochs and print the loss every 100 epochs.
Example
Train the model
num_epochs
=
1000
Train for 1000 epochs
for
epoch
in
range
(
num_epochs
)
:
model.
train
(
)
Set the model to training mode
Forward propagation
predictions
=
model
(
X
)
Model outputs predictions
loss
=
criterion
(
predictions.
squeeze
(
)
,
Y
)
Compute loss (note: predictions need to be squeezed to 1D)
Backpropagation
optimizer.
zero_grad
(
)
Clear previous gradients
loss.
backward
(
)
Compute gradients
optimizer.
step
(
)
Update the model parameters
Print loss
if
(
epoch +
1
)
%
100
==
0
:
(
f
'Epoch [{epoch + 1}/1000], Loss: {loss.item():.4f}'
)
predictions.squeeze(): Squeeze the model output from a 2D tensor to 1D, because the target valuesYis a one-dimensional array.optimizer.zero_grad(): Clear previous gradients before each backpropagation, otherwise gradients accumulate.loss.backward(): Automatically compute gradients for all trainable parameters.optimizer.step(): Update weights and bias based on the computed gradients.
Training mode vs evaluation mode: Calling
model.train()in the training loop is necessary; although this example does not use Dropout or BatchNorm, building this habit is important for complex models.
Evaluate the model
After training, we can evaluate the model by examining its weights and bias. We can also make predictions on new data and compare with actual values.
Example
View the trained weights and bias
(
f
'Predicted weight: {model.linear.weight.data.numpy()}'
)
(
f
'Predicted bias: {model.linear.bias.data.numpy()}'
)
Make predictions on new data
with
torch.
no_grad
(
)
:
No need to compute gradients during evaluation
predictions
=
model
(
X
)
Visualize predictions vs actual values
plt.
scatter
(
X
[
:
,
0
]
,
Y
,
color
=
'blue'
,
label
=
'True values'
)
plt.
scatter
(
X
[
:
,
0
]
,
predictions
,
color
=
'red'
,
label
=
'Predictions'
)
plt.
legend
(
)
plt.
show
(
)
model.linear.weight.dataandmodel.linear.bias.data: These attributes store the model's weights and bias.torch.no_grad(): In evaluation mode, gradients are not computed, saving memory and speeding up inference.
Complete example code
Below is the complete code for all the above steps, integrated and ready to run:
Example
import
torch
import
torch.
nn
as
nn
import
matplotlib.
pyplot
as
plt
1. Prepare data
torch.
manual_seed
(
42
)
X
=
torch.
randn
(
100
,
2
)
100 samples, 2 features
true_w
=
torch.
tensor
(
[
2.0
,
3.0
]
)
true_b
=
4.0
Y
=
X
@
true_w + true_b + torch.
randn
(
100
)
0.1
2. Define the model
class
LinearRegressionModel
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
)
.
init
(
)
self
.
linear
=
nn.
Linear
(
2
,
1
)
def
forward
(
self
,
x
)
:
return
self
.
linear
(
x
)
model
=
LinearRegressionModel
(
)
3. Define the loss function and optimizer
criterion
=
nn.
MSELoss
(
)
optimizer
=
torch.
optim
.
SGD
(
model.
parameters
(
)
,
lr
=
0.01
)
4. Train the model
num_epochs
=
1000
for
epoch
in
range
(
num_epochs
)
:
model.
train
(
)
predictions
=
model
(
X
)
loss
=
criterion
(
predictions.
squeeze
(
)
,
Y
)
optimizer.
zero_grad
(
)
loss.
backward
(
)
optimizer.
step
(
)
if
(
epoch +
1
)
%
100
==
0
:
(
f
'Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}'
)
5. Evaluate the model
(
f
'\nWeights after training: {model.linear.weight.data.numpy()}'
)
(
f
'Bias after training: {model.linear.bias.data.numpy()}'
)
(
f
'True weights: {true_w.numpy()}'
)
(
f
'True bias: {true_b}'
)
Interpreting the results
After running the above code, you will see output similar to the following:
Epoch [100/1000], Loss: 0.0654
Epoch [200/1000], Loss: 0.0398
Epoch [300/1000], Loss: 0.0243
Epoch [400/1000], Loss: 0.0148
Epoch [500/1000], Loss: 0.0090
Epoch [600/1000], Loss: 0.0055
Epoch [700/1000], Loss: 0.0033
Epoch [800/1000], Loss: 0.0020
Epoch [900/1000], Loss: 0.0012
Epoch [1000/1000], Loss: 0.0008
训练后的权重: [[2.0016 2.9973]]
训练后的偏置: [4.0015]
真实权重: [2. 3.]
真实偏置: 4.0
As you can see, as the number of epochs increases, the loss keeps decreasing, and finally the model's weights and bias are very close to the true values, showing that the model successfully learned the linear relationship in the data.
Extension: using a more complex optimizer
Besides SGD, PyTorch offers many other optimizers; below is an example using the Adam optimizer:
Example
Use the Adam optimizer (usually converges faster)
optimizer
=
torch.
optim
.
Adam
(
model.
parameters
(
)
,
lr
=
0.01
)
Train the model
for
epoch
in
range
(
num_epochs
)
:
model.
train
(
)
predictions
=
model
(
X
)
loss
=
criterion
(
predictions.
squeeze
(
)
,
Y
)
optimizer.
zero_grad
(
)
loss.
backward
(
)
optimizer.
step
(
)
if
(
epoch +
1
)
%
100
==
0
:
(
f
'Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}'
)
| Optimizer | Feature | Applicable scenarios |
|---|---|---|
| SGD | Simple and direct, requires manual tuning of the learning rate | Large datasets, classic scenarios |
| Adam | Adaptive learning rate, fast convergence | Most scenarios, recommended default choice |
| RMSprop | Suitable for recurrent neural networks | Sequence models such as RNN and LSTM |
Common questions
Problem 1: loss does not decrease
If the loss does not decrease during training, possible reasons include:
- Learning rate too small, resulting in tiny parameter updates.
- Learning rate too large, causing the optimizer to skip the optimum.
- Problems with the data, such as widely varying feature ranges.
Solutions:
- Try adjusting the learning rate (start with 0.1, 0.01, 0.001).
- Normalize the input data.
- Check for outliers or missing values in the data.
Problem 2: prediction shape mismatch
If a shape mismatch error occurs when computing the loss, you may need to use squeeze() or unsqueeze() to reshape the tensor.
Example
Check the output shape
predictions
=
model
(
X
)
(
f
'Model output shape: {predictions.shape}'
)
Should be [100, 1]
Squeeze to 1D
predictions
=
predictions.
squeeze
(
)
(
f
'Shape after squeezing: {predictions.shape}'
)
Should be [100]
Compute the loss
loss
=
criterion
(
predictions
,
Y
)
Problem 3: how to improve model accuracy
- Increase the number of training epochs.
- Adjust the learning rate.
- Use a more complex model architecture (such as a multilayer neural network).
- Increase the amount of training data.