Tabular Classification
Scikit-learn
Joblib
English
timeseries
detection
anomaly-detection
energy
battery-storage
vrfb
gaussian-mixture-model
one-class-svm
Instructions to use EnerTEF/Anomaly-Detection-Service with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Scikit-learn
How to use EnerTEF/Anomaly-Detection-Service with Scikit-learn:
from huggingface_hub import hf_hub_download import joblib model = joblib.load( hf_hub_download("EnerTEF/Anomaly-Detection-Service", "sklearn_model.joblib") ) # only load pickle files from sources you trust # read more about it here https://skops.readthedocs.io/en/stable/persistence.html - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse files- .gitattributes +1 -34
- Anomaly indication algorithm - VRFB.ipynb +697 -0
- Dataset_11var_treino.csv +0 -0
- LICENSE +21 -0
- README.md +128 -0
- model.joblib +3 -0
- requirements.txt +9 -0
- test_observations.csv +3 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,2 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.csv filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Anomaly indication algorithm - VRFB.ipynb
ADDED
|
@@ -0,0 +1,697 @@
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "a10db1bf",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# GMM and One-Class SVM anomaly detection\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"This notebook uses normal VRFB battery observations to train a six-component Gaussian Mixture Model. A baseline threshold is the minimum log-likelihood of the normal training data. A One-Class SVM then learns a decision boundary from the normal GMM log-likelihoods, so fitting does not require anomalous examples.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"The supplied test observations come from the failure scenario described by the source project. Because the CSV has no fault labels for individual observations, the reported results are outlier rates rather than independently verified classification accuracy. The normal-reference rate is measured on the fitting data.\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"The single-Gaussian baseline uses the same feature set as the GMM for a comparable AIC/BIC calculation. The alarm example uses dates and times to count anomalous readings within a 12-hour window.\n"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "markdown",
|
| 19 |
+
"id": "a184f359",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"# Anomaly Detection in Vanadium Battery System\n",
|
| 23 |
+
"This notebook demonstrates a two-part approach for detecting anomalies in a Battery Storage System with an example for a Vanadium Redox Flow Battery (VRFB) system. The variables will have to be adjusted according to what is provided by the corresponding Battery Management System. The significant change of variables may impact the accuracy of the model.\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"### Objective:\n",
|
| 26 |
+
"- **Part 1**: Apply a **Gaussian Mixture Model (GMM)** to identify anomalies based on a threshold value.\n",
|
| 27 |
+
"- **Part 2**: Implement a **One-Class Support Vector Machine (SVM)** to handle scenarios where anomalous data is unavailable for training.\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"### Dataset Description:\n",
|
| 30 |
+
"The dataset includes various sensor readings from the battery system. The aim is to detect and flag abnormal readings using unsupervised machine learning techniques.\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"### Dependencies:\n",
|
| 33 |
+
"- `pandas` for data manipulation.\n",
|
| 34 |
+
"- `numpy` for numerical operations.\n",
|
| 35 |
+
"- `scikit-learn` for model implementation.\n",
|
| 36 |
+
"- `matplotlib` and `seaborn` for data visualization."
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "markdown",
|
| 41 |
+
"id": "ba9d3cc2",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# 1st Part - GMM aplication"
|
| 45 |
+
]
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"id": "e9d2bc8e",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"outputs": [],
|
| 53 |
+
"source": [
|
| 54 |
+
"import pandas as pd\n",
|
| 55 |
+
"import numpy as np\n",
|
| 56 |
+
"from sklearn.mixture import GaussianMixture\n",
|
| 57 |
+
"import matplotlib.pyplot as plt\n",
|
| 58 |
+
"import seaborn as sns\n",
|
| 59 |
+
"\n",
|
| 60 |
+
"# Load the dataset\n",
|
| 61 |
+
"df = pd.read_csv('Dataset_11var_treino.csv', sep=';')\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"# Select relevant features (11 variables from the data provider)\n",
|
| 64 |
+
"features = df[['DC Power Battery W', 'DC Voltage Battery V', 'Current DC Battery A', 'Voltage L1 V', 'Current L1 A', 'Temperature Eletrolite C', 'Avg Schneider Voltage L1 V', 'Avg Schneider Current L1 kA', 'Avg Schneider React Power L1 kVAr', 'Avg Schneider Power Factor L1', 'SOC' ]]\n",
|
| 65 |
+
"df.head()\n",
|
| 66 |
+
"df.describe()"
|
| 67 |
+
]
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"id": "8c4acb6f",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"outputs": [],
|
| 75 |
+
"source": [
|
| 76 |
+
"#We can take one or two variables as example and check if the data set is unimodal or multimodal to justify the use of a mixture model\n",
|
| 77 |
+
"# Assuming 'data' is your dataset\n",
|
| 78 |
+
"fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(7, 2.5))\n",
|
| 79 |
+
"sns.histplot(df['Current DC Battery A'], kde=True, ax=axes[0])\n",
|
| 80 |
+
"axes[0].set_title('Distribution of Current DC Battery A')\n",
|
| 81 |
+
"axes[0].set_xlabel('Values')\n",
|
| 82 |
+
"axes[0].set_ylabel('Frequency')\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"sns.histplot(df['DC Power Battery W'], kde=True, ax=axes[1])\n",
|
| 85 |
+
"axes[1].set_title('Distribution of DC Power Battery W')\n",
|
| 86 |
+
"axes[1].set_xlabel('Values')\n",
|
| 87 |
+
"axes[1].set_ylabel('Frequency')\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"plt.tight_layout()\n",
|
| 90 |
+
"plt.show()"
|
| 91 |
+
]
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "markdown",
|
| 95 |
+
"id": "c9d84101",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [
|
| 98 |
+
"# Implementation with the GMM - Train the model"
|
| 99 |
+
]
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"id": "13f63963",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"outputs": [],
|
| 107 |
+
"source": [
|
| 108 |
+
"# We will fit the data to n clusters. We do this because we aknowledge that there are multimodal regions not a unique (unimodal) as seen in the pot above\n",
|
| 109 |
+
"# Fit Gaussian Mixture Model to the initial normal behavior\n",
|
| 110 |
+
"n_components = 6 # You can adjust the number of components\n",
|
| 111 |
+
"gmm = GaussianMixture(n_components=n_components, random_state=42)\n",
|
| 112 |
+
"gmm.fit(features)\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# Calculate the variance for each variable\n",
|
| 115 |
+
"variances = features.var(axis=0)\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"log_likelihoods = gmm.score_samples(features)\n",
|
| 118 |
+
"# Calculate mean and standard deviation of variances\n",
|
| 119 |
+
"mean_variance = variances.mean()\n",
|
| 120 |
+
"std_dev_variance = variances.std()\n",
|
| 121 |
+
"\n"
|
| 122 |
+
]
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"id": "7d290318",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"outputs": [],
|
| 130 |
+
"source": [
|
| 131 |
+
"total_log_likelihood = np.sum(gmm.score_samples(features))\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"# Number of components (K) and dimensionality (D)\n",
|
| 134 |
+
"K = gmm.n_components\n",
|
| 135 |
+
"D = gmm.means_.shape[1]\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"# Calculate the number of parameters\n",
|
| 138 |
+
"num_parameters = (K - 1) + K * D + K * (D * (D + 1)) / 2\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"# Print the results\n",
|
| 141 |
+
"print(\"Total Log-Likelihood_GMM:\", total_log_likelihood)\n",
|
| 142 |
+
"print(\"Number of Parameters:\", num_parameters)"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"id": "6f14fd49",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"outputs": [],
|
| 151 |
+
"source": [
|
| 152 |
+
"print(\"Min value of log:likeihood is:\",log_likelihoods.min())\n",
|
| 153 |
+
"print(\"Max value of log:likeihood is:\",log_likelihoods.max())"
|
| 154 |
+
]
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"id": "c3e2debb",
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"outputs": [],
|
| 162 |
+
"source": [
|
| 163 |
+
"from pandas.plotting import scatter_matrix\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"labels = gmm.predict(features)\n",
|
| 166 |
+
"features_c = df[['DC Power Battery W', 'Avg Schneider Voltage L1 V']].copy() # Use .copy()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"# Add cluster labels to the DataFrame\n",
|
| 169 |
+
"features_c['Cluster'] = labels\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"# Define markers for each cluster\n",
|
| 172 |
+
"markers = ['_', 'd', '>', '|', 'X', '+'] # You can extend this list for more clusters\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"# Create scatter plot with markers representing clusters\n",
|
| 175 |
+
"plt.figure(figsize=(8, 6))\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"# Plot clusters 2 to 5 first\n",
|
| 178 |
+
"for cluster_label, marker in zip(range(2, 6), markers[2:]):\n",
|
| 179 |
+
" cluster_data = features_c[features_c['Cluster'] == cluster_label]\n",
|
| 180 |
+
" plt.scatter(cluster_data['DC Power Battery W'], cluster_data['Avg Schneider Voltage L1 V'], marker=marker, label=f'Cluster {cluster_label}')\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# Plot clusters 0 and 1\n",
|
| 183 |
+
"for cluster_label, marker in zip([0, 1], markers[:2]):\n",
|
| 184 |
+
" cluster_data = features_c[features_c['Cluster'] == cluster_label]\n",
|
| 185 |
+
" plt.scatter(cluster_data['DC Power Battery W'], cluster_data['Avg Schneider Voltage L1 V'], marker=marker, label=f'Cluster {cluster_label}')\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"plt.xlabel('DC Power Battery W')\n",
|
| 188 |
+
"plt.ylabel('Avg Schneider Voltage L1 V')\n",
|
| 189 |
+
"plt.title('Scatter Plot with Cluster Symbols')\n",
|
| 190 |
+
"plt.legend()\n",
|
| 191 |
+
"plt.show()\n"
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"id": "6f9a94a0",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"outputs": [],
|
| 200 |
+
"source": [
|
| 201 |
+
"#Indicators from the GMM. Select the number of clusters to minimize these indicators\n",
|
| 202 |
+
"aic = gmm.aic(features)\n",
|
| 203 |
+
"bic = gmm.bic(features)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"print(\"AIC:\", aic)\n",
|
| 206 |
+
"print(\"BIC:\", bic)"
|
| 207 |
+
]
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "markdown",
|
| 211 |
+
"id": "338f6cd6",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Generate the Likelihood values of the test dataset using GMM to test True positives"
|
| 215 |
+
]
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "code",
|
| 219 |
+
"execution_count": null,
|
| 220 |
+
"id": "ffc1eb28",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"outputs": [],
|
| 223 |
+
"source": [
|
| 224 |
+
"# Load the CSV file with multiple observations to test (We have two dataset 'test_observations.csv' and 'VRFB_Dataset.csv', Dataset_11var_treino.csv)\n",
|
| 225 |
+
"new_observations_df = pd.read_csv('test_observations.csv', sep=';') #Ideia de submeter o dataset de treino (sem anomalias) ao teste. Conseguiremos analisar quanto comportamento normal está a gaussiana total a capturar.\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"new_observations_df.head()\n",
|
| 228 |
+
"new_observations_df.describe()\n"
|
| 229 |
+
]
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"execution_count": null,
|
| 234 |
+
"id": "35ca7870",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"outputs": [],
|
| 237 |
+
"source": [
|
| 238 |
+
"Linenbr_new_observations_df=new_observations_df.shape[0]\n",
|
| 239 |
+
"print(Linenbr_new_observations_df)"
|
| 240 |
+
]
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"id": "99f05ba3",
|
| 246 |
+
"metadata": {},
|
| 247 |
+
"outputs": [],
|
| 248 |
+
"source": [
|
| 249 |
+
"# Select relevant features for the new observations\n",
|
| 250 |
+
"new_features = new_observations_df[['DC Power Battery W', 'DC Voltage Battery V', 'Current DC Battery A', 'Voltage L1 V', 'Current L1 A', 'Temperature Eletrolite C', 'Avg Schneider Voltage L1 V', 'Avg Schneider Current L1 kA', 'Avg Schneider React Power L1 kVAr', 'Avg Schneider Power Factor L1','SOC']]\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"# Calculate log-likelihoods for the new observations\n",
|
| 253 |
+
"log_likelihoods_test = gmm.score_samples(new_features)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"new_observations_df['Log_Likelihood_test'] = log_likelihoods_test\n",
|
| 256 |
+
"variance_threshold=log_likelihoods.min() # CHANGE THIS VALUE according to the min/maximum of the train Dataset (depending on what we want to do). This is the maximum loglikelihood_test value\n",
|
| 257 |
+
"is_anomaly = log_likelihoods_test < variance_threshold\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"# Count the number of anomalies\n",
|
| 260 |
+
"anomaly_count = sum(is_anomaly)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"# Print the count of anomalies\n",
|
| 263 |
+
"print(\"Number of anomalies detected:\", anomaly_count)\n",
|
| 264 |
+
"print(\"% of anomalies detected:\", anomaly_count/Linenbr_new_observations_df*100)\n",
|
| 265 |
+
"# Add a new column 'Is_Anomaly' to the new_observations_df\n",
|
| 266 |
+
"new_observations_df['Is_Anomaly'] = is_anomaly\n",
|
| 267 |
+
"# Save the updated DataFrame to a new CSV file containing the Log:likelihhod values\n",
|
| 268 |
+
"new_observations_df.to_csv('output_file.csv', index=False)"
|
| 269 |
+
]
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"execution_count": null,
|
| 274 |
+
"id": "6f6a8743",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"outputs": [],
|
| 277 |
+
"source": [
|
| 278 |
+
"new_observations_df['Log_Likelihood_test'].describe()"
|
| 279 |
+
]
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"id": "bca4b566",
|
| 285 |
+
"metadata": {},
|
| 286 |
+
"outputs": [],
|
| 287 |
+
"source": [
|
| 288 |
+
"df_out = pd.read_csv('output_file.csv')\n",
|
| 289 |
+
"df_out.head()"
|
| 290 |
+
]
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"execution_count": null,
|
| 295 |
+
"id": "d6f3efd3",
|
| 296 |
+
"metadata": {},
|
| 297 |
+
"outputs": [],
|
| 298 |
+
"source": [
|
| 299 |
+
"plt.figure(figsize=(6, 3))\n",
|
| 300 |
+
"plt.hist(log_likelihoods_test, bins=50, color='blue', alpha=0.7)\n",
|
| 301 |
+
"plt.title('Histogram of Log-Likelihood Values for New Observations')\n",
|
| 302 |
+
"plt.xlabel('Log-Likelihood')\n",
|
| 303 |
+
"plt.ylabel('Frequency')\n",
|
| 304 |
+
"plt.show()"
|
| 305 |
+
]
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"id": "96c5f5aa",
|
| 311 |
+
"metadata": {},
|
| 312 |
+
"outputs": [],
|
| 313 |
+
"source": [
|
| 314 |
+
"# Score the normal reference data directly; no external output_file2.csv is needed.\n",
|
| 315 |
+
"df_out = pd.read_csv('Dataset_11var_treino.csv', sep=';')\n",
|
| 316 |
+
"df_out['Log_Likelihood_test'] = gmm.score_samples(df_out[features.columns])\n",
|
| 317 |
+
"df_out.head()\n"
|
| 318 |
+
]
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"execution_count": null,
|
| 323 |
+
"id": "931322e8",
|
| 324 |
+
"metadata": {},
|
| 325 |
+
"outputs": [],
|
| 326 |
+
"source": [
|
| 327 |
+
"numero_de_linhas = df_out.shape[0]\n",
|
| 328 |
+
"numero_de_linhas"
|
| 329 |
+
]
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"cell_type": "markdown",
|
| 333 |
+
"id": "37466bbe",
|
| 334 |
+
"metadata": {},
|
| 335 |
+
"source": [
|
| 336 |
+
"# Justifying why a GMM is better than a simple Gaussian fit"
|
| 337 |
+
]
|
| 338 |
+
},
|
| 339 |
+
{
|
| 340 |
+
"cell_type": "code",
|
| 341 |
+
"execution_count": null,
|
| 342 |
+
"id": "f9034482",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"outputs": [],
|
| 345 |
+
"source": [
|
| 346 |
+
"# Compare models fitted to the same 11 variables and observations.\n",
|
| 347 |
+
"# A single-component GMM is a multivariate Gaussian baseline.\n",
|
| 348 |
+
"simple_gaussian = GaussianMixture(n_components=1, random_state=42)\n",
|
| 349 |
+
"simple_gaussian.fit(features)\n",
|
| 350 |
+
"aic_SG = simple_gaussian.aic(features)\n",
|
| 351 |
+
"bic_SG = simple_gaussian.bic(features)\n",
|
| 352 |
+
"print('Single Gaussian AIC:', aic_SG)\n",
|
| 353 |
+
"print('Single Gaussian BIC:', bic_SG)\n",
|
| 354 |
+
"print('Six-component GMM AIC:', aic)\n",
|
| 355 |
+
"print('Six-component GMM BIC:', bic)\n"
|
| 356 |
+
]
|
| 357 |
+
},
|
| 358 |
+
{
|
| 359 |
+
"cell_type": "code",
|
| 360 |
+
"execution_count": null,
|
| 361 |
+
"id": "1b1d97b9",
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"outputs": [],
|
| 364 |
+
"source": [
|
| 365 |
+
"print('Lower AIC/BIC indicates a better fit after penalizing model complexity.')\n",
|
| 366 |
+
"print('GMM has lower AIC:', aic < aic_SG)\n",
|
| 367 |
+
"print('GMM has lower BIC:', bic < bic_SG)\n"
|
| 368 |
+
]
|
| 369 |
+
},
|
| 370 |
+
{
|
| 371 |
+
"cell_type": "markdown",
|
| 372 |
+
"id": "6f28e62e",
|
| 373 |
+
"metadata": {},
|
| 374 |
+
"source": [
|
| 375 |
+
"# Applying the model to the original training dataset to get the likelihood values and test false positives later on"
|
| 376 |
+
]
|
| 377 |
+
},
|
| 378 |
+
{
|
| 379 |
+
"cell_type": "code",
|
| 380 |
+
"execution_count": null,
|
| 381 |
+
"id": "e8d675d2",
|
| 382 |
+
"metadata": {},
|
| 383 |
+
"outputs": [],
|
| 384 |
+
"source": [
|
| 385 |
+
"# Load the CSV file with multiple observations to test\n",
|
| 386 |
+
"new_observations_df = pd.read_csv('Dataset_11var_treino.csv', sep=';') \n",
|
| 387 |
+
"# Select relevant features for the new observations\n",
|
| 388 |
+
"new_features1 = new_observations_df[['DC Power Battery W', 'DC Voltage Battery V', 'Current DC Battery A', 'Voltage L1 V', 'Current L1 A', 'Temperature Eletrolite C', 'Avg Schneider Voltage L1 V', 'Avg Schneider Current L1 kA', 'Avg Schneider React Power L1 kVAr', 'Avg Schneider Power Factor L1', 'SOC']]\n",
|
| 389 |
+
"\n",
|
| 390 |
+
"# Calculate log-likelihoods for the new observations\n",
|
| 391 |
+
"log_likelihoods_test = gmm.score_samples(new_features1)\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"new_observations_df['Log_Likelihood_test'] = log_likelihoods_test\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"# Save the updated DataFrame to a new CSV file\n",
|
| 396 |
+
"new_observations_df.to_csv('output_file1.csv', index=False)"
|
| 397 |
+
]
|
| 398 |
+
},
|
| 399 |
+
{
|
| 400 |
+
"cell_type": "markdown",
|
| 401 |
+
"id": "74d303f8",
|
| 402 |
+
"metadata": {},
|
| 403 |
+
"source": [
|
| 404 |
+
"# Plot the Components and the GMM Curve"
|
| 405 |
+
]
|
| 406 |
+
},
|
| 407 |
+
{
|
| 408 |
+
"cell_type": "code",
|
| 409 |
+
"execution_count": null,
|
| 410 |
+
"id": "00d3064d",
|
| 411 |
+
"metadata": {},
|
| 412 |
+
"outputs": [],
|
| 413 |
+
"source": [
|
| 414 |
+
"import pandas as pd\n",
|
| 415 |
+
"import numpy as np\n",
|
| 416 |
+
"from sklearn.mixture import GaussianMixture\n",
|
| 417 |
+
"import matplotlib.pyplot as plt\n",
|
| 418 |
+
"from scipy.stats import norm\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"# Plot histogram of each feature with Gaussian mixture components\n",
|
| 421 |
+
"plt.figure(figsize=(16, 10))\n",
|
| 422 |
+
"for i, feature in enumerate(features.columns):\n",
|
| 423 |
+
" plt.subplot(3, 4, i+1)\n",
|
| 424 |
+
" plt.hist(features[feature], bins=30, density=True, alpha=0.5, color='blue')\n",
|
| 425 |
+
"\n",
|
| 426 |
+
" # Plot Gaussian mixture components for this feature\n",
|
| 427 |
+
" x = np.linspace(features[feature].min(), features[feature].max(), 1000)\n",
|
| 428 |
+
" pdf_components = np.zeros_like(x)\n",
|
| 429 |
+
" for j in range(n_components):\n",
|
| 430 |
+
" weight = gmm.weights_[j]\n",
|
| 431 |
+
" mean = gmm.means_[j, i] # Extract mean for the specific feature\n",
|
| 432 |
+
" std = np.sqrt(gmm.covariances_[j, i, i]) # Extract standard deviation for the specific feature\n",
|
| 433 |
+
" pdf_components += norm.pdf(x, mean, std) * weight\n",
|
| 434 |
+
" plt.plot(x, norm.pdf(x, mean, std) * weight, label=f'Comp. {j+1}', linestyle='--', color='red')\n",
|
| 435 |
+
" \n",
|
| 436 |
+
" # Plot resulting Gaussian mixture curve\n",
|
| 437 |
+
" plt.plot(x, pdf_components, label='G. Mix.', color='green')\n",
|
| 438 |
+
" \n",
|
| 439 |
+
" plt.title(feature)\n",
|
| 440 |
+
" plt.xlabel('Value')\n",
|
| 441 |
+
" plt.ylabel('Density')\n",
|
| 442 |
+
" plt.legend()\n",
|
| 443 |
+
"\n",
|
| 444 |
+
"plt.tight_layout()\n",
|
| 445 |
+
"plt.show()\n"
|
| 446 |
+
]
|
| 447 |
+
},
|
| 448 |
+
{
|
| 449 |
+
"cell_type": "markdown",
|
| 450 |
+
"id": "acde899e",
|
| 451 |
+
"metadata": {},
|
| 452 |
+
"source": [
|
| 453 |
+
"# 2nd Part - ONE-Class SVM implementation"
|
| 454 |
+
]
|
| 455 |
+
},
|
| 456 |
+
{
|
| 457 |
+
"cell_type": "code",
|
| 458 |
+
"execution_count": null,
|
| 459 |
+
"id": "7a20916b",
|
| 460 |
+
"metadata": {},
|
| 461 |
+
"outputs": [],
|
| 462 |
+
"source": [
|
| 463 |
+
"# We now take the log-likelihood values and train the model. \n",
|
| 464 |
+
"# The log_likelihood values corresponding to normal observations are stores in output_file1 (from the training dataset)\n",
|
| 465 |
+
"import pandas as pd\n",
|
| 466 |
+
"import numpy as np\n",
|
| 467 |
+
"import matplotlib.pyplot as plt\n",
|
| 468 |
+
"from sklearn.svm import OneClassSVM\n",
|
| 469 |
+
"from sklearn.metrics import accuracy_score\n",
|
| 470 |
+
"from sklearn.model_selection import GridSearchCV\n",
|
| 471 |
+
"\n",
|
| 472 |
+
"# Load the dataset generated by the training model of the GMM to train the OCSVM (normal data output_file1.csv)\n",
|
| 473 |
+
"df = pd.read_csv('output_file1.csv', sep=',', encoding='latin1')\n",
|
| 474 |
+
"\n",
|
| 475 |
+
"# Extract the 'log-likelihood' variable\n",
|
| 476 |
+
"X_train = df['Log_Likelihood_test'].values.reshape(-1, 1)\n",
|
| 477 |
+
"\n",
|
| 478 |
+
"# Train the one-class SVM model\n",
|
| 479 |
+
"ocsvm_model = OneClassSVM(nu=0.001, kernel=\"rbf\", gamma=0.01)\n",
|
| 480 |
+
"ocsvm_model.fit(X_train)"
|
| 481 |
+
]
|
| 482 |
+
},
|
| 483 |
+
{
|
| 484 |
+
"cell_type": "markdown",
|
| 485 |
+
"id": "3f0350d7",
|
| 486 |
+
"metadata": {},
|
| 487 |
+
"source": [
|
| 488 |
+
"# Fine Tune HyperParameters"
|
| 489 |
+
]
|
| 490 |
+
},
|
| 491 |
+
{
|
| 492 |
+
"cell_type": "code",
|
| 493 |
+
"execution_count": null,
|
| 494 |
+
"id": "33d9fab3",
|
| 495 |
+
"metadata": {},
|
| 496 |
+
"outputs": [],
|
| 497 |
+
"source": [
|
| 498 |
+
"#Run the cross validation in the first time to fine tune the hyperparameters\n",
|
| 499 |
+
"#We can tune the Kernel, the Gamma and the nu. here is an example for the nu parameter:\n",
|
| 500 |
+
"#param_grid = {'nu': [0.000001, 0001., 0.1, 0.5]}\n",
|
| 501 |
+
"#Perform Cross Validation to fine tune the nu parameter\n",
|
| 502 |
+
"#grid_search = GridSearchCV(ocsvm_model, param_grid, cv=5, scoring='accuracy')\n",
|
| 503 |
+
"#grid_search.fit(X_train)\n",
|
| 504 |
+
"\n",
|
| 505 |
+
"# Get the best parameter value\n",
|
| 506 |
+
"#best_nu = grid_search.best_params_['nu']\n",
|
| 507 |
+
"#print(\"Best value of nu found:\", best_nu)\n",
|
| 508 |
+
"\n",
|
| 509 |
+
"# You can access other information such as best score and CV results as well\n",
|
| 510 |
+
"#print(\"Best cross-validation score:\", grid_search.best_score_)\n",
|
| 511 |
+
"#print(\"Grid search results:\", grid_search.cv_results_)\n",
|
| 512 |
+
"\n",
|
| 513 |
+
"# Hyperparameter are:\n",
|
| 514 |
+
"#Kernel type (kernel),The choice of kernel function which can be Linear ('linear'), Radial basis function (RBF) ('rbf'), Polynomial ('poly'), Sigmoid ('sigmoid')\n",
|
| 515 |
+
"#nu relaxes or tightens the boundary - trade off between false positives and false negatives\n",
|
| 516 |
+
"# Kernel coefficient (gamma): This parameter is specific to the RBF, polynomial, and sigmoid kernels. It determines the influence of a single training example; low values imply a Gaussian-like function, and high values may lead to overfitting."
|
| 517 |
+
]
|
| 518 |
+
},
|
| 519 |
+
{
|
| 520 |
+
"cell_type": "markdown",
|
| 521 |
+
"id": "7e80b424",
|
| 522 |
+
"metadata": {},
|
| 523 |
+
"source": [
|
| 524 |
+
"# Test The actual DataSets for abnormal observation and Export prediction results to CSV"
|
| 525 |
+
]
|
| 526 |
+
},
|
| 527 |
+
{
|
| 528 |
+
"cell_type": "code",
|
| 529 |
+
"execution_count": null,
|
| 530 |
+
"id": "94bd92bd",
|
| 531 |
+
"metadata": {},
|
| 532 |
+
"outputs": [],
|
| 533 |
+
"source": [
|
| 534 |
+
"import pandas as pd\n",
|
| 535 |
+
"import numpy as np\n",
|
| 536 |
+
"import matplotlib.pyplot as plt\n",
|
| 537 |
+
"from sklearn.metrics import accuracy_score\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"# Load test data from CSV (use output1.csv to test the training dataset with normal observation, and output.csv or use output2.csv the new dataset)\n",
|
| 540 |
+
"test_data = pd.read_csv('output_file.csv', sep=',', encoding='latin1')\n",
|
| 541 |
+
"\n",
|
| 542 |
+
"# Extract the 'log-likelihood' variable\n",
|
| 543 |
+
"X_test = test_data['Log_Likelihood_test'].values.reshape(-1, 1)\n",
|
| 544 |
+
"\n",
|
| 545 |
+
"# Predict outliers on the test data\n",
|
| 546 |
+
"outlier_preds = ocsvm_model.predict(X_test)\n",
|
| 547 |
+
"\n",
|
| 548 |
+
"# Extract hour and date columns\n",
|
| 549 |
+
"hour_column = test_data['Hora']\n",
|
| 550 |
+
"date_column = test_data['Data']\n",
|
| 551 |
+
"\n",
|
| 552 |
+
"# Create a DataFrame with test data, hour, date, and predicted outliers\n",
|
| 553 |
+
"results_df = pd.DataFrame({'Date': date_column,\n",
|
| 554 |
+
" 'Hour': hour_column,\n",
|
| 555 |
+
" 'Log_Likelihood': X_test.flatten(),\n",
|
| 556 |
+
" 'Outlier_Predictions': outlier_preds})\n",
|
| 557 |
+
"\n",
|
| 558 |
+
"# Save the results to a CSV file\n",
|
| 559 |
+
"results_df.to_csv('OC_SVM_anomaly_results.csv', index=False)\n",
|
| 560 |
+
"\n",
|
| 561 |
+
"# The test outlier rate is reported below; there are no row-level labels in the CSV.\n",
|
| 562 |
+
"\n",
|
| 563 |
+
"# Plot the results\n",
|
| 564 |
+
"plt.figure(figsize=(5, 3))\n",
|
| 565 |
+
"\n",
|
| 566 |
+
"# Plot normal data\n",
|
| 567 |
+
"plt.scatter(X_train, np.zeros_like(X_train), color='blue', label='Normal Data')\n",
|
| 568 |
+
"\n",
|
| 569 |
+
"# Plot outliers detected by the model\n",
|
| 570 |
+
"plt.scatter(X_test[outlier_preds == -1], np.zeros_like(X_test[outlier_preds == -1]), color='red', label='Detected Outliers')\n",
|
| 571 |
+
"\n",
|
| 572 |
+
"# Plot the decision boundary\n",
|
| 573 |
+
"xx = np.linspace(X_train.min(), X_train.max(), 500).reshape(-1, 1)\n",
|
| 574 |
+
"yy = np.zeros_like(xx) # For 1D boundary plot\n",
|
| 575 |
+
"Z = ocsvm_model.decision_function(xx)\n",
|
| 576 |
+
"plt.plot(xx, Z, color='black', linestyle='dashed', label='Decision Boundary')\n",
|
| 577 |
+
"\n",
|
| 578 |
+
"plt.xlabel('Log-Likelihood')\n",
|
| 579 |
+
"plt.ylabel('Observation Class')\n",
|
| 580 |
+
"plt.title('One-Class SVM Outlier Detection')\n",
|
| 581 |
+
"plt.legend()\n",
|
| 582 |
+
"plt.show()\n",
|
| 583 |
+
"\n",
|
| 584 |
+
"# Print results\n",
|
| 585 |
+
"print(\"% of anomalies classified:\", np.sum(outlier_preds == -1)/len(X_test))\n",
|
| 586 |
+
"print(\"Number of observations:\", len(X_test))\n",
|
| 587 |
+
"print(\"Number of abnormal observations classified by the model:\", np.sum(outlier_preds == -1),\"which is\",round(np.sum(outlier_preds == -1)/len(X_test)*100,2), \"%\")\n",
|
| 588 |
+
"print(\"Number of normal observations classified by the model:\", np.sum(outlier_preds == 1),\"which is\", round(np.sum(outlier_preds == 1)/len(X_test)*100,2), \"%\")\n",
|
| 589 |
+
"\n"
|
| 590 |
+
]
|
| 591 |
+
},
|
| 592 |
+
{
|
| 593 |
+
"cell_type": "markdown",
|
| 594 |
+
"id": "85fb751c",
|
| 595 |
+
"metadata": {},
|
| 596 |
+
"source": [
|
| 597 |
+
"# Alarm example: more than three anomalous readings within 12 hours\n",
|
| 598 |
+
"\n",
|
| 599 |
+
"This is an illustrative maintenance rule. Calibrate the window and event count for the asset and its sampling rate. Use complete dates and times so the window works across midnight.\n"
|
| 600 |
+
]
|
| 601 |
+
},
|
| 602 |
+
{
|
| 603 |
+
"cell_type": "code",
|
| 604 |
+
"execution_count": null,
|
| 605 |
+
"id": "2172b7c5",
|
| 606 |
+
"metadata": {},
|
| 607 |
+
"outputs": [],
|
| 608 |
+
"source": [
|
| 609 |
+
"df_ratio = pd.read_csv('OC_SVM_anomaly_results.csv')\n",
|
| 610 |
+
"df_ratio['Timestamp'] = pd.to_datetime(\n",
|
| 611 |
+
" df_ratio['Date'] + ' ' + df_ratio['Hour'], format='%d/%m/%Y %H:%M:%S'\n",
|
| 612 |
+
")\n",
|
| 613 |
+
"df_ratio = df_ratio.sort_values('Timestamp')\n",
|
| 614 |
+
"df_ratio.head()\n"
|
| 615 |
+
]
|
| 616 |
+
},
|
| 617 |
+
{
|
| 618 |
+
"cell_type": "code",
|
| 619 |
+
"execution_count": null,
|
| 620 |
+
"id": "1f7843e5",
|
| 621 |
+
"metadata": {},
|
| 622 |
+
"outputs": [],
|
| 623 |
+
"source": [
|
| 624 |
+
"# Set the anomaly column to boolean\n",
|
| 625 |
+
"df_ratio['Outlier_Predictions'] = df_ratio['Outlier_Predictions'].map({1: False, -1: True})\n",
|
| 626 |
+
"# Set the time window for anomaly checking (12 hours)\n",
|
| 627 |
+
"df_ratio['Outlier_Predictions']"
|
| 628 |
+
]
|
| 629 |
+
},
|
| 630 |
+
{
|
| 631 |
+
"cell_type": "code",
|
| 632 |
+
"execution_count": null,
|
| 633 |
+
"id": "94c47abe",
|
| 634 |
+
"metadata": {},
|
| 635 |
+
"outputs": [],
|
| 636 |
+
"source": [
|
| 637 |
+
"# Count anomalies in (timestamp - 12 hours, timestamp], in chronological order.\n",
|
| 638 |
+
"recent_counts = df_ratio.set_index('Timestamp')['Outlier_Predictions'].rolling('12h').sum()\n",
|
| 639 |
+
"triggered = df_ratio['Outlier_Predictions'].to_numpy() & (recent_counts.to_numpy() > 3)\n",
|
| 640 |
+
"if triggered.any():\n",
|
| 641 |
+
" print('Anomaly ratios triggered within the past 12 hours:')\n",
|
| 642 |
+
" print('Total anomalous readings satisfying the rule:', int(triggered.sum()))\n",
|
| 643 |
+
" print('Please consider preventive maintenance')\n",
|
| 644 |
+
"else:\n",
|
| 645 |
+
" print('No maintenance alarm triggered.')\n"
|
| 646 |
+
]
|
| 647 |
+
},
|
| 648 |
+
{
|
| 649 |
+
"cell_type": "code",
|
| 650 |
+
"execution_count": null,
|
| 651 |
+
"id": "d537be18",
|
| 652 |
+
"metadata": {},
|
| 653 |
+
"outputs": [],
|
| 654 |
+
"source": [
|
| 655 |
+
"# Persist the trained estimators and feature contract for direct inference.\n",
|
| 656 |
+
"import joblib\n",
|
| 657 |
+
"import sklearn\n",
|
| 658 |
+
"\n",
|
| 659 |
+
"model_bundle = {\n",
|
| 660 |
+
" 'gmm': gmm,\n",
|
| 661 |
+
" 'ocsvm': ocsvm_model,\n",
|
| 662 |
+
" 'feature_names': list(features.columns),\n",
|
| 663 |
+
" 'gmm_threshold': float(log_likelihoods.min()),\n",
|
| 664 |
+
" 'training_rows': len(features),\n",
|
| 665 |
+
" 'sklearn_version': sklearn.__version__,\n",
|
| 666 |
+
"}\n",
|
| 667 |
+
"joblib.dump(model_bundle, 'model.joblib', compress=3)\n",
|
| 668 |
+
"\n",
|
| 669 |
+
"# Report rates, without assuming the CSV contains per-observation fault labels.\n",
|
| 670 |
+
"normal_predictions = ocsvm_model.predict(gmm.score_samples(features).reshape(-1, 1))\n",
|
| 671 |
+
"print('Normal-reference outlier rate:', float(np.mean(normal_predictions == -1)))\n",
|
| 672 |
+
"print('Test outlier rate:', float(np.mean(outlier_preds == -1)))\n"
|
| 673 |
+
]
|
| 674 |
+
}
|
| 675 |
+
],
|
| 676 |
+
"metadata": {
|
| 677 |
+
"kernelspec": {
|
| 678 |
+
"display_name": "Python 3 (ipykernel)",
|
| 679 |
+
"language": "python",
|
| 680 |
+
"name": "python3"
|
| 681 |
+
},
|
| 682 |
+
"language_info": {
|
| 683 |
+
"codemirror_mode": {
|
| 684 |
+
"name": "ipython",
|
| 685 |
+
"version": 3
|
| 686 |
+
},
|
| 687 |
+
"file_extension": ".py",
|
| 688 |
+
"mimetype": "text/x-python",
|
| 689 |
+
"name": "python",
|
| 690 |
+
"nbconvert_exporter": "python",
|
| 691 |
+
"pygments_lexer": "ipython3",
|
| 692 |
+
"version": "3.11.8"
|
| 693 |
+
}
|
| 694 |
+
},
|
| 695 |
+
"nbformat": 4,
|
| 696 |
+
"nbformat_minor": 5
|
| 697 |
+
}
|
Dataset_11var_treino.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2024 Horizont-Europe-Interstore
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,3 +1,131 @@
|
|
| 1 |
---
|
| 2 |
license: mit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
library_name: sklearn
|
| 6 |
+
pipeline_tag: tabular-classification
|
| 7 |
+
tags:
|
| 8 |
+
- timeseries
|
| 9 |
+
- detection
|
| 10 |
+
- anomaly-detection
|
| 11 |
+
- energy
|
| 12 |
+
- battery-storage
|
| 13 |
+
- vrfb
|
| 14 |
+
- gaussian-mixture-model
|
| 15 |
+
- one-class-svm
|
| 16 |
---
|
| 17 |
+
|
| 18 |
+
# Anomaly Detection Service — VRFB
|
| 19 |
+
|
| 20 |
+
An unsupervised anomaly detection model for a **Vanadium Redox Flow Battery (VRFB)**, prepared for the [EnerTEF model collection](https://huggingface.co/EnerTEF). It combines a Gaussian Mixture Model (GMM) with a One-Class Support Vector Machine (OCSVM) to flag unusual battery sensor observations using normal operating data for training.
|
| 21 |
+
|
| 22 |
+
This release packages the methodology from [ENERTEF/Anomaly-Detection-Service](https://github.com/ENERTEF/Anomaly-Detection-Service) as a fitted scikit-learn model and a reproducible notebook example.
|
| 23 |
+
|
| 24 |
+
## Model description
|
| 25 |
+
|
| 26 |
+
1. A GMM learns normal operating behaviour from 11 battery measurements, using six components, full covariance matrices and `random_state=42`.
|
| 27 |
+
2. The GMM assigns each observation a log-likelihood. The standalone GMM baseline flags values below the minimum training log-likelihood.
|
| 28 |
+
3. An OCSVM learns a decision boundary on the **one-dimensional GMM log-likelihoods** of normal observations, using `kernel="rbf"`, `nu=0.001` and `gamma=0.01`.
|
| 29 |
+
|
| 30 |
+
The combined model returns `1` for an inlier and `-1` for an outlier. Measurements retain their original units; the notebook does not apply scaling or imputation. Dates and times are used for the alarm example, rather than as model features. The model classifies individual observations and does not learn temporal sequences.
|
| 31 |
+
|
| 32 |
+
## Repository contents
|
| 33 |
+
|
| 34 |
+
| File | Purpose |
|
| 35 |
+
| --- | --- |
|
| 36 |
+
| `model.joblib` | Fitted GMM and OCSVM, ordered feature names, GMM threshold, training row count and scikit-learn version. |
|
| 37 |
+
| `Anomaly indication algorithm - VRFB.ipynb` | Training, distribution plots, evaluation, model export and a maintenance alarm example. |
|
| 38 |
+
| `Dataset_11var_treino.csv` | Normal reference data: 74,992 observations. |
|
| 39 |
+
| `test_observations.csv` | Test data: 130,543 observations from the failure scenario described in the source notebook. |
|
| 40 |
+
| `requirements.txt` | Pinned dependencies used to create and verify the fitted model. |
|
| 41 |
+
| `LICENSE` | Original MIT license and copyright notice. |
|
| 42 |
+
| `.gitattributes` | Git LFS attributes for the model and CSV files. |
|
| 43 |
+
|
| 44 |
+
Both CSV files use `;` as the delimiter. They contain `Data` and `Hora` columns alongside the following numeric features, in model order:
|
| 45 |
+
|
| 46 |
+
```text
|
| 47 |
+
DC Power Battery W
|
| 48 |
+
DC Voltage Battery V
|
| 49 |
+
Current DC Battery A
|
| 50 |
+
Voltage L1 V
|
| 51 |
+
Current L1 A
|
| 52 |
+
Temperature Eletrolite C
|
| 53 |
+
Avg Schneider Voltage L1 V
|
| 54 |
+
Avg Schneider Current L1 kA
|
| 55 |
+
Avg Schneider React Power L1 kVAr
|
| 56 |
+
Avg Schneider Power Factor L1
|
| 57 |
+
SOC
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Keep these column names, units and order, including the original spelling of `Temperature Eletrolite C`. Input measurements must be numeric and finite. The source describes data obtained around a European industrial partner's battery failure; the CSV files do not include fault labels for individual observations.
|
| 61 |
+
|
| 62 |
+
## Installation and inference
|
| 63 |
+
|
| 64 |
+
Download the repository files and run the following commands from their directory. The supplied model was trained and verified with Python 3.14.4 and scikit-learn 1.9.1. Use the pinned package versions when loading it.
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
python -m pip install -r requirements.txt
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
import joblib
|
| 72 |
+
import numpy as np
|
| 73 |
+
import pandas as pd
|
| 74 |
+
|
| 75 |
+
model = joblib.load("model.joblib")
|
| 76 |
+
observations = pd.read_csv("test_observations.csv", sep=";")
|
| 77 |
+
features = observations.loc[:, model["feature_names"]]
|
| 78 |
+
if not np.isfinite(features.to_numpy(dtype=float)).all():
|
| 79 |
+
raise ValueError("Battery measurements must be numeric and finite.")
|
| 80 |
+
|
| 81 |
+
log_likelihoods = model["gmm"].score_samples(features)
|
| 82 |
+
labels = model["ocsvm"].predict(log_likelihoods.reshape(-1, 1))
|
| 83 |
+
|
| 84 |
+
results = observations.copy()
|
| 85 |
+
results["Log_Likelihood"] = log_likelihoods
|
| 86 |
+
results["Outlier_Predictions"] = labels # 1: inlier, -1: outlier
|
| 87 |
+
results["Is_Anomaly"] = labels == -1
|
| 88 |
+
results.to_csv("predictions.csv", index=False)
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
The same inference code accepts new observations with the required feature columns. Load the Joblib artifact only from a trusted source, because Joblib uses pickle-based deserialization. Inference runs locally with scikit-learn; this release provides no hosted inference endpoint.
|
| 92 |
+
|
| 93 |
+
## Reproduce the model
|
| 94 |
+
|
| 95 |
+
Open `Anomaly indication algorithm - VRFB.ipynb` in Jupyter or a notebook editor, with the repository directory as the working directory. Execute all cells in order using an environment with the dependencies above. If needed, install a Jupyter interface with `python -m pip install jupyterlab`.
|
| 96 |
+
|
| 97 |
+
The notebook fits both estimators, generates intermediate result CSVs, and saves `model.joblib`. Its maintenance example flags anomalous readings after more than three anomalies occur within the preceding 12 hours, using complete dates and times. This rule counts readings, rather than distinct failure events, and requires calibration to the sampling rate and asset.
|
| 98 |
+
|
| 99 |
+
The upload copy corrects prose cells stored as code, a reference to an unavailable intermediate CSV, the single-Gaussian comparison, and the alarm window implementation. Historical outputs were cleared. The GMM and OCSVM training parameters are preserved; the supplied artifact is newly fitted from the included normal data.
|
| 100 |
+
|
| 101 |
+
## Evaluation
|
| 102 |
+
|
| 103 |
+
All executable notebook cells completed in the pinned environment. Reloading `model.joblib` reproduced every test prediction from that run.
|
| 104 |
+
|
| 105 |
+
| Method and data | Outliers / observations | Outlier rate |
|
| 106 |
+
| --- | --- | --- |
|
| 107 |
+
| GMM minimum-training-likelihood threshold, test data | 85,956 / 130,543 | 65.8450% |
|
| 108 |
+
| GMM + OCSVM, test data | 128,762 / 130,543 | 98.6357% |
|
| 109 |
+
| GMM + OCSVM, normal training reference | 138 / 74,992 | 0.1840% |
|
| 110 |
+
|
| 111 |
+
These are **flagging rates**. Treating every test observation as anomalous makes the test flagging rate an assumed anomaly recall, but the CSV has no labels to independently verify that assumption. The normal reference was also used for fitting, so its outlier rate is an in-sample measurement. Precision, held-out false-positive rate and general classification accuracy are not established. Small numerical differences from the historical notebook outputs can occur across library versions and platforms.
|
| 112 |
+
|
| 113 |
+
## Intended uses and limitations
|
| 114 |
+
|
| 115 |
+
The demonstrated use is offline analysis of VRFB battery measurements and experimentation with condition monitoring. The source project also identifies storage assets, wind generation and wave energy converters as potential applications; those applications require appropriate variables, retraining and validation.
|
| 116 |
+
|
| 117 |
+
Training data represent one battery system and may not cover other operating regimes, sensor calibrations or seasonal conditions. Sensor errors and shifts in operating conditions can produce outliers without an equipment fault. Adapting the feature set or measurement units requires retraining. Validate the model on separate normal and labelled fault periods before using its outputs to guide maintenance decisions.
|
| 118 |
+
|
| 119 |
+
## License and project references
|
| 120 |
+
|
| 121 |
+
Distributed under the [MIT license](LICENSE), preserving `Copyright (c) 2024 Horizont-Europe-Interstore` from the source repository.
|
| 122 |
+
|
| 123 |
+
- [Source project and original methodology](https://github.com/ENERTEF/Anomaly-Detection-Service)
|
| 124 |
+
- [EnerTEF organization](https://huggingface.co/EnerTEF)
|
| 125 |
+
- [EnerTEF/SAMFormer](https://huggingface.co/EnerTEF/SAMFormer) — organization reference for notebook distribution and model-card metadata.
|
| 126 |
+
- [EnerTEF/ChebAutoencoder](https://huggingface.co/EnerTEF/ChebAutoencoder) — related detection model in the organization.
|
| 127 |
+
- [Hugging Face model cards](https://huggingface.co/docs/hub/model-cards)
|
| 128 |
+
|
| 129 |
+
## Upload this package
|
| 130 |
+
|
| 131 |
+
Create a model repository under `EnerTEF` (suggested name: `Anomaly-Detection-Service`) and upload **the contents of this folder to the repository root** through **Files and versions → Add file → Upload files**. Keeping `README.md` at the root makes it the model card. See the [Hugging Face upload instructions](https://huggingface.co/docs/hub/models-uploading).
|
model.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:856b572bad800fb8107c164f20fc5280a84b2c1d345af551c54c17a6fceec6a1
|
| 3 |
+
size 14716
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tested with Python 3.14.4; use these versions to load model.joblib.
|
| 2 |
+
numpy==2.5.3
|
| 3 |
+
pandas==3.0.6
|
| 4 |
+
scikit-learn==1.9.1
|
| 5 |
+
scipy==1.18.1
|
| 6 |
+
joblib==1.6.0
|
| 7 |
+
matplotlib==3.11.2
|
| 8 |
+
seaborn==0.13.2
|
| 9 |
+
ipykernel==7.4.0
|
test_observations.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e0e1d26b56eb5d05250ba75877132b0d6b5e2600ec57b8955325396fa72ed181
|
| 3 |
+
size 10525460
|