Surrogate Model in Python: 5 Easy Steps for CFD and FEA Results

A surrogate model in Python is a fast stand-in for a slow CFD or FEA simulation. You run the solver for a limited set of cases, train a regression model on the results, and then predict new cases instantly. In this guide you build one in five steps and see which model type works best, using real code output.

Surrogate model in Python: five-step workflow from running CFD or FEA cases to validating and using the model
The five steps of a surrogate model project.

What Is a Surrogate Model and When Do You Need One?

A solver run can take minutes or hours. A design study may need hundreds of runs, for example to find the best tube diameter for a heat transfer target. A surrogate learns the link between inputs (such as velocity, diameter, heat flux) and one output (such as wall temperature rise) so you can scan many designs quickly and run the full solver only for the best few.

An honest note on the data: this guide does not use real solver files. The “simulation results” are generated by a standard heat transfer correlation for turbulent flow in a tube, with 2% random scatter added to behave like solver noise. This lets you run everything yourself. With real work, you replace the table with your own CFD or FEA results and keep the same steps.

Step 1: Build the Table of Cases

Each row is one simulation. The inputs are Reynolds number, tube diameter and wall heat flux, and the output is the temperature difference between the wall and the air.

import numpy as np, pandas as pd

rng = np.random.default_rng(3)

def run_case(Re, D, q):
    Pr, k = 0.71, 0.026                 # air near 300 K
    Nu = 0.023 * Re**0.8 * Pr**0.4      # Dittus-Boelter type correlation
    h = Nu * k / D
    return q / h                        # wall minus bulk temperature, K

n = 80
Re = rng.uniform(5000, 50000, n)        # Reynolds number
D  = rng.uniform(0.010, 0.030, n)       # tube diameter, m
q  = rng.uniform(500, 3000, n)          # wall heat flux, W/m2
dT = run_case(Re, D, q) * (1 + rng.normal(0, 0.02, n))   # 2% scatter
df = pd.DataFrame({'Re': Re, 'D_m': D, 'q_Wm2': q, 'dT_K': dT})
print(df.head().round(3))
print(df.dT_K.describe().round(2))
         Re    D_m     q_Wm2     dT_K
0  8854.213  0.013   632.574   10.543
1 15656.473  0.016  1970.733   25.894
2 41057.351  0.020   934.778    7.345
3 31197.292  0.027  2419.576   32.268
4  9235.789  0.029  2844.078  105.009
count    80.00
mean     24.03
std      19.91
min       3.97
25%      11.85
50%      19.56
75%      31.31
max     113.93

The output ranges from about 4 K to 114 K, so the response changes a lot across the design space. That already hints that a straight-line model will struggle.

Step 2: Train Several Models and Compare Them

We hold back 25% of the cases (20 runs) as unseen test cases and try four common regression models.

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel, ConstantKernel as C
from sklearn.metrics import r2_score, mean_absolute_error

X = df[['Re', 'D_m', 'q_Wm2']]; y = df.dT_K
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, random_state=1)

gp = GaussianProcessRegressor(C(1.0) * RBF([1, 1, 1]) + WhiteKernel(1e-2),
                              normalize_y=True, random_state=1, n_restarts_optimizer=3)
models = {
  'Linear (raw inputs)': make_pipeline(StandardScaler(), LinearRegression()),
  'Random forest': RandomForestRegressor(n_estimators=300, random_state=1),
  'Polynomial deg 2': make_pipeline(StandardScaler(), PolynomialFeatures(2), LinearRegression()),
  'Gaussian process': make_pipeline(StandardScaler(), gp),
}
for name, m in models.items():
    m.fit(Xtr, ytr); p = m.predict(Xte)
    print(f'{name}: R2 {r2_score(yte, p):.3f}  MAE {mean_absolute_error(yte, p):.3f} K')
Linear (raw inputs): R2 0.806  MAE 4.627 K
Random forest: R2 0.574  MAE 5.051 K
Polynomial deg 2: R2 0.919  MAE 2.932 K
Gaussian process: R2 0.955  MAE 1.136 K

Step 3: Use Physics to Choose the Model

Heat transfer relations are power laws, so taking the logarithm of the inputs and the output turns the curve into a straight line. A plain linear model on logarithms then does much better than the fancier models:

# Heat transfer follows power laws, so work in logarithms
Xl = np.log(X)
m = make_pipeline(StandardScaler(), LinearRegression())
m.fit(Xl.loc[Xtr.index], np.log(ytr))
p = np.exp(m.predict(Xl.loc[Xte.index]))
print(f'Linear on log inputs and output: R2 {r2_score(yte, p):.3f}  MAE {mean_absolute_error(yte, p):.3f} K')
Linear on log inputs and output: R2 0.999  MAE 0.320 K
Surrogate model in Python: error of five regression models on unseen cases
Error on 20 unseen cases for five surrogate models. Lower is better.
ModelR²Mean error on unseen casesComment
Random forest0.5745.051 KNeeds far more runs for smooth trends
Linear, raw inputs0.8064.627 KCannot follow a curved response
Polynomial, degree 20.9192.932 KBetter, still not enough
Gaussian process0.9551.136 KStrong choice for small, smooth data
Linear on logs0.9990.320 KBest here because the physics is a power law

Be careful with this lesson. The log model wins because our generated data follows a power law exactly. Real CFD results can have separation, buoyancy or other effects, so always test on your own data. The general rule still holds: let the physics suggest the form of the model before you reach for a complex one.

Step 4: Validate Outside the Training Range

A surrogate is often used to predict new designs, so test the hardest case: train on low Reynolds numbers and test on higher ones the model never saw.

tr = df.Re < 30000     # train only on lower Reynolds numbers
te = df.Re >= 40000    # test on higher ones the model never saw

rf = RandomForestRegressor(n_estimators=300, random_state=1).fit(X[tr], y[tr])
print('Random forest MAE:', mean_absolute_error(y[te], rf.predict(X[te])).round(3), 'K')

lg = LinearRegression().fit(np.log(X[tr]), np.log(y[tr]))
print('Log-linear MAE:', mean_absolute_error(y[te], np.exp(lg.predict(np.log(X[te])))).round(3), 'K')
Random forest MAE: 13.862 K  (17 test cases)
Log-linear MAE: 0.296 K  (17 test cases)
ModelError when extrapolatingWhat happened
Random forest13.862 KPredictions stopped following the trend outside the training data
Log-linear regression0.296 KThe physical trend carried on correctly

Tree models, including random forests, cannot extend a trend beyond their data. If your design study needs values outside the simulated range, add simulations there, or use a model that follows the physics.

Step 5: Use the Surrogate and Know Its Limits

DoDo not
Predict inside the range of your simulationsTrust predictions outside that range
Report the error measured on unseen casesReport only the error on training data
Check the best design with the full solverSubmit a design found only by the surrogate
Add new simulations where the error is largeKeep adding model complexity instead of data
Say clearly in your report that results are surrogate predictionsPresent them as solver results

Common Mistakes

  • Too few runs for too many inputs. Every extra input needs more cases.
  • Picking cases by hand. Spread the runs across the whole range, for example with Latin hypercube sampling.
  • No unseen test cases. A model can fit its training data perfectly and still be useless.
  • Ignoring units and scales. Scale inputs before using methods that compare distances.
  • Skipping data checks. Clean the table first with our data cleaning in Python guide.

Where to Go Next

Plot your simulation results first with our guide to plotting CFD and FEA results in Python, check Reynolds number values with the Reynolds number calculator, then learn the basics in linear regression in Python and machine learning for beginners. For project topics, see thermal analysis projects and Python for mechanical engineers. The scikit-learn Gaussian process guide explains the kernel options used above.

If you want help planning the simulation cases or the validation for your own project, you can reach us through the 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.

FAQs

What is a surrogate model?

It is a fast model trained on results from a slow simulation. After training, it predicts the output for new inputs in a fraction of a second instead of running the solver again.

How many simulation runs do I need?

It depends on how many inputs you vary and how curved the response is. Here 80 cases were enough for three inputs. Start small, check the error on unseen cases, and add runs where the error is high.

Why did random forest fail on new Reynolds numbers?

A tree model predicts values it has seen in training. It cannot continue a trend beyond its data, so it flattens out. Smooth models such as regression or Gaussian processes can extend a trend more safely.

Can I trust a surrogate outside its training range?

No. Use it only inside the range of the simulations it was trained on, and run the full solver to confirm any important design point.

Is this allowed in a final year project?

Yes, if you explain your inputs, show your validation on unseen cases and state the limits. Examiners value a clear validation more than a complicated model.

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

Enquire on WhatsApp
Scroll to Top