Certainly! Let's improve the provided code for detecting outliers in salary data using a Gaussian Mixture Model (GMM). The improvements will include:
Data Preprocessing: Handle missing values, consider transformations for skewed data, and standardize the data.
Model Selection: Use the Bayesian Information Criterion (BIC) to determine the optimal number of components for the GMM.
Code Clarity: Add comments and structure the code for better readability.
Visualization: Include plots to help understand the data distribution and model selection.
Outlier Detection: Use clear thresholds and label outliers in the dataset.
Here's the improved code:
python
import numpy as np
import pandas as pd
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
# Ensure matplotlib plots display correctly
%matplotlib inline
# Copy the salary_data to avoid modifying the original dataset
salary_df = salary_data.copy()
# 1. Data Preprocessing
# Handle missing values in 'salary'
salary_df = salary_df.dropna(subset=['salary'])
# Apply a logarithmic transformation to handle skewness in salary data
salary_df['salary_log'] = np.log1p(salary_df['salary'])
# Standardize the log-transformed salary data
scaler = StandardScaler()
salary_df['salary_scaled'] = scaler.fit_transform(salary_df[['salary_log']])
# 2. Model Selection
# Determine the optimal number of components using BIC
bic_scores = []
n_components_range = range(1, 7) # Try models with 1 to 6 components
for n_components in n_components_range:
gmm = GaussianMixture(n_components=n_components, covariance_type='full', random_state=42)
gmm.fit(salary_df[['salary_scaled']])
bic_scores.append(gmm.bic(salary_df[['salary_scaled']]))
# Plot BIC scores to visualize the optimal number of components
plt.figure(figsize=(8, 4))
plt.plot(n_components_range, bic_scores, marker='o')
plt.xlabel('Number of Components')
plt.ylabel('BIC Score')
plt.title('BIC Scores for GMM with Different Numbers of Components')
plt.show()
# Select the number of components with the lowest BIC score
optimal_n_components = n_components_range[np.argmin(bic_scores)]
print(f"Optimal number of components according to BIC: {optimal_n_components}")
# 3. Fit the GMM Model
# Initialize the GMM with the optimal number of components
gmm = GaussianMixture(n_components=optimal_n_components, covariance_type='full', random_state=42)
# Fit the GMM to the standardized salary data
gmm.fit(salary_df[['salary_scaled']])
# 4. Compute Log-Likelihood Scores
# Calculate the log-likelihood of each sample
salary_df['gmm_score'] = gmm.score_samples(salary_df[['salary_scaled']])
# Visualize the distribution of log-likelihood scores
plt.figure(figsize=(8, 4))
plt.hist(salary_df['gmm_score'], bins=30, edgecolor='k')
plt.xlabel('Log-Likelihood Score')
plt.ylabel('Frequency')
plt.title('Distribution of GMM Log-Likelihood Scores')
plt.show()
# 5. Outlier Detection
# Define an outlier threshold (e.g., 5th percentile of the log-likelihood scores)
threshold = np.percentile(salary_df['gmm_score'], 5)
print(f"Outlier threshold (5th percentile of log-likelihood scores): {threshold:.2f}")
# Mark outliers based on the threshold
salary_df['is_outlier'] = salary_df['gmm_score'] < threshold
# Extract the outliers
outliers_gmm = salary_df[salary_df['is_outlier']]
# Show the detected outliers
print("Detected outliers:")
print(outliers_gmm.head())
# Optional: Visualize the outliers in the context of the salary distribution
plt.figure(figsize=(8, 4))
plt.hist(salary_df['salary'], bins=30, edgecolor='k', alpha=0.7, label='All Data')
plt.hist(outliers_gmm['salary'], bins=30, edgecolor='k', alpha=0.7, label='Outliers')
plt.xlabel('Salary')
plt.ylabel('Frequency')
plt.title('Salary Distribution with Outliers Highlighted')
plt.legend()
plt.show()
Explanation of Improvements:
Data Preprocessing:
Handling Missing Values: We drop any rows with missing values in the 'salary' column to avoid errors during model fitting.
Log Transformation: Salaries often have a right-skewed distribution. Applying a logarithmic transformation (np.log1p) helps in normalizing the distribution, which is beneficial for GMM.
Standardization: Standardizing the data ensures that it has a mean of 0 and a standard deviation of 1, which is important for algorithms like GMM that assume normalized data.
Model Selection:
Optimal Number of Components: Instead of assuming 2 clusters, we use the Bayesian Information Criterion (BIC) to select the optimal number of components for the GMM. We test models with 1 to 6 components and choose the one with the lowest BIC score.
Visualization: Plotting the BIC scores helps in visually assessing the optimal number of components.
Code Clarity:
Comments: Added comments to explain each step of the code.
Variable Naming: Used descriptive variable names for clarity.
Structured Code: Organized the code into logical sections for easier understanding.
Visualization:
Histogram of Log-Likelihood Scores: Helps in understanding the distribution of the scores and choosing an appropriate threshold.
Salary Distribution with Outliers Highlighted: Provides a visual representation of where the outliers lie within the overall salary distribution.
Outlier Detection:
Threshold Definition: Used the 5th percentile of the log-likelihood scores as the threshold for outlier detection.
Labeling Outliers: Added a new column 'is_outlier' to the DataFrame to flag outliers.
Note: Before running the improved code, ensure that all necessary libraries are installed and that salary_data is a pandas DataFrame containing a 'salary' column with numerical values.