Certainly! Below is a step-by-step Python code example demonstrating anomaly detection on your dataframe using the Isolation Forest algorithm. It includes data preprocessing, training the Isolation Forest, saving the model, and then loading it back for inference on new data.
Steps
- Prepare data: Convert categorical data to numerical (one-hot encoding or label encoding).
- Fit Isolation Forest model.
- Save model using
joblib.
- Load model and predict anomalies on new data.
Code example
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import LabelEncoder
import joblib
# 1. Prepare your data
data = {
'pid': [1, 1, 2, 3, 4, 5],
'degree': ['MMBS', 'MD', 'NSC', 'MBBS', 'MID', 'MIDL'],
'board': ['American Medical Board', 'American Medical Board', 'Chiness Board', None, 'Maly Board', 'Germany Board'],
'university': ['Medical Health University', 'Medical Health University', 'Bejing Univ', 'Tokoyo University', 'Jakartha University', 'Berlin Unv'],
'certificateNumber': ['M1234', 'G4564', 'C12SD001', None, 'JK1234', 'GB789'],
'issuedate': ['2001-06-01', '1989-06-01', '2022-02-05', '2015-05-15', '2022-09-15', '2000-06-15']
}
df = pd.DataFrame(data)
# Convert 'issuedate' to datetime and extract useful features (year, month, day)
df['issuedate'] = pd.to_datetime(df['issuedate'], errors='coerce')
df['issue_year'] = df['issuedate'].dt.year
df['issue_month'] = df['issuedate'].dt.month
df['issue_day'] = df['issuedate'].dt.day
# For categorical columns, fill missing values with a placeholder
df['board'] = df['board'].fillna('Unknown')
df['university'] = df['university'].fillna('Unknown')
df['certificateNumber'] = df['certificateNumber'].fillna('Unknown')
df['degree'] = df['degree'].fillna('Unknown')
# Label encode categorical variables (you can use OneHotEncoder but label encoding is simpler here)
label_encoders = {}
categorical_cols = ['degree', 'board', 'university', 'certificateNumber']
for col in categorical_cols:
le = LabelEncoder()
df[col] = le.fit_transform(df[col])
label_encoders[col] = le # save encoder for inference later
# Select features for Isolation Forest
features = ['degree', 'board', 'university', 'certificateNumber', 'issue_year', 'issue_month', 'issue_day']
X = df[features]
# 2. Train Isolation Forest
iso_forest = IsolationForest(contamination=0.2, random_state=42)
iso_forest.fit(X)
# Add anomaly score and prediction
df['anomaly_score'] = iso_forest.decision_function(X)
df['anomaly'] = iso_forest.predict(X) # -1 for anomaly, 1 for normal
print(df[['pid', 'anomaly_score', 'anomaly']])
# 3. Save model and label encoders
joblib.dump(iso_forest, 'isolation_forest_model.joblib')
joblib.dump(label_encoders, 'label_encoders.joblib')
# ---- Later or in new script file for inference ----
# Example new incoming data for inference
new_data = {
'pid': [6, 7],
'degree': ['MD', 'MIDL'],
'board': ['American Medical Board', 'Germany Board'],
'university': ['Medical Health University', 'Berlin Unv'],
'certificateNumber': ['M9999', 'GB123'],
'issuedate': ['2023-01-01', '2005-07-30']
}
new_df = pd.DataFrame(new_data)
new_df['issuedate'] = pd.to_datetime(new_df['issuedate'], errors='coerce')
new_df['issue_year'] = new_df['issuedate'].dt.year
new_df['issue_month'] = new_df['issuedate'].dt.month
new_df['issue_day'] = new_df['issuedate'].dt.day
new_df['board'] = new_df['board'].fillna('Unknown')
new_df['university'] = new_df['university'].fillna('Unknown')
new_df['certificateNumber'] = new_df['certificateNumber'].fillna('Unknown')
new_df['degree'] = new_df['degree'].fillna('Unknown')
# Load model and label encoders
loaded_iso_forest = joblib.load('isolation_forest_model.joblib')
loaded_label_encoders = joblib.load('label_encoders.joblib')
# Apply label encoding using loaded encoders (handle unseen labels by assigning a default)
for col in categorical_cols:
le = loaded_label_encoders[col]
# Map new data, if label not seen during training assign -1 or a default
new_df[col] = new_df[col].map(lambda s: le.transform([s])[0] if s in le.classes_ else -1)
# Prepare inference features
new_X = new_df[features]
# Predict
new_df['anomaly_score'] = loaded_iso_forest.decision_function(new_X)
new_df['anomaly'] = loaded_iso_forest.predict(new_X)
print(new_df[['pid', 'anomaly_score', 'anomaly']])
Explanation:
- Preprocessing: We convert dates into numeric features because Isolation Forest needs numeric input.
- Label Encoding: Used on categorical variables for model use and consistency between training and inference.
- Isolation Forest: Trained on prepared features, contamination rate set (adjust based on expected anomalies).
- Persistence: Model and encoders saved with
joblib.
- Inference: New data is preprocessed similarly, encoded with saved encoders (note unseen categories handled).
- Outcome: -1 prediction indicates anomaly; 1 indicates normal.
Let me know if you need help adjusting the code or working with different preprocessing!