diff --git a/docs/Tutorial_Motif_Feature_Encoding.ipynb b/docs/Tutorial_Motif_Feature_Encoding.ipynb new file mode 100644 index 000000000..daf2f8ef6 --- /dev/null +++ b/docs/Tutorial_Motif_Feature_Encoding.ipynb @@ -0,0 +1,184 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Binary Motif Features for Time-Series Classification\n", + "\n", + "This tutorial turns class-discriminative subsequences into binary features. It uses the GunPoint dataset and the matrix-profile approach from the [Shapelet Discovery tutorial](Tutorial_Shapelet_Discovery.ipynb). Each candidate pattern becomes one feature: a value of `1` means a close match occurs somewhere in that sample. A sample can contain several patterns, so its feature vector is multi-hot.\n", + "\n", + "Pattern discovery and distance thresholds use only the training split. The test split is used only for the final evaluation. The candidates below are shapelet-like motif prototypes; the same encoding can be applied to motifs discovered by another method." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import stumpy\n", + "from sklearn import metrics, tree" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Load the labeled series\n", + "\n", + "Each row is one time series. The first column contains the class (`0` for `Gun`, `1` for `Point`)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "train_url = \"https://zenodo.org/record/4281349/files/gun_point_train_data.csv?download=1\"\n", + "test_url = \"https://zenodo.org/record/4281349/files/gun_point_test_data.csv?download=1\"\n", + "train_df = pd.read_csv(train_url)\n", + "test_df = pd.read_csv(test_url)\n", + "\n", + "y_train = train_df.iloc[:, 0].to_numpy()\n", + "y_test = test_df.iloc[:, 0].to_numpy()\n", + "X_train = train_df.iloc[:, 1:].to_numpy(dtype=float)\n", + "X_test = test_df.iloc[:, 1:].to_numpy(dtype=float)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Find candidate patterns from the training classes\n", + "\n", + "Concatenating samples with a `NaN` separator lets a matrix profile compare subsequences from different samples without creating matches across sample boundaries. The profile contrast favors patterns that are conserved within one class and less similar to the other class. We select non-overlapping high-contrast candidates from each class." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def concatenate_samples(samples):\n", + " return np.concatenate([np.r_[sample, np.nan] for sample in samples])\n", + "\n", + "\n", + "def discover_candidates(source, other, m, k=5):\n", + " P_self = stumpy.stump(source, m)[:, 0].astype(float)\n", + " P_other = stumpy.stump(source, m, other, ignore_trivial=False)[:, 0].astype(float)\n", + " contrast = P_other - P_self\n", + " contrast[~np.isfinite(contrast)] = -np.inf\n", + "\n", + " selected = []\n", + " for idx in np.argsort(contrast)[::-1]:\n", + " if not np.isfinite(contrast[idx]):\n", + " break\n", + " if all(abs(idx - previous) >= m for previous in selected):\n", + " selected.append(int(idx))\n", + " if len(selected) == k:\n", + " break\n", + "\n", + " return [source[idx : idx + m].copy() for idx in selected]\n", + "\n", + "\n", + "m = 38\n", + "gun_series = concatenate_samples(X_train[y_train == 0])\n", + "point_series = concatenate_samples(X_train[y_train == 1])\n", + "\n", + "motifs = []\n", + "motif_classes = []\n", + "for label, source, other in [(0, gun_series, point_series), (1, point_series, gun_series)]:\n", + " candidates = discover_candidates(source, other, m)\n", + " motifs.extend(candidates)\n", + " motif_classes.extend([label] * len(candidates))\n", + "\n", + "print(f\"Discovered {len(motifs)} candidate patterns\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Convert motif distances to binary features\n", + "\n", + "For each candidate, compute its minimum MASS distance to every sample. We set that candidate's presence threshold to the 95th percentile of distances among training samples from the class where the candidate was discovered. The rule is then fixed and applied to both splits. Thresholds tuned this way avoid using test samples to define what counts as a match." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def motif_distances(samples, motifs):\n", + " distances = np.empty((len(samples), len(motifs)))\n", + " for j, motif in enumerate(motifs):\n", + " for i, sample in enumerate(samples):\n", + " distances[i, j] = stumpy.mass(motif, sample).min()\n", + " return distances\n", + "\n", + "\n", + "D_train = motif_distances(X_train, motifs)\n", + "D_test = motif_distances(X_test, motifs)\n", + "motif_classes = np.asarray(motif_classes)\n", + "same_class = y_train[:, None] == motif_classes[None, :]\n", + "thresholds = np.array([\n", + " np.percentile(D_train[same_class[:, j], j], 95)\n", + " for j in range(len(motifs))\n", + "])\n", + "\n", + "X_train_features = (D_train <= thresholds[None, :]).astype(np.uint8)\n", + "X_test_features = (D_test <= thresholds[None, :]).astype(np.uint8)\n", + "print(\"Feature matrix shape:\", X_train_features.shape)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Train and evaluate a classifier\n", + "\n", + "The decision tree receives one binary column per candidate pattern. Its predictions are evaluated once on the held-out test samples. Different data may need a different motif length, number of candidates, or threshold; choose these using training data or cross-validation." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "clf = tree.DecisionTreeClassifier(max_depth=3, random_state=0)\n", + "clf.fit(X_train_features, y_train)\n", + "y_pred = clf.predict(X_test_features)\n", + "print(f\"Test accuracy = {metrics.accuracy_score(y_test, y_pred):.3f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Summary\n", + "\n", + "Matrix-profile contrasts can provide candidate class-associated patterns. Measuring their minimum distance in each sample and applying training-derived thresholds produces one-hot or multi-hot features that can be passed to standard supervised models." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/tutorials.rst b/docs/tutorials.rst index 9f9e2ce83..946d45c88 100644 --- a/docs/tutorials.rst +++ b/docs/tutorials.rst @@ -27,3 +27,4 @@ Tutorials Tutorial_Multidimensional_Motif_Discovery.ipynb Tutorial_Annotation_Vectors.ipynb Tutorial_Shapelet_Discovery.ipynb + Tutorial_Motif_Feature_Encoding.ipynb