Pulse Data Hub

Data Science in Manufacturing: 8 Use Cases and a Predictive Maintenance Project

A factory produces data all the time: sensor readings from machines, results from quality inspections, production schedules, energy meters, supplier deliveries. Data science in manufacturing is about turning that data into fewer breakdowns, less scrap, better plans and lower costs.

This guide covers the main use cases of data science in the manufacturing industry, then builds the best-known one in Python: a predictive maintenance model that learns to spot machine failures before they happen. It also shows the two decisions that matter most in a real project, which features to build and when to raise an alert. Every number below comes from running the code in this article.

How data science is used in manufacturing

Use caseQuestion it answersTypical dataCommon methods
Predictive maintenanceWhich machine is likely to fail soon?Sensor readings, run hours, maintenance logsClassification, anomaly detection, remaining-useful-life models
Quality controlWhich parts or batches are likely to be defective?Process parameters, inspection resultsClassification, statistical process control
Visual inspectionDoes this part have a scratch, crack or missing component?Camera imagesConvolutional neural networks
Process optimization and yieldWhich settings give the most good parts?Process parameters, yield per batchRegression, design of experiments, optimization
Demand forecasting and production planningHow much should we make, and when?Orders, sales history, seasonalityTime series forecasting
Supply chain and inventoryHow much stock of each part should we hold?Supplier lead times, usage, stock levelsForecasting, optimization, simulation
Energy managementWhere is energy wasted, and when is it cheapest to run?Energy meters, machine states, tariffsTime series analysis, optimization
Digital twins and simulationWhat happens if we change the line?Process models plus live sensor dataSimulation, physics-based and machine learning models
Common uses of data science in the manufacturing industry.

Most of this data already exists. Machines report readings to control systems, a manufacturing execution system (MES) tracks what the line produced and when, the ERP system holds orders and stock, and quality teams record inspection results. The hard part is usually joining these sources: they use different IDs, time stamps and levels of detail, and few of them share data easily.

Why predictive maintenance comes first

There are three ways to maintain a machine:

  • Reactive: run it until it breaks, then fix it. Simple, but a breakdown stops production, can damage parts and often costs far more than a planned repair.
  • Preventive: service it on a fixed schedule, for example every 500 hours. Breakdowns are rarer, but teams often replace parts that still have life left.
  • Predictive: use data to estimate when each machine is likely to fail and service it just before. This aims for the best of both: fewer breakdowns and less wasted maintenance.

Predictive maintenance is often the first data science project in a factory because the value is easy to measure: every unplanned stop it prevents has a known cost. The project below builds one.

Python project: predict machine failures

The data is the AI4I 2020 Predictive Maintenance Dataset from the UCI Machine Learning Repository, published by S. Matzka in 2020. It is synthetic: generated to reflect the kind of data a real milling machine produces, because companies rarely publish real factory failure data. That makes it ideal for learning, with one caveat covered at the end: real data is messier. It has 10,000 records, each with the machine’s air and process temperature, rotational speed, torque, tool wear, the product quality variant (L, M or H) and whether the machine failed.

You need pandas, scikit-learn and Matplotlib:

pip install pandas scikit-learn matplotlib

1. Load the data

The code reads a copy of the dataset stored on GitHub, so it runs without a manual download, and gives the columns short names:

import pandas as pd

URL = ("https://raw.githubusercontent.com/lingchenlijing/"
       "AI4I-2020-Predictive-Maintenance-Dataset/master/data/ai4i2020.csv")
df = pd.read_csv(URL)
df.columns = ["udi", "product_id", "type", "air_temp", "process_temp", "rpm",
              "torque", "tool_wear", "failure", "TWF", "HDF", "PWF", "OSF", "RNF"]

print(df.shape)
print(df.head(3).to_string())

Output:

(10000, 14)
   udi product_id type  air_temp  process_temp   rpm  torque  tool_wear  failure  TWF  HDF  PWF  OSF  RNF
0    1     M14860    M     298.1         308.6  1551    42.8          0        0    0    0    0    0    0
1    2     L47181    L     298.2         308.7  1408    46.3          3        0    0    0    0    0    0
2    3     L47182    L     298.1         308.5  1498    49.4          5        0    0    0    0    0    0

2. Explore the failures

print(f"Machine failures: {df['failure'].sum()} of {len(df):,} ({df['failure'].mean():.2%})")
print(df.groupby("type")["failure"].agg(["size", "mean"]).round(4).to_string())

modes = ["TWF", "HDF", "PWF", "OSF", "RNF"]
print(df[modes].sum().to_string())

# Check the labels against each other
any_mode = df[modes].any(axis=1)
print("Failures with no mode recorded:", (df["failure"].eq(1) & ~any_mode).sum())
print("Modes recorded without a failure:", (df["failure"].eq(0) & any_mode).sum())

Output:

Machine failures: 339 of 10,000 (3.39%)
      size    mean
type              
H     1003  0.0209
L     6000  0.0392
M     2997  0.0277
TWF     46
HDF    115
PWF     95
OSF     98
RNF     19
Failures with no mode recorded: 9
Modes recorded without a failure: 18

Only 339 of the 10,000 records, 3.39%, are failures. That is typical: machines work most of the time, so failure data is always rare, and a model that simply predicts “no failure” every time would be 96.6% accurate and completely useless. Accuracy is the wrong score for this problem, which is why the models below use different scores.

The five columns after failure record the failure mode: tool wear failure (TWF), heat dissipation failure (HDF), power failure (PWF), overstrain failure (OSF) and random failure (RNF). Two checks show the labels don’t fully agree: 9 failures have no mode recorded, and 18 records have a random-failure flag but no failure. Inconsistent labels are normal in maintenance data, which people often type in by hand after the event. The model below predicts the overall failure column and leaves the mode columns out, because nobody knows them until after a failure. Using them as inputs would be data leakage: the model would look perfect in testing and be useless in practice.

Low-quality (L) products have the highest failure rate, 3.9% against 2.1% for high-quality (H) ones.

3. Build features from engineering knowledge

The raw readings don’t describe the physics directly. Three combinations do: the mechanical power the machine delivers (torque times rotational speed in radians per second), the temperature difference between the process and the air, which shows how well heat is being removed, and strain on the tool, tool wear times torque.

import numpy as np

df["power"] = df["torque"] * df["rpm"] * 2 * np.pi / 60    # watts
df["temp_diff"] = df["process_temp"] - df["air_temp"]       # kelvin
df["strain"] = df["tool_wear"] * df["torque"]               # minute-newton-metres

print(df[["power", "temp_diff", "strain"]].describe().round(1).to_string())

print("Failure rate by power band:")
bands = pd.cut(df["power"], [0, 3500, 9000, np.inf], labels=["< 3.5 kW", "3.5-9 kW", "> 9 kW"])
print(df.groupby(bands, observed=True)["failure"].agg(["size", "mean"]).round(3).to_string())

Output:

         power  temp_diff   strain
count  10000.0    10000.0  10000.0
mean    6279.7       10.0   4314.7
std     1067.4        1.0   2826.6
min     1148.4        7.6      0.0
25%     5561.2        9.3   1963.6
50%     6271.0        9.8   4013.0
75%     7003.0       11.0   6279.0
max    10469.9       12.1  16497.0
Failure rate by power band:
          size   mean
power                
< 3.5 kW    31  1.000
3.5-9 kW  9905  0.025
> 9 kW      64  1.000

The power feature alone separates a whole class of failures: every record below 3.5 kW or above 9 kW is a failure, against 2.5% in between. In this synthetic data the rule is exact because the dataset’s author generated power failures that way. In a real machine the boundary would be fuzzier, but the lesson holds: features that express what engineers already know about how a machine fails are often worth more than a more complex model.

4. Look at the operating range

import matplotlib.pyplot as plt

ok, fail = df[df["failure"] == 0], df[df["failure"] == 1]
fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(ok["rpm"], ok["torque"], s=4, color="#c3cad3", label="No failure")
ax.scatter(fail["rpm"], fail["torque"], s=12, color="#c8242c", label="Failure")
ax.set_xlabel("Rotational speed (rpm)")
ax.set_ylabel("Torque (Nm)")
ax.set_title("Failures cluster at the edges of the operating range")
ax.legend(frameon=False, markerscale=2)
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("operating_range.png", dpi=150, bbox_inches="tight")
plt.show()
Scatter plot of torque against rotational speed for 10,000 records. Normal records form a curved grey band; red failure points cluster at the top left, where speed is low and torque is high, and along the bottom right, where speed is high and torque very low
Torque against rotational speed. Failures (red) gather at the edges of the normal operating band.

Most failures sit at the edges of the normal band: low speed with high torque at the top left, and very high speed with very low torque at the bottom right. That has a consequence for the choice of model. Risk doesn’t rise steadily in one direction, it rises at both ends, which a straight-line model like logistic regression can’t capture without extra work.

5. Train and compare models

The code splits the data into 70% for training and 30% for testing, keeping the same share of failures in both. The code compares four models: logistic regression and gradient boosting, each on the raw readings and on the readings plus the three engineered features.

from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.compose import make_column_transformer
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score, average_precision_score

raw = ["air_temp", "process_temp", "rpm", "torque", "tool_wear"]
engineered = raw + ["power", "temp_diff", "strain"]
X = df[engineered + ["type"]]
y = df["failure"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=42)

def build(kind, cols):
    prep = make_column_transformer(
        (OneHotEncoder(), ["type"]),
        (StandardScaler(), cols))
    if kind == "logistic":
        est = LogisticRegression(max_iter=1000, class_weight="balanced")
    else:
        est = HistGradientBoostingClassifier(random_state=42)
    return make_pipeline(prep, est)

def model(kind, cols):
    return build(kind, cols).fit(X_train, y_train)

def report(name, m):
    p = m.predict_proba(X_test)[:, 1]
    print(f"{name:<34} ROC AUC {roc_auc_score(y_test, p):.3f}   "
          f"PR AUC {average_precision_score(y_test, p):.3f}")
    return p

print(f"Test set: {len(y_test):,} records, {y_test.sum()} failures")
report("Logistic regression, raw", model("logistic", raw))
report("Logistic regression, engineered", model("logistic", engineered))
report("Gradient boosting, raw", model("boost", raw))
best = model("boost", engineered)
proba = report("Gradient boosting, engineered", best)

Output:

Test set: 3,000 records, 102 failures
Logistic regression, raw           ROC AUC 0.888   PR AUC 0.380
Logistic regression, engineered    ROC AUC 0.920   PR AUC 0.386
Gradient boosting, raw             ROC AUC 0.977   PR AUC 0.798
Gradient boosting, engineered      ROC AUC 0.987   PR AUC 0.892

The output shows two scores. ROC AUC measures how well a model ranks failures above normal records, where 0.5 is random and 1.0 is perfect. PR AUC (the area under the precision-recall curve, also called average precision) focuses only on how well the failures are found and how many alerts are false, and for rare events it is the more honest score: random guessing would score only about 0.034 here, the failure rate.

Gradient boosting beats logistic regression by a wide margin, PR AUC 0.798 against 0.380 on the raw readings, because it can learn that risk is high at both ends of a range. The engineered features then lift it further, to 0.892. Logistic regression barely improves with the same features, because the problem isn’t missing information but the shape of the relationship.

6. Choose when to raise an alert

A model outputs a probability of failure. Turning that into an action, such as “inspect this machine now”, needs a threshold. The usual default is 0.5, but nothing makes 0.5 special:

from sklearn.metrics import confusion_matrix

for t in [0.5, 0.2, 0.05]:
    tn, fp, fn, tp = confusion_matrix(y_test, proba >= t).ravel()
    print(f"threshold {t:<4}  caught {tp}/{tp + fn} failures ({tp / (tp + fn):.0%}), "
          f"{fp} false alarms, {tp + fp} inspections")

Output:

threshold 0.5   caught 83/102 failures (81%), 9 false alarms, 92 inspections
threshold 0.2   caught 85/102 failures (83%), 13 false alarms, 98 inspections
threshold 0.05  caught 87/102 failures (85%), 31 false alarms, 118 inspections

Lowering the threshold catches more failures but raises more false alarms. The right balance depends on what each outcome costs. The next step assumes an unplanned failure costs 10,000 and a planned inspection 500. These numbers are assumptions for this example; in a real project they come from the maintenance and finance teams. The code chooses the threshold on the training data using cross-validation, then checks it once on the test set, so the test result stays honest.

from sklearn.model_selection import cross_val_predict

COST_FAILURE = 10_000    # unplanned breakdown: repair, scrap, lost output (assumed)
COST_CHECK = 500         # planned inspection or tool change (assumed)

def total_cost(y_true, p, t):
    tn, fp, fn, tp = confusion_matrix(y_true, p >= t).ravel()
    return fn * COST_FAILURE + (tp + fp) * COST_CHECK, tp, fp

# Choose the threshold on the training data only, using out-of-fold predictions
oof = cross_val_predict(build("boost", engineered), X_train, y_train,
                        cv=5, method="predict_proba")[:, 1]
thresholds = np.geomspace(0.001, 0.9, 200)
costs = np.array([total_cost(y_train, oof, t)[0] for t in thresholds])
best_t = thresholds[costs.argmin()]

# Then check it once on the test set
print(f"No model (fix every failure after it happens): {y_test.sum() * COST_FAILURE:,}")
for name, t in [("threshold 0.5", 0.5), (f"chosen threshold {best_t:.3f}", best_t)]:
    cost, tp, fp = total_cost(y_test, proba, t)
    print(f"Model, {name}: {cost:,} ({tp} failures caught, {fp} false alarms)")

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(thresholds, costs / 1000, color="#1f4e79")
ax.axvline(best_t, color="#c8242c", linestyle="--", label=f"Lowest cost at {best_t:.3f}")
ax.set_xscale("log")
ax.set_xlabel("Alert threshold (predicted probability of failure, log scale)")
ax.set_ylabel("Cost on training data (thousands)")
ax.set_title("Pick the threshold by cost, not by accuracy")
ax.legend(frameon=False)
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("threshold_cost.png", dpi=150, bbox_inches="tight")
plt.show()

Output:

No model (fix every failure after it happens): 1,020,000
Model, threshold 0.5: 236,000 (83 failures caught, 9 false alarms)
Model, chosen threshold 0.011: 188,500 (91 failures caught, 66 false alarms)
Line chart of total cost on the training data against the alert threshold on a log scale from 0.001 to 0.9. Cost is lowest, about 490 thousand, at a threshold of 0.011, rises above about 0.05 and reaches about 800 thousand at 0.9
Cost of missed failures plus inspections at each alert threshold, measured on the training data with cross-validation.

With these costs, the best threshold is 0.011, much lower than 0.5. On the test set it catches 91 of the 102 failures (89%) at the price of 66 false alarms, and the total cost falls from 1,020,000 without a model to 188,500, against 236,000 at the default threshold. The general rule: when a missed failure costs much more than a check, set a low threshold and accept extra inspections.

7. See which failures the model misses

test = df.loc[X_test.index].assign(alert=proba >= best_t)
failed = test[test["failure"] == 1]
for mode in ["TWF", "HDF", "PWF", "OSF"]:
    rows = failed[failed[mode] == 1]
    print(f"{mode}: {rows['alert'].sum()} of {len(rows)} caught")
rows = failed[~failed[modes].any(axis=1)]
print(f"No mode recorded: {rows['alert'].sum()} of {len(rows)} caught")

Output:

TWF: 5 of 13 caught
HDF: 42 of 42 caught
PWF: 23 of 23 caught
OSF: 26 of 27 caught
No mode recorded: 0 of 2 caught

(A failure can have more than one mode, so the counts add up to more than 102.) The model catches every heat dissipation and power failure and all but one overstrain failure, because those follow clear rules in the readings. Tool wear failures are much harder, 5 of 13: in this dataset the tool fails at a random point between 200 and 240 minutes of wear, so the readings can only say a failure is getting likely, not exactly when. Failures with no recorded cause weren’t caught at all. Some failures will always look random from the data available, which is why predictive maintenance reduces breakdowns rather than eliminating them.

8. Check what the model relies on

Permutation importance measures how much the PR AUC drops when one feature’s values are shuffled, which breaks its link with the outcome:

from sklearn.inspection import permutation_importance

r = permutation_importance(best, X_test, y_test, scoring="average_precision",
                           n_repeats=10, random_state=42)
imp = pd.Series(r.importances_mean, index=X_test.columns).sort_values(ascending=False)
print(imp.round(3).to_string())

Output:

temp_diff       0.386
rpm             0.383
strain          0.147
power           0.140
tool_wear       0.053
type            0.032
torque          0.012
air_temp        0.001
process_temp   -0.001

Temperature difference and rotational speed matter most, which fits the heat dissipation failures, the largest group. Strain and power come next. The raw air and process temperatures add almost nothing on their own once their difference is available. This kind of check is worth doing on every model: if the most important feature makes no engineering sense, it is often a sign of leakage or a data problem, and the people who maintain the machines are the best judges of that.

From a notebook to the factory floor

A model that works in a notebook is the start of a predictive maintenance project, not the end. The remaining work is usually bigger:

  • Real data is messier. Sensors drift and fail, time stamps from different systems don’t line up, and people record failures inconsistently. Expect data cleaning to take most of the time; see how to clean and preprocess data in Python.
  • Failures are rare per machine. A single machine may fail only a few times a year, so teams often train one model across many similar machines.
  • Time matters. Real sensor data is a time series. Useful features include trends and rolling averages over the last hours or days, and the test set should come from a later period than the training set; see time series analysis in Python.
  • Alerts need an owner. Every alert should lead to a clear action by a named team, and the team needs to trust the alerts. Too many false alarms and people stop responding.
  • Deployment. Models may run in the cloud, on a server in the plant or on a device next to the machine. To serve predictions through an API, see deploying a machine learning model with Flask.

Quality control and visual inspection

Quality is the second big area. Two approaches are common:

  • Predicting defects from process data: the same kind of classification as above, using temperatures, pressures, speeds and material properties to predict which batches will fail inspection, so problems can be fixed before more scrap is made.
  • Computer vision: cameras on the line and image models that spot scratches, cracks, missing parts or misalignment. These models are usually convolutional neural networks, trained on photos of good and defective parts.

Both share the challenge of the project above: defects are rare, so you have to judge the model on how many defects it finds and how many false rejects it makes, not on accuracy.

What does a manufacturing data scientist do?

Manufacturing data scientists work with process, maintenance and quality engineers. Typical projects include predictive maintenance, defect prediction, yield improvement, demand forecasting and energy analysis. The work needs the usual data science skills, SQL, pandas, statistics and machine learning, plus a willingness to learn how the machines and processes work, because the best features and the most useful sanity checks come from engineering knowledge. The data science career guide covers how to get started.

Project ideas for manufacturing data science

  • Extend this project: build a separate model for each failure mode, or compare the gradient boosting model with a random forest.
  • Semiconductor yield: the SECOM dataset has 1,567 production examples with 591 measured process signals and 104 failures, with many missing values. It is a good test of feature selection and handling messy data.
  • Fault classification: the Steel Plates Faults dataset has 1,941 steel plates with 27 features and seven fault types, such as scratches, stains and bumps.
  • Remaining useful life: NASA’s turbofan engine degradation data (C-MAPSS) contains simulated run-to-failure sensor histories, used to predict how many cycles an engine has left.
  • Visual inspection: train an image classifier on photos of good and defective parts, starting from the techniques in our CNN tutorial.

You can read the full description of the dataset on its UCI Machine Learning Repository page, and the scikit-learn user guide documents the gradient boosting model used above.

Related reading

FAQ

How is data science used in manufacturing?

To predict machine failures before they happen, find defective parts and batches, inspect products with cameras, tune processes for higher yield, forecast demand and plan production, manage inventory and reduce energy use. Predictive maintenance and quality control are usually the first projects.

What is predictive maintenance?

Predictive maintenance uses data from machines, such as temperatures, vibration, speed and run hours, to estimate when a machine is likely to fail, so the team can service it just before. It sits between reactive maintenance (fix it when it breaks) and preventive maintenance (service it on a fixed schedule).

What data is used in manufacturing data science?

Sensor readings from machines and control systems, production records from the manufacturing execution system (MES), orders and stock from the ERP system, maintenance logs, quality inspection results and, for visual inspection, camera images.

Which machine learning models work best for predictive maintenance?

For tabular sensor features, gradient boosting models are a strong default, as the project in this article shows. Teams use time series models and deep learning when there is long, detailed sensor history, and anomaly detection when there are very few recorded failures.

Why not use accuracy to evaluate a failure prediction model?

Because failures are rare. In this article’s data only 3.39% of records are failures, so a model that never predicts a failure would be 96.6% accurate and catch nothing. Precision, recall, PR AUC and the cost of missed failures and false alarms are better measures.

Is there a public dataset for predictive maintenance?

Yes. The AI4I 2020 Predictive Maintenance Dataset used here is a popular synthetic one. NASA’s turbofan engine degradation data is widely used for remaining-useful-life models, and SECOM is a real semiconductor manufacturing dataset for defect prediction.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights