Linear Regression in Python: 4 Easy Steps with an Engineering Example

Linear regression in Python is the simplest and most useful machine learning method for engineers. It fits a straight line through measured data and gives you a slope, an intercept and a way to predict new values. In this guide you will learn linear regression in Python in four easy steps, using a real engineering task: finding the Young’s modulus of steel from noisy stress and strain readings. The full code runs as it is. For the maths behind it, see linear regression.

Linear regression in Python: stress vs strain data with fitted line giving Young's modulus

What Linear Regression Does in Engineering

Many engineering relationships are close to linear over a useful range. Stress rises linearly with strain in the elastic region, deflection rises linearly with load, and pressure drop in slow flow rises with flow rate. Linear regression finds the line y = m·x + c that best matches your readings by minimising the squared error. The slope m often has a physical meaning. In a tensile test the slope of stress against strain is the Young’s modulus, which our stress strain curve guide explains in detail.

4 Easy Steps of Linear Regression in Python

  1. Prepare the data. Put the input (strain) in a column and the output (stress) in an array.
  2. Split into training and test sets. The model learns from one part and is checked on the other.
  3. Fit the model. scikit-learn finds the best slope and intercept in one line.
  4. Check the result. Read the slope, then check R², the error in real units and whether the prediction makes physical sense.

Linear Regression in Python: Full Code

The code below creates 40 elastic-region readings for steel with a true modulus of 200 GPa and adds measurement noise of 12 MPa. It then fits a line on 75 percent of the data and tests it on the remaining 25 percent. With real lab data you would load your readings from a CSV file with pandas instead, as shown in our pandas tutorial.

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_absolute_error

rng = np.random.default_rng(7)
E_true = 200.0                                    # GPa, steel (elastic range)
strain = np.linspace(0.0002, 0.0012, 40)          # dimensionless, elastic region only
stress = E_true * 1e3 * strain + rng.normal(0, 12, strain.size)   # MPa, with measurement noise

X = strain.reshape(-1, 1)
Xtr, Xte, ytr, yte = train_test_split(X, stress, test_size=0.25, random_state=3)

model = LinearRegression().fit(Xtr, ytr)
pred = model.predict(Xte)

print(f"Young's modulus estimate: {model.coef_[0]/1e3:.1f} GPa")
print(f"intercept: {model.intercept_:.2f} MPa")
print(f"R2 on test data: {r2_score(yte, pred):.4f}")
print(f"MAE on test data: {mean_absolute_error(yte, pred):.2f} MPa")
print(f"predicted stress at strain 0.0010: {model.predict([[0.0010]])[0]:.1f} MPa")

Output:

Young's modulus estimate: 197.7 GPa
intercept: -1.87 MPa
R2 on test data: 0.9449
MAE on test data: 9.15 MPa
predicted stress at strain 0.0010: 195.8 MPa

Download the data: stress-strain-elastic-data.csv (40 readings, strain and stress in MPa). It is the simulated data used above, so you can load it with pandas and repeat the fit.

How to Read the Linear Regression Result

The estimated modulus is 197.7 GPa, which is within 1.2 percent of the true value of 200 GPa, even with noisy readings. R² on the unseen test data is 0.9449, so the line explains about 94 percent of the variation. The mean absolute error is 9.15 MPa, which is in the same range as the 12 MPa noise we added, so the model is doing about as well as the data allows. The intercept of -1.87 MPa is very close to zero, which is physically correct because stress should be zero at zero strain.

MetricValueMeaning
Slope197.7 GPaYoung’s modulus estimate
Intercept-1.87 MPaShould be near zero for this test
R² (test)0.9449Share of variation explained
MAE (test)9.15 MPaTypical error in real units

A warning about extrapolation

Ask the same model for the stress at a strain of 0.01 and it answers 1,975 MPa. That is physically impossible for ordinary steel, because the material yields long before that point and the stress-strain line stops being straight. A regression line is only valid inside the range of data it was trained on. Always state that range in your report.

Common Mistakes in Linear Regression Projects

  • Extrapolating beyond the data range. Linear models fail outside the elastic region, as shown above.
  • Trusting R² alone. A high R² can hide a curved trend. Always plot the data and the line.
  • Mixing units. Keep strain dimensionless and stress in MPa throughout, and convert the slope once at the end.
  • Testing on the training data. Always keep unseen data for the final check.
  • Using a line for a curved relationship. If the plot bends, use a polynomial or another model.

Project Ideas Using Linear Regression

  • Fit the spring constant from force and extension data.
  • Estimate thermal conductivity from heat flow and temperature gradient data.
  • Predict pressure drop against flow rate in a pipe in the laminar range.
  • Relate cutting force to feed rate in a machining test.
  • Predict battery capacity fade against cycle count over a short range.

For larger project lists, see our machine learning projects for final year and Python projects for beginners pages, and our next step in this series, predictive maintenance in Python.

Where Students Usually Get Stuck

The code is short, but real projects bring messy data, outliers, unit errors and questions from examiners such as “why a straight line?” and “how reliable is the slope?”. These depend on your own experiment and your guide’s expectations. If you send us your data description and your first attempt, we can review your approach, explain what the numbers mean and teach you the next step, so you complete the work yourself. Message us on WhatsApp or see our Python for mechanical engineers page.

A note on the code in this guide. It is a small learning demo that shows how the method works, using generated data. For a full project with your own data, complete analysis, code and report, we offer paid project support, where we plan the work with you and explain every step. Contact us through the Python for mechanical engineers page to discuss your topic and the cost.

Frequently Asked Questions

What is linear regression in Python used for?

It is used to fit a straight-line relationship between measured quantities and to predict new values inside the range of the data.

Which library is best for linear regression in Python?

scikit-learn is the easiest for machine learning workflows. NumPy’s polyfit is fine for quick fits, and statsmodels gives detailed statistics such as confidence intervals.

What is a good R² value?

It depends on the noise in the experiment. For a clean lab test above 0.95 is common, but R² must be read together with the error in real units and a plot of the data.

Can linear regression predict outside my data range?

It can calculate a number, but the number may be meaningless. Stay inside the range of the training data unless you know the physics stays linear.

How is linear regression different from machine learning models like random forest?

Linear regression is simple, fast and easy to explain. Random forest handles curved and complex relationships but is harder to interpret. Start with linear regression and move on only if it fits badly.

Related guides: beam deflection in Python, Newton Raphson method in Python and how to plot results with Python.

Interested in this project? Get the details, files and guidance from our team.

Enquire on WhatsApp
Scroll to Top