Certainly! Below is a Python function that performs anomaly detection on a power grid node using the provided dataset columns. This function leverages the Isolation Forest algorithm from scikit-learn, which is effective for high-dimensional datasets and doesn't assume any underlying data distribution.
Overview
-
Data Preprocessing:
- Handling Missing Values: It's crucial to handle missing data before feeding it into the model. You can choose to fill missing values or drop them based on your dataset's characteristics.
- Feature Scaling: Scaling ensures that all features contribute equally to the model's performance. Here,
StandardScaler is used to standardize features by removing the mean and scaling to unit variance.
-
Anomaly Detection with Isolation Forest:
- Isolation Forest: This algorithm isolates anomalies instead of profiling normal data points. It works well with high-dimensional data and is efficient for large datasets.
- Parameters:
n_estimators: Number of trees in the forest.
contamination: Proportion of anomalies in the data set.
random_state: Seed used by the random number generator.
-
Function Output:
- The function returns the original DataFrame with an additional column named
'Anomaly', where 1 indicates normal data and -1 indicates an anomaly.
Python Function
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
def detect_anomalies_power_grid(data: pd.DataFrame,
contamination: float = 0.01,
random_state: int = 42) -> pd.DataFrame:
"""
Detect anomalies in power grid node data using Isolation Forest.
Parameters:
- data (pd.DataFrame): The input DataFrame containing power grid metrics.
- contamination (float): The proportion of anomalies in the data set (default is 1%).
- random_state (int): Seed for reproducibility (default is 42).
Returns:
- pd.DataFrame: The original DataFrame with an additional 'Anomaly' column.
Anomaly values: 1 for normal, -1 for anomalies.
"""
# Copy the data to avoid modifying the original DataFrame
df = data.copy()
# Check for missing values
if df.isnull().sum().sum() > 0:
print("Handling missing values by filling with column mean.")
df.fillna(df.mean(), inplace=True)
# Feature Scaling
scaler = StandardScaler()
scaled_features = scaler.fit_transform(df)
# Initialize Isolation Forest
iso_forest = IsolationForest(n_estimators=100,
contamination=contamination,
random_state=random_state)
# Fit the model
iso_forest.fit(scaled_features)
# Predict anomalies
anomalies = iso_forest.predict(scaled_features)
# Add the anomaly predictions to the DataFrame
df['Anomaly'] = anomalies
# Optionally, you can map the anomaly labels to more interpretable values
# df['Anomaly'] = df['Anomaly'].map({1: 'Normal', -1: 'Anomaly'})
return df
# Example Usage:
if __name__ == "__main__":
# Sample column list provided by the user
columns = ['Voltage L1 min [V]', 'Voltage L1 avg [V]', 'Voltage L1 max [V]',
'Voltage L2 min [V]', 'Voltage L2 avg [V]', 'Voltage L2 max [V]',
'Voltage L3 min [V]', 'Voltage L3 avg [V]', 'Voltage L3 max [V]',
'Inverted Component [%]', 'Homopolar Component [%]',
'Current L1 avg [A]', 'Current L1 max [A]', 'Current L2 avg [A]',
'Current L2 max [A]', 'Current L3 avg [A]', 'Current L3 max [A]',
'Current LN avg [A]', 'Current LN max [A]', 'P L1 [kW]', 'P L2 [kW]',
'P L3 [kW]', 'Q L1 [kVar]', 'Q L2 [kVar]', 'Q L3 [kVar]', 'S L1 [kVA]',
'S L2 [kVA]', 'S L3 [kVA]', 'Cos phi L1', 'Cos phi L2', 'Cos phi L3',
'Frequency L1 min [Hz]', 'Frequency L1 avg [Hz]',
'Frequency L1 max [Hz]', 'Frequency L2 min [Hz]',
'Frequency L2 avg [Hz]', 'Frequency L2 max [Hz]',
'Frequency L3 min [Hz]', 'Frequency L3 avg [Hz]',
'Frequency L3 max [Hz]', 'THDS L1 max [%]', 'THDS L2 max [%]',
'THDS L3 max [%]', 'Harmonics L1 max [%]', 'Harmonics L2 max [%]',
'Harmonics L3 max [%]', 'EPC L1 [kWh]', 'EPC L2 [kWh]', 'EPC L3 [kWh]',
'EPP L1 [kWh]', 'EPP L2 [kWh]', 'EPP L3 [kWh]', 'EQC L1 [kVarh]',
'EQC L2 [kVarh]', 'EQC L3 [kVarh]', 'EQP L1 [kVarh]', 'EQP L2 [kVarh]',
'EQP L3 [kVarh]']
# Assuming you have a CSV file with the data
# df = pd.read_csv('power_grid_data.csv', usecols=columns)
# For demonstration, let's create a dummy DataFrame
import numpy as np
np.random.seed(42)
dummy_data = pd.DataFrame(np.random.randn(1000, len(columns)), columns=columns)
# Detect anomalies
result_df = detect_anomalies_power_grid(dummy_data, contamination=0.01)
# Display anomalies
anomalies = result_df[result_df['Anomaly'] == -1]
print(f"Number of anomalies detected: {len(anomalies)}")
print(anomalies)
Explanation of the Function
-
Function Parameters:
data: The input DataFrame containing all the mentioned power grid metrics.
contamination: Represents the expected proportion of anomalies in the dataset. Adjust this based on domain knowledge or expected anomaly rate.
random_state: Ensures reproducibility of results.
-
Handling Missing Values:
- The function checks for any missing values and fills them with the column mean. Depending on your dataset, you might choose other imputation strategies.
-
Feature Scaling:
StandardScaler is used to standardize features. This step is essential for algorithms like Isolation Forest to perform optimally.
-
Isolation Forest Setup:
n_estimators=100: The number of trees in the forest. More trees can lead to better performance but will increase computation time.
contamination: As defined by the user.
random_state: For reproducibility.
-
Anomaly Prediction:
- After fitting the model, each data point is assigned a label:
1 for normal and -1 for anomalies.
-
Result:
- The original DataFrame is returned with an additional
'Anomaly' column indicating the status of each data point.
Customization and Enhancements
-
Model Selection: While Isolation Forest is effective, you can experiment with other algorithms like One-Class SVM, Local Outlier Factor (LOF), or even deep learning-based methods like Autoencoders for potentially better results.
-
Parameter Tuning: Adjust n_estimators, contamination, and other hyperparameters using techniques like Grid Search or Random Search to optimize model performance.
-
Dimensionality Reduction: With a high number of features, applying PCA or other dimensionality reduction techniques before anomaly detection can improve performance and reduce computational overhead.
-
Time-Series Considerations: If the data is time-dependent, incorporating time-based features or using time-series specific anomaly detection methods (like ARIMA-based models or LSTM Autoencoders) might yield better results.
Final Notes
Anomaly detection in power grids is critical for identifying faults, ensuring reliability, and maintaining efficient operations. It's essential to validate the detected anomalies with domain experts to minimize false positives and negatives. Additionally, continuously updating and retraining the model with new data will help maintain its effectiveness over time.