Predictive Maintenance in Python: 4 Easy Steps with Machine Learning

Predictive maintenance uses sensor data and machine learning to find a developing fault before the machine breaks down. Instead of replacing a bearing every six months or waiting for it to fail, you replace it when the data says it is needed. In this guide you will build a predictive maintenance model in Python in four easy steps: create vibration data, extract features, train a random forest and read the result honestly. The full code runs as it is. For the idea behind the topic, see predictive maintenance.

Predictive maintenance in Python pipeline: sensor data, features, random forest model and maintenance decision

What Predictive Maintenance Means for Mechanical Engineers

There are three maintenance styles. Reactive maintenance fixes a machine after it fails. Preventive maintenance follows a fixed calendar. Predictive maintenance watches the condition of the machine and acts when the condition changes. Vibration is the most common signal for rotating machines such as motors, pumps, fans and gearboxes, because a worn bearing or a loose part changes the vibration pattern long before the machine stops. If you have not worked with vibration signals before, read our guide on vibration analysis in Python with FFT first.

4 Easy Steps of a Predictive Maintenance Project in Python

  1. Collect or simulate vibration records. Each record is one second of acceleration data labelled healthy or faulty.
  2. Extract features. Turn each record into a few numbers: RMS, kurtosis, crest factor and the energy in the band where a fault resonance appears.
  3. Train a classifier. A random forest learns the difference between healthy and faulty records.
  4. Test it on unseen records. Check accuracy, the confusion matrix and which features mattered.

Predictive Maintenance in Python: Full Code

The code below creates 600 simulated records (300 healthy and 300 with a bearing fault), extracts four features from each and trains a random forest. The data is synthetic so that you can run it anywhere. The fault is a train of small impacts at 87 Hz that excite a 1,200 Hz resonance, hidden in noise, which is how an early bearing defect often looks.

import numpy as np
from scipy.stats import kurtosis
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

rng = np.random.default_rng(42)
fs, n = 5000, 5000            # sampling rate (Hz) and samples per record (1 second)
t = np.arange(n) / fs

def make_signal(fault):
    s = 1.0*np.sin(2*np.pi*50*t) + 0.3*np.sin(2*np.pi*100*t)       # shaft and harmonic
    if fault:
        # bearing fault: periodic impacts at 87 Hz exciting a 1200 Hz resonance
        impulses = (np.sin(2*np.pi*87*t) > 0.999).astype(float)
        decay = np.exp(-800*t[:60])*np.sin(2*np.pi*1200*t[:60])
        s += 0.9*np.convolve(impulses, decay)[:n]
    return s + rng.normal(0, 0.6, n)

def features(x):
    spec = np.abs(np.fft.rfft(x))/len(x)
    freqs = np.fft.rfftfreq(len(x), 1/fs)
    return [np.sqrt(np.mean(x**2)), kurtosis(x), np.max(np.abs(x))/np.sqrt(np.mean(x**2)), spec[(freqs>1000)&(freqs<1400)].sum()]

X, y = [], []
for _ in range(300):
    X.append(features(make_signal(False))); y.append(0)
    X.append(features(make_signal(True)));  y.append(1)
X, y = np.array(X), np.array(y)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, random_state=1, stratify=y)
clf = RandomForestClassifier(n_estimators=200, random_state=1).fit(Xtr, ytr)
pred = clf.predict(Xte)
print("records:", len(y), "| train:", len(ytr), "| test:", len(yte))
print("accuracy:", round(accuracy_score(yte, pred), 3))
print("confusion matrix [healthy, faulty]:\n", confusion_matrix(yte, pred))
names = ["RMS","Kurtosis","Crest factor","1.0-1.4 kHz band energy"]
for nme, imp in sorted(zip(names, clf.feature_importances_), key=lambda z:-z[1]):
    print(f"{nme}: {imp:.2f}")

Output:

records: 600 | train: 450 | test: 150
accuracy: 0.827
confusion matrix [healthy, faulty]:
 [[57 18]
 [ 8 67]]
1.0-1.4 kHz band energy: 0.58
RMS: 0.27
Kurtosis: 0.09
Crest factor: 0.07

How to Read the Predictive Maintenance Result

The model reaches 82.7 percent accuracy on 150 unseen records. It missed 8 faulty records and raised 18 false alarms. Look at the feature importance. The 1.0 to 1.4 kHz band energy carries 58 percent of the importance, while kurtosis and crest factor carry only 9 and 7 percent. In this early-fault case, the average RMS of healthy and faulty records is almost the same (0.95 and 0.96), so a simple RMS alarm would not catch the fault. The spectrum does. This is the main lesson of predictive maintenance: choose features based on the physics of the fault.

FeatureWhat it measuresGood for
RMSOverall vibration energyUnbalance, severe wear
KurtosisSpikiness of the signalEarly impacts, if the noise is low
Crest factorPeak compared with RMSIsolated shocks
Band energyEnergy near a resonanceBearing and gear faults

Common Mistakes in Predictive Maintenance Projects

  • Trusting 100 percent accuracy. Perfect scores usually mean the data is too easy or the test records leaked into training.
  • Mixing training and test records from the same machine run. Split by machine or by time, not randomly.
  • Using only RMS. It misses early faults, as the result above shows.
  • Ignoring false alarms. Too many false alarms make operators ignore the system.
  • Using only synthetic data in a thesis. Validate on a public bearing dataset or on your own measured data.

Project Ideas to Extend This Predictive Maintenance Model

  • Add a third class for a gear fault and train a multi-class model.
  • Predict remaining useful life with regression instead of classification.
  • Replace the random forest with a small neural network and compare.
  • Test the model on a public bearing dataset and report precision and recall.
  • Add temperature and current signals to the features.

For more ideas that combine mechanical engineering with data, see our machine learning projects for final year, data science projects and Python for mechanical engineers pages.

Where Students Usually Get Stuck

The code is short, but a real project needs a real dataset, the right features for your machine and a fair way to test the model. Students often get stuck choosing features, splitting data correctly and explaining the result to examiners. If you send us your dataset 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.

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 predictive maintenance in simple words?

It means repairing a machine when its data shows a developing problem, instead of waiting for a breakdown or following a fixed calendar.

Which Python libraries are used for predictive maintenance?

NumPy and SciPy for signals and features, pandas for data tables, scikit-learn for models and Matplotlib for plots. See our NumPy tutorial to get started.

Do I need real sensor data?

You can learn the method with simulated data, as here. For a final year project or thesis, you should also test on a public dataset or on measured data from a lab setup.

Why is accuracy not enough?

Accuracy hides the cost of errors. A missed fault can destroy a machine, and a false alarm wastes time. Report precision, recall and the confusion matrix.

Is predictive maintenance a good final year project?

Yes. It combines mechanical knowledge (vibration, bearings), signal processing and machine learning, and examiners can see a clear problem and a measurable result.

Related guides: types of bearings, pandas for engineers 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