Yes, anomaly detection is an effective AI approach for identifying weak points in your intersection pressure data. By treating unusual patterns or outliers in the data as potential weak points, you can leverage various anomaly detection algorithms to automatically identify these critical intersections.
Below, I'll guide you through integrating an anomaly detection method into your existing WeakPointDetector class. We'll use the Isolation Forest algorithm from scikit-learn, which is well-suited for detecting anomalies in high-dimensional datasets.
Step-by-Step Integration
-
Data Preparation: Ensure your data is in a suitable format for anomaly detection. This usually involves numerical features, so your intersection pressure data fits well.
-
Choose an Anomaly Detection Model: We'll use Isolation Forest, but other options include One-Class SVM, DBSCAN, or Autoencoders.
-
Fit the Model: Train the model on your data to learn the normal behavior.
-
Detect Anomalies: Use the trained model to predict anomalies.
-
Integrate Results: Update the identify_weak_points method to use the anomaly scores for identifying weak points.
Updated WeakPointDetector Class with Anomaly Detection
Here's the updated class incorporating the Isolation Forest algorithm for anomaly detection:
import json
import os
from typing import List, Dict
import pandas as pd
import sys
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
# Append the parent directory to the system path to allow importing from core
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
class WeakPointDetector:
def __init__(self, intersection_pressure_path: str):
self.intersection_pressure_path = intersection_pressure_path
self.intersections = set()
self.intersection_pressure_data = {}
def parse_log_file(self, file_path: str) -> List[Dict[str, float]]:
"""
Parses a log file and returns a list of dictionaries containing the data
from the specified epoch type (e.g., "TEST") for the last epoch.
"""
data = []
with open(file_path, 'r') as file:
lines = file.readlines()
# Filter lines for the specified epoch type
filtered_lines = [line for line in lines if line.split()[1].lower() == "test"]
print(f"Filtered Lines: {filtered_lines}")
# Get the last epoch
last_epoch_num = None
last_epoch_lines = []
for line in reversed(filtered_lines):
parts = line.strip().split('\t')
if len(parts) >= 4:
epoch_num = parts[2]
if last_epoch_num is None:
last_epoch_num = epoch_num
if epoch_num == last_epoch_num:
last_epoch_lines.insert(0, line) # Maintain original order
else:
break
for line in last_epoch_lines:
parts = line.strip().split('\t')
if len(parts) >= 4:
json_str = parts[3]
try:
json_data = json.loads(json_str)
data.append(json_data)
# Extract intersection IDs
for key in json_data.keys():
intersection_id = key.split('_')[0] if '_' in key else key
self.intersections.add(intersection_id)
except json.JSONDecodeError:
print(f"Failed to decode JSON for line: {line}")
return data
def aggregate_data(self):
"""
Aggregates intersection pressure data for the last epoch.
"""
# Aggregate Intersection Pressure Data
intersection_pressure = self.parse_log_file(self.intersection_pressure_path)
for entry in intersection_pressure:
for key, value in entry.items():
self.intersection_pressure_data[key] = self.intersection_pressure_data.get(key, 0) + abs(value)
def compute_performance_metric(self) -> pd.DataFrame:
"""
Prepares the data for anomaly detection by creating a DataFrame.
"""
data = []
for intersection in self.intersections:
intersection_pressure = self.intersection_pressure_data.get(intersection, 0)
data.append({
'Intersection': intersection,
'Intersection_Pressure': intersection_pressure
})
df = pd.DataFrame(data)
return df
def identify_weak_points(self, contamination: float = 0.05) -> pd.DataFrame:
"""
Identifies weak points using anomaly detection (Isolation Forest).
Parameters:
- contamination: The proportion of anomalies in the data set.
Returns:
- A DataFrame containing the weak points identified as anomalies.
"""
self.aggregate_data()
df = self.compute_performance_metric()
# Features for anomaly detection
X = df[['Intersection_Pressure']].values # Add more features if available
# Standardize the data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Initialize Isolation Forest
iso_forest = IsolationForest(
n_estimators=100,
contamination=contamination,
random_state=42
)
# Fit the model
iso_forest.fit(X_scaled)
# Predict anomalies
df['Anomaly_Score'] = iso_forest.decision_function(X_scaled)
df['Anomaly'] = iso_forest.predict(X_scaled)
# In Isolation Forest, anomalies are marked as -1
weak_points = df[df['Anomaly'] == -1].sort_values(by='Anomaly_Score')
return weak_points
if __name__ == "__main__":
# Define paths to the log files
intersection_pressure_log = "workspace/data/output_data/tsc/cityflow_colight/cityflow_grid4x4/test/logger/2024_10_01-08_40_50_PRESSURE.log"
detector = WeakPointDetector(intersection_pressure_log)
# Set contamination to 5%, adjust based on your data
weak_points_df = detector.identify_weak_points(contamination=0.05)
# Save the weak points to a CSV file
output_path = "workspace/data/output_data/tsc/cityflow_colight/cityflow_grid4x4/test/logger/weak_points.csv"
weak_points_df.to_csv(output_path, index=False)
print(f"Weak points saved to {output_path}")
print(weak_points_df)
Detailed Explanation
1. Data Aggregation and Preparation
-
aggregate_data Method: Parses the log file and aggregates the intersection pressure data.
-
compute_performance_metric Method: Constructs a DataFrame with each intersection and its corresponding pressure. This DataFrame serves as the input for the anomaly detection model.
2. Anomaly Detection with Isolation Forest
-
Feature Selection: Currently, only Intersection_Pressure is used. If you have additional relevant features (e.g., queue length, lane pressure), include them to improve detection accuracy.
-
Data Scaling: The StandardScaler standardizes features by removing the mean and scaling to unit variance. This step is crucial for algorithms like Isolation Forest that are sensitive to feature scaling.
-
Model Initialization:
n_estimators=100: Number of base estimators in the ensemble. More trees can improve performance but increase computation time.
contamination=0.05: The proportion of expected anomalies. Adjust this based on domain knowledge. For example, if you expect 5% of intersections to be weak points, set contamination to 0.05.
random_state=42: Ensures reproducibility.
-
Model Training and Prediction:
fit: Trains the Isolation Forest on the scaled data.
decision_function: Provides anomaly scores. Lower scores indicate more abnormal instances.
predict: Labels each instance as normal (1) or anomaly (-1).
3. Identifying Weak Points
-
Filtering Anomalies: After prediction, filter the DataFrame to include only those intersections labeled as anomalies (Anomaly == -1).
-
Sorting: Sort the weak points by their anomaly scores to prioritize the most significant anomalies.
4. Output
Customization and Enhancements
-
Adjusting Contamination:
- The
contamination parameter defines the proportion of data points expected to be anomalies. If you have prior knowledge about the percentage of weak points, set this accordingly.
- Alternatively, you can set
contamination='auto' in recent versions of scikit-learn to let the model determine it, but specifying it can offer more control.
-
Including More Features:
- If available, incorporate additional features such as queue lengths, lane pressures, or temporal data to enrich the model’s input.
- This can help the model detect more nuanced anomalies.
-
Model Selection:
- Experiment with different anomaly detection algorithms to see which performs best for your data.
- For example, One-Class SVM or Local Outlier Factor (LOF) are alternatives that might capture different aspects of anomalies.
-
Hyperparameter Tuning:
- Optimize hyperparameters like
n_estimators, max_samples, or max_features for Isolation Forest to improve performance.
- Use cross-validation techniques or grid search for systematic tuning.
-
Visualization:
- Visualize the anomaly scores or the distribution of intersection pressures to better understand the anomalies.
- Plotting can help in verifying if the identified weak points make sense from a domain perspective.
Example of Adding More Features
If you decide to include additional features like Lane_Pressure and Queue_Length, update the compute_performance_metric method and the features used for anomaly detection:
def compute_performance_metric(self) -> pd.DataFrame:
"""
Prepares the data for anomaly detection by creating a DataFrame with multiple features.
"""
data = []
for intersection in self.intersections:
intersection_pressure = self.intersection_pressure_data.get(intersection, 0)
# Assume you have methods to get lane_pressure and queue_length
lane_pressure = self.lane_pressure_data.get(intersection, 0)
queue_length = self.queue_data.get(intersection, 0)
data.append({
'Intersection': intersection,
'Intersection_Pressure': intersection_pressure,
'Lane_Pressure': lane_pressure,
'Queue_Length': queue_length
})
df = pd.DataFrame(data)
return df
And then adjust the feature selection in identify_weak_points:
X = df[['Intersection_Pressure', 'Lane_Pressure', 'Queue_Length']].values
Ensure that you have the corresponding data aggregated in aggregate_data.
Conclusion
By integrating anomaly detection into your WeakPointDetector class, you can automatically identify intersections that behave unusually, indicating potential weak points. The Isolation Forest algorithm provides a robust and scalable method for this purpose. Adjust the parameters and features based on your specific data and requirements to achieve optimal results.
If you have further questions or need assistance with specific parts of the implementation, feel free to ask!