Zero Labs
Industry News / AI

Time Series Analysis and Forecasting — Part 3: Forecasting Models, Evaluation, and Practical Cases

Source · Towards AI By Michalzarnecki

From the publisher’s feed, collected in the ZeroLabs newsroom.

Hi. This is the third and final part of the series on time series analysis and forecasting. In Part 1 we covered the fundamentals and walked through a Freezing-of-Gait classifier on real Parkinson's sensor data. In Part 2 we went deep on data preparation with Pandas — dates and time zones, up/downsampling, missing values, smoothing, autocorrelation, and stationarity.In this part we get to the modeling itself. I'll cover:A short review of e-commerce revenue forecasting — a real-world framing of the problemThe main families of forecasting models — ARIMA, SARIMA, ETS, Prophet, NPTS, TransformerA code walkthrough of ARIMA and Time Series Transformer on a simulated seriesEvaluation metrics — MAE, RMSE, MAPE, WAPE, MASE, Column ImpactProbabilistic forecasting and weighted quantile lossAn LSTM walkthrough on Google stock pricesA siren classification walkthrough using FFT featuresA final wrap-upCode repository: https://github.com/mzarnecki/time-series-analysisLet's dive in.A real-world framing: forecasting daily revenue for an online storeBefore we get into algorithms, let's anchor things in a concrete business problem. Imagine we want to predict daily revenue for an online shop, using data from the same calendar period last year.I'm using "corresponding period" deliberately, because days of the week — and especially weekends — don't line up across years. Holidays are the same: Easter isn't fixed to a date, promotions move. So the "same day last year" isn't as straightforward as it looks.The input to the model belongs to three categories — exactly the three data layers we introduced in Part 1:Time series data — daily revenue.Related signals — price changes, promotions, campaign flags.Metadata — date ranges, location, currency.We train the model on historical periods where we know both the features and the true revenue. Then we feed it a date range in the future, and it produces predicted revenue for each day.Later, when real revenue data comes in, we check how well the forecast held up. This is where model drift shows up — the model was good at predicting under the historical trend, but changing conditions may have made it less accurate. Detecting drift early is important, because a forecast that was fine three months ago may already be misleading today.In a real project of this type I've worked on, we plotted actual revenue in blue against the forecast in orange. The model generally captured the direction — when real revenue fell, the forecast fell too — but the magnitude of the forecast sometimes deviated noticeably from reality. This is the typical behaviour: direction is often recoverable, but absolute levels in a volatile domain are hard.With that context in mind, let's look at the modelling options.A tour of forecasting modelsBelow is a short list of the approaches I reach for most often. In practice, the choice depends on the shape of your data — whether trend dominates, whether seasonality is strong, whether short-term dependencies matter — and how stable the series is over time.ARIMAARIMA stands for AutoRegressive Integrated Moving Average. It's a classical statistical model describing the current value as a function of past values (autoregressive part) and a random noise term (moving average part). The "integrated" piece refers to differencing — transforming the series to make it more stationary before fitting.ARIMA works well on data with clear autocorrelation and moderately stable dynamics.SARIMASARIMA extends ARIMA with a seasonal component. If your data has a repeating weekly, monthly, or yearly pattern on top of short-term dependencies, SARIMA captures both. It also keeps ARIMA's interpretability.ETS — Exponential SmoothingETS (Error, Trend, Seasonality) is a family of methods that build the forecast by taking a weighted average of past observations, with more weight on recent ones. It's widely used in business forecasting, especially when trend and seasonality matter and you want a simple, stable model that's easy to explain.NPTS — Nonparametric Time SeriesNPTS is a family of nonparametric approaches — they don't assume a specific parametric form for the model. Instead they rely on similarity between fragments of the series, or on flexible fitting procedures. Useful when the data has non-standard structure and classical parametric models don't describe it well.ProphetProphet is a library by Facebook (now Meta) designed for practical business forecasting. It models trend and seasonality in a way that tends to work well out-of-the-box on business data, with easy integration of holidays and calendar events. It's often a good starting point when you want a sensible forecast quickly and need simple control over the model components.Time Series Transformerhttps://huggingface.co/docs/transformers/model_doc/time_series_transformerWhen dependencies in the data are more complex, or you want to use additional features beyond the signal itself, neural-network approaches become attractive. A Time Series Transformer takes a context window of past observations (e.g., the last 48) and produces a forecast for a prediction horizon (e.g., the next 24) using an encoder–decoder architecture similar to language-model transformers.The inputs don't have to be just the series values. You can feed in lags, time-based features (day of week, month, time of day), and additional covariates. The upside is the model's ability to learn non-linear, long-range dependencies. The downside is higher compute cost and reduced interpretability compared to ARIMA or ETS.Code walkthrough: ARIMA and Time Series TransformerTime to run some code. The notebook for this section is time_series_arima_transformer.ipynb. We'll generate a small synthetic series with a linear trend, a sinusoidal component, and noise — and then try to forecast it with both ARIMA and a transformer.ARIMAimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.arima.model import ARIMAnp.random.seed(42)time_steps = 200t = np.arange(time_steps)series = 0.05 * t + np.sin(0.2 * t) + 0.2 * np.random.randn(time_steps)train_size = 170train, test = series[:train_size], series[train_size:]# ARIMA order=(p, d, q):# p=2: AR terms (uses the last 2 lagged values)# d=1: 1st differencing (models changes to reduce trend / non-stationarity)# q=2: MA terms (uses the last 2 lagged forecast errors to absorb residual autocorrelation)model = ARIMA(train, order=(2, 1, 2))model_fit = model.fit()forecast = model_fit.forecast(steps=len(test))plt.figure(figsize=(12, 5))plt.plot(t[:train_size], train, label="train")plt.plot(t[train_size:], test, label="real")plt.plot(t[train_size:], forecast, label="ARIMA forecast", linestyle="--")plt.legend()plt.title("ARIMA forecast example")plt.show()Worth calling out the order=(p, d, q) tuple. p=2 means the model uses the last 2 lagged values as autoregressive terms, d=1 means we take first differences (so the model really operates on changes between consecutive values, which removes trend), and q=2 means it uses the last 2 forecast-error terms. For a trending, sinusoidal series, (2, 1, 2) is a reasonable starting point, though in production you'd typically grid-search or use auto_arima.Time Series TransformerNow the same forecasting problem with a Hugging Face TimeSeriesTransformerForPrediction model.First, set up the data and config:import numpy as npimport torchimport matplotlib.pyplot as pltfrom torch.utils.data import DataLoader, TensorDatasetfrom transformers import (TimeSeriesTransformerConfig, TimeSeriesTransformerForPrediction)# 1. Generate example datatime_steps = 200t = np.arange(time_steps)series = 0.05 * t + np.sin(0.2 * t) + 0.2 * np.random.randn(time_steps)data = torch.tensor(series, dtype=torch.float32)# 2. Normalize for trainingmean = data.mean()std = data.std()data_norm = (data - mean) / std# 3. Configcontext_length = 48prediction_length = 24lags = [1, 2, 3, 4, 5, 6, 7]max_lag = max(lags)past_length = context_length + max_lagconfig = TimeSeriesTransformerConfig( prediction_length=prediction_length, context_length=context_length, lags_sequence=lags, num_time_features=1, num_dynamic_real_features=0, num_static_real_features=0, num_static_categorical_features=0, scaling="none", # we already normalized manually)model = TimeSeriesTransformerForPrediction(config)Two things worth noting in the config:context_length = 48 and prediction_length = 24 — the model looks at 48 past points and predicts 24 forward.lags_sequence = [1..7] — on top of the raw context window, the model can also use values at lags 1 through 7. The effective past window the transformer needs is therefore context_length + max_lag.Next, build sliding windows from the normalized series:past_windows, future_windows = [], []past_tf_windows, future_tf_windows = [], []for start in range(0, len(data_norm) - past_length - prediction_length + 1): past = data_norm[start:start + past_length] future = data_norm[start + past_length:start + past_length + prediction_length] past_windows.append(past) future_windows.append(future) past_tf_windows.append(torch.arange(start, start + past_length, dtype=torch.float32)) future_tf_windows.append(torch.arange(start + past_length, start + past_length + prediction_length, dtype=torch.float32))past_values = torch.stack(past_windows).unsqueeze(-1)future_values = torch.stack(future_windows).unsqueeze(-1)past_time_features = torch.stack(past_tf_windows).unsqueeze(-1)future_time_features = torch.stack(future_tf_windows).unsqueeze(-1)past_observed_mask = torch.ones_like(past_values)future_observed_mask = torch.ones_like(future_values)dataset = TensorDataset( past_values, past_time_features, past_observed_mask, future_values, future_time_features, future_observed_mask,)loader = DataLoader(dataset, batch_size=8, shuffle=True)Training loop:optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)model.train()for epoch in range(10): total_loss = 0.0 for batch in loader: pv, ptf, pom, fv, ftf, fom = batch optimizer.zero_grad() outputs = model( past_values=pv.squeeze(-1), past_time_features=ptf, past_observed_mask=pom.squeeze(-1), future_values=fv.squeeze(-1), future_time_features=ftf, future_observed_mask=fom.squeeze(-1), ) loss = outputs.loss loss.backward() optimizer.step() total_loss += loss.item() print(f"Epoch {epoch + 1}: loss={total_loss / len(loader):.4f}")And finally forecast from the last available window:model.eval()with torch.no_grad(): last_past_values = data_norm[-past_length:].unsqueeze(0) last_past_time_features = torch.arange( len(data_norm) - past_length, len(data_norm), dtype=torch.float32, ).view(1, past_length, 1) last_past_observed_mask = torch.ones_like(last_past_values) future_time_features = torch.arange( len(data_norm), len(data_norm) + prediction_length, dtype=torch.float32, ).view(1, prediction_length, 1) forecast = model.generate( past_values=last_past_values, past_time_features=last_past_time_features, past_observed_mask=last_past_observed_mask, future_time_features=future_time_features, ) pred_norm = forecast.sequences.mean(dim=1).squeeze(0) pred = pred_norm * std + meanHonest note on the resultThe transformer's output here isn't "ideal", and that's on purpose. This is a deliberately minimal demo on a very small synthetic sample. The model trained for only a few epochs on a limited number of windows, and we used minimal time features (basically just the index) and simple generation settings.In this configuration the model typically picks up the overall level and trend but has a harder time reproducing the exact amplitude and phase of the oscillations. The plot is meant to illustrate the context → horizon principle, not the maximum achievable prediction quality. Give a transformer more data, richer time features, and proper training, and the picture changes substantially.Evaluating forecasts: the metrics that actually matterOnce you have a model producing forecasts, the next question is: how do we know it's any good?For time series, it's rarely enough to say "the model predicted something". What we care about is how far off the predictions are from reality, and whether that error is acceptable in the business context.MAE — Mean Absolute ErrorMAE is the average of absolute errors: mean(|forecast − actual|). Very intuitive — it tells you the typical error in the same units as the data.RMSE — Root Mean Squared ErrorRMSE is the square root of the mean of squared errors. The squaring step makes RMSE more sensitive to large mistakes than MAE. If big outliers hurt you more than small ones, RMSE is the metric to watch.In practice I treat MAE and RMSE as two complementary views: MAE describes "typical error", RMSE highlights "large mistakes".ExampleSay the model predicted sales of 545, 560, 548, 552 on four days, and actuals were 550, 555, 540, 560. The errors and squared errors are:ForecastActual|error|error²545550525560555525548540864552560864MAE is the mean of the |error| column: (5 + 5 + 8 + 8) / 4 = 6.5If actuals are in the range of hundreds of thousands (e.g. 550,000), a MAE of ~6–9 (thousand) represents roughly a 2% error, which in many contexts is acceptable.RMSE is the square root of the mean of error²: sqrt((25 + 25 + 64 + 64) / 4) = sqrt(44.5) ≈ 6.67The RMSE value is close to but slightly above MAE — it would diverge more from MAE if a single error were much larger than the others.MAPE — Mean Absolute Percentage ErrorMAPE expresses the average error as a percentage of the actual value. If MAPE = 8%, on average the model is off by about 8%.The appeal of MAPE is that the result is easy to communicate to non-technical stakeholders. The catch: MAPE breaks down when actual values are zero or very small (division by something tiny blows up the metric).WAPE — Weighted Absolute Percentage ErrorWAPE divides the total absolute error by the total actual value — rather than averaging per-point percentages. This makes it much more stable than MAPE when there are big fluctuations or occasional small values.WAPE tells you how large the total forecast error is relative to the total volume of sales (or demand). It's a favourite in operational and business contexts.MASE — Mean Absolute Scaled ErrorMASE compares your model's error to the error of a naive baseline — typically a model that predicts "tomorrow = today". This is a very useful sanity check:If MASE If MASE > 1 → your model is actually worse than doing nothing clever.MASE is also normalized by the scale of the series, which makes it especially useful for comparing models across different time series (e.g. across products, regions, customers).Column ImpactColumn Impact is a different kind of metric. It doesn't measure prediction error directly — it measures how much each input feature contributes to the prediction. For a sales-forecast model, it answers "what mattered more — the promotion flag, day of week, website traffic, or marketing spend?"This is about interpretability. If all you need is raw accuracy, Column Impact isn't directly relevant. But if you have to explain or defend the model to the business, it's essential.Which metric to use?In practice I look at several at the same time. MAPE is intuitive. WAPE is more stable at the portfolio level. MASE tells you whether the model is actually worth deploying. Column Impact helps explain it. Watching all of them together gives a much clearer picture than any single number.Probabilistic forecastingSo far we've been discussing single-value forecasts — "revenue tomorrow will be 1000". A richer alternative is to produce multiple quantiles — effectively a distribution of possible futures.A typical setup predicts P10, P50, P90:P10 — the 10th percentile, a cautious lower boundP50 — the median, the "typical" predictionP90 — the 90th percentile, a more optimistic upper boundOn a chart the three curves form a band of uncertainty. A wide band means the future is hard to predict; a narrow band means the model is confident.Weighted Quantile Loss (wQL)Evaluating a probabilistic forecast needs a different metric than a point forecast. Weighted Quantile Loss (wQL) computes a loss separately for each predicted quantile and averages them. Critically, the loss is asymmetric — overestimation and underestimation are penalized differently depending on which quantile you're evaluating. This ensures the predicted quantiles really behave as quantiles: the 10th percentile should be exceeded about 90% of the time, the 50th about 50%, etc.In practice, wQL is useful when you care not only about hitting a single number, but about providing a reasonable range for downstream planning — inventory safety stock, capacity planning, risk management.Case study: LSTM forecast for Google stock priceTime for the next full walkthrough. Notebook: prognose_google_stock_price.ipynb. We'll build an LSTM-based forecaster for Google stock prices and evaluate it with MAE and RMSE.The workflowLoad the dataInspect itPrepare featuresBuild the networkTrainEvaluateMarket volatility and external events: a WIG20 exampleBefore jumping into code, I like to show a reminder that forecasts can be broken by external events. In the notebook I plot WIG20 values around October–November 2020, with annotations at the dates of Polish COVID restrictions (yellow zone on 07.10.2020, full red zone on 27.10.2020):# (abbreviated)chart, axis = plt.subplots(figsize=(14, 7))wig20_frame["WIG20"].plot(ax=axis, style="r-", linewidth=4)axis.annotate("Start of first drop", xy=(4, 1719 + 30), xytext=(4, 1719 + 150), arrowprops=dict(facecolor='black', headwidth=8, width=2))axis.annotate("Start of second drop", xy=(18, 1610 + 30), xytext=(18, 1610 + 150), arrowprops=dict(facecolor='black', headwidth=8, width=2))Both drops start close to actual policy announcements. This is the same phenomenon as the Musk/Bitcoin example in Part 1 — a forecast built on historical prices has no way to anticipate a regulatory change.Loading and inspecting the dataimport pandas as pdimport numpy as npfrom sklearn import metricsfrom sklearn.preprocessing import MinMaxScalerfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, LSTMimport matplotlib.pyplot as pltstock_frame = pd.read_csv("../data/google.csv")stock_frame.describe()stock_frame.info()stock_frame.head()Nothing fancy — just get a feel for the shape of the data.Feature scalingNeural networks train much more smoothly when inputs are scaled. For a single column like the closing price, MinMaxScaler to the [0, 1] range is a clean choice:close_values = stock_frame.iloc[:, 3:4].valuesvalue_scaler = MinMaxScaler(feature_range=(0, 1))scaled_close_values = value_scaler.fit_transform(close_values)Building training and test sequencesThis is the "window" logic we discussed in Part 1 used in practice:train_sequences, train_targets = [], []lookback_window = 70for row_idx in range(lookback_window, 3500): train_sequences.append( scaled_close_values[row_idx - lookback_window:row_idx, 0] ) train_targets.append(scaled_close_values[row_idx, 0])train_sequences = np.array(train_sequences)train_targets = np.array(train_targets)test_sequences, test_targets = [], []for row_idx in range(3501, 4300): test_sequences.append( scaled_close_values[row_idx - lookback_window:row_idx, 0] ) test_targets.append(scaled_close_values[row_idx, 0])test_sequences = np.array(test_sequences)test_targets = np.array(test_targets)# reshape for LSTM: (samples, timesteps, features)train_sequences = np.reshape( train_sequences, (train_sequences.shape[0], train_sequences.shape[1], 1),)test_sequences = np.reshape( test_sequences, (test_sequences.shape[0], test_sequences.shape[1], 1),)Each training example is a 70-day window. The target is the 71st day. That's literally the "context → horizon" setup from Part 1 — just implemented with NumPy instead of a library helper.The LSTM networkFour stacked LSTM layers with dropout, plus a single-unit dense output:price_forecaster = Sequential()price_forecaster.add(LSTM(units=50, return_sequences=True))price_forecaster.add(Dropout(0.2))price_forecaster.add(LSTM(units=50, return_sequences=True))price_forecaster.add(Dropout(0.2))price_forecaster.add(LSTM(units=50, return_sequences=True))price_forecaster.add(Dropout(0.2))price_forecaster.add(LSTM(units=50))price_forecaster.add(Dropout(0.2))price_forecaster.add(Dense(units=1))price_forecaster.compile(optimizer="adam", loss="mean_squared_error")Training and predictionprice_forecaster.fit(train_sequences, train_targets, epochs=10, batch_size=32)forecast_scaled = price_forecaster.predict(test_sequences)forecast_values = value_scaler.inverse_transform(forecast_scaled)observed_values = value_scaler.inverse_transform(test_targets.reshape(-1, 1))Note the inverse_transform calls — we need to convert predictions and targets back from the [0, 1] scale to actual dollar values for interpretation and error metrics.Plotting actual vs. predictedplt.plot(observed_values, color="orange", label="observed price")plt.plot(forecast_values, color="green", label="forecast price")plt.title("Google stock price forecast")plt.xlabel("time")plt.ylabel("stock price")plt.legend()plt.show()Evaluationprint(f'RMSE {metrics.root_mean_squared_error(forecast_values, observed_values)}')print(f'MAE {metrics.mean_absolute_error(forecast_values, observed_values)}')Two lines, two numbers — and now you can argue about whether the model is actually useful. In real practice, I’d also compare these errors to a naive baseline (tomorrow’s price = today’s price), because a sophisticated model that barely beats naive isn’t doing much work.Case study: Siren classification with FFT featuresLast full walkthrough. Notebook: siren_sound_analyse_and_classify.ipynb.This is a good example of a time series that doesn’t look like a time series at first glance. The input is audio — a sound signal sampled many thousand times per second — but once you remember that audio is a high-frequency time series, everything from Part 1 applies.The task is to classify a recording into one of three categories: ambulance, fire truck, or street traffic.The key idea: FFT as feature extractorInstead of pushing raw amplitude samples into a classifier, we transform each clip into its frequency-domain representation with FFT. Different sirens occupy characteristic frequency bands, so in the frequency domain the classes become much easier to separate.Imports and visualization helpersimport glob, warnings, wavefrom os import pathimport matplotlib.pyplot as pltimport pandas as pdimport pylabfrom scipy.fftpack import fftfrom scipy.io import wavfile as wavfrom sklearn import ensemble, linear_model, metrics, svmfrom sklearn.model_selection import train_test_splitfrom tqdm.auto import tqdmwarnings.filterwarnings('ignore')def plot_wave(audio_path: str): signal_values, _ = read_wav_metadata(audio_path) plt.figure(num=1, figsize=(15, 5)) plt.title(f"Signal waveform: {audio_path}") plt.xlabel('time'); plt.ylabel('amplitude') plt.plot(signal_values) plt.show()def plot_fft(audio_path: str): fft_values = build_fft_vector(audio_path) fft_size = len(fft_values) plt.figure(figsize=(15, 5)) plt.ylim(0, 50000) plt.title(f"FFT: {audio_path}") plt.xlabel('frequency'); plt.ylabel('amplitude') plt.plot(abs(fft_values[: int(fft_size) - 1]), 'r') plt.show()def plot_spectrogram(audio_path: str): signal_values, sample_rate = read_wav_metadata(audio_path) pylab.figure(figsize=(15, 5)) pylab.subplot(111) pylab.axis('off') pylab.title(f"Spectrogram: {audio_path}") pylab.specgram(signal_values, Fs=sample_rate)def read_wav_metadata(audio_path: str) -> tuple: wav_handle = wave.open(audio_path, 'r') frame_buffer = wav_handle.readframes(-1) signal_values = pylab.fromstring(frame_buffer, 'int16') sample_rate = wav_handle.getframerate() wav_handle.close() return signal_values, sample_rateThe three plot functions give you three different views of the same clip: waveform (amplitude vs. time), FFT (magnitude per frequency), and spectrogram (frequency vs. time, with intensity as colour). They’re complementary — the spectrogram is the most informative, but the FFT vector is what actually becomes the feature vector.The FFT feature vectordef build_fft_vector(audio_path: str) -> list: _, raw_audio = wav.read(audio_path) left_channel = raw_audio.T[0] normalized_signal = [(sample / 2**8.0) * 2 - 1 for sample in left_channel] fft_result = fft(normalized_signal) half_length = len(fft_result) / 2 return abs(fft_result[: int(half_length) - 1])A few things happen here: we load the raw audio, take one channel (mono), normalize to roughly [-1, 1], compute the FFT, and return the magnitudes for the first half of the output (the second half is the mirror of the first for a real input). The result is a fixed-length vector representing how much energy the clip has at each frequency bin — exactly the kind of input a classical ML model is happy to consume.Visual sanity checksBefore training we plot a couple of examples to make sure the signals look like what we expect:plot_wave('../data/sounds/ambulance/sound_102.wav')plot_fft('../data/sounds/ambulance/sound_102.wav')plot_spectrogram('../data/sounds/ambulance/sound_102.wav')plot_wave('../data/sounds/firetruck/sound_203.wav')plot_fft('../data/sounds/firetruck/sound_203.wav')plot_spectrogram('../data/sounds/firetruck/sound_203.wav')plot_wave('../data/sounds/traffic/sound_404.wav')plot_fft('../data/sounds/traffic/sound_404.wav')plot_spectrogram('../data/sounds/traffic/sound_404.wav')The ambulance and fire-truck sirens have clear peaks at their characteristic frequencies; traffic has energy spread more broadly. This is the visual confirmation that the FFT representation is a reasonable feature space for this problem.Building the datasetfeature_rows, class_labels = [], []class_map = { 'ambulance': 1, 'firetruck': 2, 'traffic': 3,}def collect_example(file_path): try: path_parts = file_path.split('/') # take every 3rd FFT bin up to 50000 - keeps features compact feature_rows.append(build_fft_vector(file_path)[:50000:3]) class_labels.append(class_map[path_parts[3]]) except Exception: passaudio_files = glob.glob(path.join('', '../data/sounds/**/**'))_ = [collect_example(f) for f in tqdm(audio_files)]We subsample the FFT output with [:50000:3] so the feature vector stays at a reasonable length — full-resolution FFT vectors would be enormous and mostly empty.Train/test split and the training helpertrain_features, test_features, train_labels, test_labels = train_test_split( feature_rows, class_labels, test_size=0.2, random_state=12345,)def fit_and_score(model, train_vectors, target_values, valid_vectors): model.fit(train_vectors, target_values) predicted_labels = model.predict(valid_vectors)metric_values = list( metrics.precision_recall_fscore_support(predicted_labels, test_labels) ) summary_scores = [ metric_values[0][0], metric_values[1][0], metric_values[2][0], ] summary_scores.append(metrics.accuracy_score(predicted_labels, test_labels)) return model, summary_scoresFour classifiersWe then fit logistic regression, an SVM, a random forest, and a small MLP, and collect their precision/recall/F1/accuracy:from sklearn.neural_network import MLPClassifierresults_by_model = {}_, results_by_model['LR'] = fit_and_score( linear_model.LogisticRegression(), train_features, train_labels, test_features)_, results_by_model['SVM'] = fit_and_score( svm.SVC(), train_features, train_labels, test_features)best_model, results_by_model['RF'] = fit_and_score( ensemble.RandomForestClassifier(), train_features, train_labels, test_features)best_model, results_by_model['neural network'] = fit_and_score( MLPClassifier(hidden_layer_sizes=(10, 10, 10), max_iter=1000), train_features, train_labels, test_features)comparison_frame = pd.DataFrame( results_by_model, index=['precision', 'recall', 'f1 score', 'accuracy'],)comparison_frame.plot(kind='bar')A quick prediction testambulance_fft = build_fft_vector('../data/sounds/ambulance/sound_102.wav')[:50000:3]firetruck_fft = build_fft_vector('../data/sounds/firetruck/sound_203.wav')[:50000:3]traffic_fft = build_fft_vector('../data/sounds/traffic/sound_404.wav')[:50000:3]best_model.predict([ambulance_fft, firetruck_fft, traffic_fft])If the model learned the task, this line should return [1, 2, 3].array([3, 3, 3])Why this example mattersThe siren case study shows that the technique — window the signal, compute features in a friendlier domain, run a classical ML model on those features — generalizes surprisingly well across different physical signals. The same template works for:Audio → FFT → classifier (sirens, wake-word detection, machine sound monitoring)Accelerometer → statistical window features → classifier (Parkinson’s FoG, activity recognition, industrial vibration monitoring)Time-varying business metrics → lags + calendar features → regressor (sales, energy demand)Different raw inputs, same playbook.Wrap-upTime to tie everything together.We started from first principles: what a time series actually is, and why it needs three layers of data to be useful — the measurements themselves, metadata about the source, and events that give context and typically serve as labels for supervised learning.We then walked through the typical preparation pipeline: interpreting dates and time zones, unifying frequency via down- and upsampling, smoothing (carefully — not losing the phenomena you care about), and checking autocorrelation and stationarity. Those last two tell you directly whether past values contain information about future ones, and whether the generating mechanism is stable enough for classical models to apply.On top of that foundation we looked at the main families of forecasting models — classical statistical ones like ARIMA, SARIMA, and ETS; practical defaults like Prophet; and modern neural-network approaches like the Time Series Transformer. The honest takeaway: there is no single “best” model. The right choice depends on the shape of the data, available history, seasonality, interpretability requirements, and whether you need a point forecast or a probabilistic one.We also covered evaluation — MAE and RMSE for absolute error, MAPE and WAPE for percentage errors, MASE for comparison against a naive baseline, Column Impact for interpretability. And we went one level deeper into probabilistic forecasting — quantile predictions and weighted quantile loss — which is the right framing when you care about risk and uncertainty, not just a single best-guess number.Along the way we walked through three complete notebooks: Parkinson’s Freezing of Gait detection from wearable sensors, Google stock price forecasting with an LSTM, and siren classification with FFT features + classical ML. Different domains, different model choices, same fundamentals.One last principleIn forecasting, the quality of the result starts with the quality of the data and a correctly defined problem. Only then does it make sense to think about which model and which metrics to use. Getting the problem framing right and the preprocessing clean is usually a bigger lever than swapping out the model for a fancier one.Repository and notebooksAll three case-study notebooks — plus the Pandas exploration and the ARIMA/Transformer demo — are in the repository:https://github.com/mzarnecki/time-series-analysisThanks for reading. The best way to make this material stick is to clone the repository and run the notebooks yourself — change the windows, try different models, break things, and see what changes. That’s where intuition comes from.Time Series Analysis and Forecasting — Part 3: Forecasting Models, Evaluation, and Practical Cases was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.