Skip to content

The Data Scientist

Machine

Time-Series Classification with Machine Learning: From Raw Signals to Reliable Predictions

Time-series classification is a common machine learning task in which a model assigns a category to a sequence of observations collected over time. Applications include industrial fault detection, wearable sensor analysis, network monitoring, and equipment diagnostics. Unlike conventional tabular classification, time-series analysis must account for the order of observations and the temporal patterns that connect them.

A sphygmomanometer, or blood pressure monitor, provides a useful example of a sensor-based system. Automated devices can record pressure-related signals during a measurement cycle. Researchers can analyze these signals to investigate waveform quality, identify recording artifacts, or classify predefined signal patterns.

This article explains how to build a reproducible time-series classification workflow with Python. It focuses on data preparation, feature engineering, baseline models, leakage-resistant evaluation, and deployment considerations. The example illustrates a machine learning methodology; it does not establish that a model can independently diagnose a medical condition or produce clinically valid blood pressure estimates.

1. Define the Classification Problem

Before selecting an algorithm, define what the model should predict. A vague goal such as “analyze sensor data” is not sufficient to design a valid experiment.

A classification task needs three components:

For example, an industrial monitoring project might classify machine vibrations as normal or abnormal. A wearable-device project might identify activity types from accelerometer readings.

In a research project involving a sphygmomanometer, the target could be a predefined signal-quality category, provided that reliable labels and a documented labeling protocol are available. The task must not be confused with estimating systolic or diastolic blood pressure, which is a different modeling problem requiring suitable reference measurements and validation.

The target definition determines the entire workflow, including the data required, the model architecture, and the metrics used to assess performance.

2. Represent Sensor Readings as Time-Series Data

A time series consists of observations ordered by time. A simple sensor recording might contain a timestamp and a measured value:

Timestamp Sensor value
10:00:00.00 12.4
10:00:00.01 12.8
10:00:00.02 12.1
10:00:00.03 11.7

These illustrative values demonstrate the data structure; they are not measurements from a real blood pressure monitor.

Before training, verify that timestamps are ordered correctly, sampling intervals are understood, missing observations are identified, and corrupted recordings are handled consistently. If recordings come from multiple devices, store device identifiers and relevant acquisition metadata.

Many classification pipelines divide long recordings into windows. Each window becomes one example, with a corresponding label. Window duration should reflect the expected duration of the pattern being classified.

Overlapping windows can increase the number of training examples, but they also create a major evaluation risk: adjacent windows from the same recording may be highly similar. If related windows appear in both the training and test sets, reported performance can be overly optimistic.

3. Prepare the Dataset Before Training

Data preparation should follow a documented sequence.

First, remove records that violate predefined quality rules. Next, handle missing values and inconsistent sampling intervals. Apply filtering or resampling only when justified by the signal characteristics and the intended task.

Then split the data into training, validation, and test sets using a strategy appropriate to the deployment scenario.

For independent recordings, it may be appropriate to separate complete recordings or subjects. If the model must generalize to unseen devices, device-level separation may be necessary. If the objective is to predict future observations, use a chronological split.

The correct strategy depends on how the model will be used. Randomly splitting individual rows is not automatically valid for sequential data.

The scikit-learn documentation on common pitfalls explains why information from test data must not influence preprocessing or model selection.

4. Extract Features from Sensor Signals

A time-series model can operate on raw sequences or on features calculated from each window. Feature engineering is often a useful starting point because it makes the initial pipeline easier to inspect.

Common feature groups include:

Statistical features. Mean, standard deviation, minimum, maximum, range, and selected quantiles summarize the distribution of values in a window.

Temporal features. First differences, local slopes, peak intervals, and changes between consecutive measurements describe how a signal evolves.

Shape features. Peak prominence, rise time, waveform width, and relationships between neighboring peaks can help characterize signal morphology.

Frequency-domain features. Spectral energy and dominant frequencies may reveal periodic patterns when the sampling rate and signal characteristics support frequency analysis.

Feature selection must be performed without consulting the held-out test set. Otherwise, the test data indirectly influences the model, making evaluation less trustworthy.

It is also important to avoid features that encode the answer. A device identifier, collection-session label, or timestamp can become a shortcut if it correlates with the target for reasons unrelated to the intended pattern.

5. Build a Reproducible Python Baseline

A baseline establishes a reference point before more complex models are introduced. For window-level features, a random forest is one reasonable starting point. It can learn nonlinear relationships between features and provides a useful comparison for later experiments.

The following example assumes that a dataset has already been converted into a feature matrix named X and a label vector named y. Each row represents one independently labeled example. The splitting strategy must be adapted if rows share a recording, subject, or device.

import pandas as pd

from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import (
    accuracy_score,
    classification_report,
    confusion_matrix,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline

# X: numeric features, one row per labeled example
# y: target class for each example

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.20,
    random_state=42,
    stratify=y,
)

model = make_pipeline(
    SimpleImputer(strategy="median"),
    RandomForestClassifier(
        n_estimators=300,
        random_state=42,
        class_weight="balanced",
    ),
)

model.fit(X_train, y_train)
predictions = model.predict(X_test)

print("Accuracy:", accuracy_score(y_test, predictions))
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))

This code is a baseline template, not a complete medical-signal analysis system. It assumes that the examples can reasonably be split at the row level. If multiple windows come from the same source recording or subject, use a group-aware split instead.

The pipeline fits the imputation step on training data and applies the learned transformation to test data. This helps prevent a common form of preprocessing leakage.

The test set should not be used to choose the best model, tune parameters, or repeatedly modify features. Those decisions belong in the training and validation process. After model development is complete, the held-out test set provides a more independent estimate of generalization performance.

6. Choose an Evaluation Strategy That Matches the Data

Evaluation design can matter as much as algorithm choice. Time-series observations are often correlated with nearby observations, so ordinary random cross-validation can produce misleading results.

The scikit-learn TimeSeriesSplit documentation describes a chronological validation strategy in which training observations precede the corresponding test observations. This is useful when the objective is to predict future data from past data and the observations satisfy the method’s assumptions.

For grouped sensor recordings, use a group-aware strategy when the intended test is performance on previously unseen groups. For example, separating subjects or devices can reveal whether the model has learned patterns that generalize beyond the specific sources used in training.

The UCR Time Series Classification Archive paper is another useful reference. Dau and colleagues describe a widely used collection of benchmark datasets and discuss pitfalls in comparing time-series classification methods. Their work reinforces the importance of careful experimental design rather than relying on a single headline score.

A strong evaluation plan should specify the split strategy before the final experiment. It should also document the number of examples, the class distribution, and any exclusions applied to the data.

7. Look Beyond Accuracy

Accuracy is the proportion of predictions that match the reference labels. It can be informative, but it does not describe every type of model error.

If one class is much more common than another, a model can achieve high accuracy while performing poorly on the less frequent class.

Use a confusion matrix to inspect which classes are being confused. Precision measures how often predictions of a given class are correct, while recall measures how many examples belonging to that class are identified. The F1 score summarizes precision and recall in a single measure.

For imbalanced classification, macro-averaged precision, recall, and F1 can help prevent large classes from dominating the summary. The appropriate metric should still reflect the practical cost of errors in the intended application.

For medical or safety-related applications, classification metrics alone do not demonstrate clinical validity, regulatory compliance, or suitability for decision-making. Those claims require additional evidence and evaluation appropriate to the intended use.

8. Compare Models Without Creating a Benchmark Trap

Once the baseline is established, compare it with a small number of alternatives. Depending on the representation and dataset size, candidates might include logistic regression, support vector machines, gradient-boosted trees, or a one-dimensional convolutional neural network.

Keep the evaluation procedure consistent across models. Use the same data partitions, the same target definition, and comparable preprocessing. Tune hyperparameters on training and validation data rather than on the final test set.

Do not select an algorithm solely because it produces the highest score on one split. A small improvement may reflect random variation, a leakage problem, or a model that performs well only on a narrow subset of the data.

For a defensible comparison, report the chosen metrics, the split strategy, relevant model settings, and limitations. Where practical, evaluate variability across multiple valid folds or independent test groups.

The objective is not to find the most complicated model. It is to identify a method that provides useful and reproducible performance under the conditions in which it will be used.

9. Connect the Model to Software Engineering

A trained classifier is only one component of a production system. The surrounding software must validate inputs, handle failures, record versions, and make model behavior observable.

A practical deployment pipeline should include:

  • Input validation for missing values, invalid shapes, and unexpected sampling rates.
  • Version control for feature-generation code, configuration, and model artifacts.
  • Automated tests for preprocessing and prediction behavior.
  • Logging that supports debugging without exposing unnecessary sensitive data.
  • Monitoring for shifts in input distributions, prediction frequencies, and processing latency.
  • A documented process for investigating failures, reverting releases, and approving retraining.

Monitoring should distinguish between changes in the input data and changes in actual outcomes. A shift in sensor readings does not automatically mean the model is wrong, but it may indicate that the deployment environment has changed and further investigation is needed.

Retraining should be treated as a controlled engineering process. New data needs appropriate quality checks, labels, evaluation, and approval before a replacement model is deployed.

10. Apply the Workflow Carefully to Sphygmomanometer Signals

An automated sphygmomanometer illustrates how a physical measurement system can generate sequential data for computational analysis. During a measurement cycle, an oscillometric device records pressure-related signals that may be studied for signal-quality classification or other clearly defined research tasks.

A responsible workflow begins with a documented acquisition protocol and reliable reference labels. It then checks recording quality, creates suitable windows, calculates or learns features, trains a baseline model, and evaluates performance on appropriately separated recordings.

The limitations of the dataset must remain visible throughout the project. A model trained on one device or one population may not generalize to another. Signal-quality classification must not be presented as blood pressure estimation, and a model’s predictions should not be described as a clinical diagnosis unless the relevant evidence supports that claim.

This example is useful because it connects sensor data, machine learning, statistical evaluation, and production engineering in one practical workflow. The same principles apply to vibration monitoring, wearable devices, industrial telemetry, and other time-dependent measurements.

Conclusion

Reliable time-series classification depends on a complete machine learning workflow rather than an algorithm alone. Clear target definitions, careful preprocessing, appropriate feature engineering, leakage-resistant data splits, and relevant evaluation metrics all contribute to trustworthy results.

Python tools such as scikit-learn make it possible to construct reproducible baselines and integrate preprocessing with model training. Research resources such as the UCR Time Series Classification Archive provide useful context for evaluating methods and avoiding misleading comparisons.

A sphygmomanometer is one example of a sensor system whose signals can be studied with these techniques. The essential lesson is broader: a model is useful only when its evaluation reflects the data, the intended deployment, and the limitations of the evidence.

References

  1. scikit-learn developers. “Common pitfalls and recommended practices.” https://scikit-learn.org/stable/common_pitfalls.html
  2. scikit-learn developers. “TimeSeriesSplit.” https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html
  3. Dau, H. A., et al. “The UCR Time Series Archive.” IEEE/CAA Journal of Automatica Sinica, 2019, 6(6), 1293–1305. https://doi.org/10.1109/JAS.2019.1911747

Media Publishing • The Data Scientist

Sponsored Editorial Publishing & Tech Media Placement

Get your technical product or case study published on The Data Scientist with domain authority backlinks.