import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
from sklearn.tree import DecisionTreeRegressor, plot_tree, export_graphviz
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
import graphviz
import os
Check if graphviz is installed
if not os.system("dot -V"):
print("Graphviz is installed correctly.")
else:
print("Please install Graphviz from https://graphviz.org/download/")
Creating a dummy target variable for demonstration
df[target] = np.random.rand(len(df)) * 1000 # You should replace this with your actual target data
feature_columns = [
'2012',
'IRSD (avg)',
'population',
'Personal income <$400/week, persons',
'Number of families',
'Female-headed lone parent families',
'Male-headed lone parent families',
'Holds degree or higher, persons',
'Did not complete year 12, persons'
]
categorical_features = [col for col in df.columns if 'Region_' in col]
feature_columns.extend(categorical_features)
Check if all selected features are available
available_features = [col for col in feature_columns if col in df.columns]
if len(available_features) != len(feature_columns):
missing_features = list(set(feature_columns) - set(available_features))
print(f"Warning: The following features are missing and will be ignored: {missing_features}")
Adjust the feature set accordingly
X = df[available_features]
y = df[target]
Handle Missing Values
X = X.fillna(X.median())
y = y.fillna(y.median())
d. Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
plt.figure(figsize=(20, 10))
plot_tree(dt_regressor, feature_names=available_features, filled=True, rounded=True, fontsize=12)
plt.title("Decision Tree for EGM Expenditure per Capita")
plt.show()
Optional: Enhanced Visualization with Graphviz
dot_data = export_graphviz(dt_regressor, out_file=None, feature_names=available_features, filled=True, rounded=True, special_characters=True)
graph = graphviz.Source(dot_data)
output_file = "decision_tree_egm_expenditure"
try:
graph.render(output_file, format="png", cleanup=True)
print(f"\nDecision Tree visualization saved as '{output_file}.png'.")
except Exception as e:
print(f"Error in rendering the graphviz tree: {e}")
Decision Tree MSE: 95708.43
Decision Tree R² Score: -0.68
Feature Importances:
Feature Importance
0 2012 0.347439
7 Holds degree or higher, persons 0.232138
1 IRSD (avg) 0.203325
6 Male-headed lone parent families 0.113497
4 Number of families 0.103601
2 population 0.000000
3 Personal income <$400/week, persons 0.000000
5 Female-headed lone parent families 0.000000
8 Did not complete year 12, persons 0.000000
9 Region_M 0.000000
Error in rendering the graphviz tree: failed to execute PosixPath('dot'), make sure the Graphviz executables are on your systems' PATH
Best Parameters from Grid Search:
{'max_depth': 3, 'min_samples_leaf': 1, 'min_samples_split': 2}
Random Forest MSE: 71256.23
Random Forest R² Score: -0.25
Note that each of the above features should have an importance, so improve the decision tree so that it captures all the features to the appropriate extent
It appears that your Decision Tree model is not utilizing all the available features, as evidenced by several features having zero importance. This situation can arise due to restrictive hyperparameters that limit the tree's ability to create splits based on all features. To address this, you can adjust the Decision Tree's hyperparameters to make the model more flexible and capable of capturing the influence of all features.
Here are several steps and recommendations to improve your Decision Tree model:
Adjust Hyperparameters:
Increase max_depth: A deeper tree can capture more intricate patterns in the data, allowing it to consider more features.
Decrease min_samples_split and min_samples_leaf: Lowering these values allows the tree to make splits even with fewer samples, potentially incorporating more features.
Remove Restrictions Temporarily: Start by removing constraints like max_depth to see if the tree starts utilizing all features, then fine-tune from there.
Feature Engineering and Selection:
Check for Multicollinearity: Highly correlated features can confuse the tree, causing it to prefer one over the other. Consider removing or combining correlated features.
Ensure Feature Variance: Features with little to no variance provide minimal information and might be excluded by the tree.
Use Ensemble Methods:
Random Forests: They can capture feature importance more robustly by averaging across multiple trees.
Gradient Boosting Machines: These can also provide better performance and feature utilization.
Evaluate Data Quality:
Ensure Proper Target Variable: Make sure your target variable is meaningful and correctly represents what you're trying to predict.
Handle Missing Values Appropriately: Ensure that missing values are handled in a way that doesn't bias the model.
Visualize and Interpret the Tree:
Use Built-In Plotting Tools: Even without Graphviz, you can use matplotlib's plot_tree to visualize the tree structure.
Review the Tree Structure: Understanding how the tree splits can provide insights into feature importance and model behavior.
Below is an updated version of your code incorporating these recommendations:
python
Detailed Explanations and Recommendations
Removing Restrictions on Tree Growth:
max_depth=None: Allows the tree to expand until all leaves are pure or contain fewer than min_samples_split samples.
min_samples_split=2 and min_samples_leaf=1: Ensures that the tree can make splits even with the smallest number of samples, allowing it to consider more features.
Enhanced Hyperparameter Tuning:
Expanded the param_grid to include max_features, which controls the number of features considered for splitting. This can help the tree explore different feature subsets.
Including max_depth=None in the grid ensures that the grid search evaluates the unrestricted tree as well.
Using GridSearchCV to Find Optimal Parameters:
After finding the best parameters, the model is retrained using these parameters to achieve better performance.
This step ensures that the Decision Tree is optimally configured to utilize all relevant features.
Cross-Validation:
Provides a more reliable estimate of the model's performance by evaluating it across multiple folds.
Ensures that the model generalizes well to unseen data.
Ensemble Methods:
Random Forests are less prone to overfitting and can capture feature importances more effectively by averaging across multiple trees.
They often provide better performance and robustness compared to a single Decision Tree.
Visualization:
plot_tree: Allows you to visualize the structure of the Decision Tree directly within matplotlib.
Feature Importance Plots: Helps in understanding which features contribute most to the predictions.
Data Validation:
Ensure that your target variable is not synthetic (random data) when training the model. Replace the dummy target with your actual EGM expenditure per capita data to get meaningful results.
Verify that all preprocessing steps are correctly applied and that no unintended data leakage occurs.
Addressing Graphviz Issues
The error message indicates that Graphviz is not installed or not added to your system's PATH. To resolve this:
Install Graphviz:
macOS: Use Homebrew:
bash
brew install graphviz
Windows: Download the installer from Graphviz Downloads and follow the installation instructions.
Linux: Use package managers like apt:
bash
sudo apt-get install graphviz
Add Graphviz to PATH:
Ensure that the Graphviz bin directory is added to your system's PATH environment variable so that executables like dot are accessible from the command line.
Verify Installation:
Run the following command in your terminal or command prompt to confirm:
bash
dot -V
This should display the Graphviz version if installed correctly.
Final Tips
Evaluate Model Performance Properly: Negative R² scores indicate that the model performs worse than a simple mean predictor. This suggests issues with model configuration, data quality, or signal-to-noise ratio in the data.
Explore Data Further: Investigate the relationships between features and the target variable using exploratory data analysis (EDA) techniques. Visualizations like scatter plots, correlation matrices, and box plots can provide valuable insights.
Consider Alternative Models: If Decision Trees and Random Forests are not yielding satisfactory results, exploring other regression models like Gradient Boosting Machines (e.g., XGBoost, LightGBM) or even linear models with regularization could be beneficial.
By implementing these adjustments and thoroughly evaluating your data and models, you should be able to create a more effective Decision Tree model that utilizes all relevant features appropriately.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
from sklearn.tree import DecisionTreeRegressor, plot_tree
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.ensemble import RandomForestRegressor
import matplotlib.pyplot as plt
import os
# Check if graphviz is installed
if not os.system("dot -V"):
print("Graphviz is installed correctly.")
else:
print("Please install Graphviz from https://graphviz.org/download/")
# a. Load the Dataset
data_path = '/Users/rahulkulkarni/Downloads/Data/merged.csv'
df = pd.read_csv(data_path)
print("Initial Data:")
print(df.head())
# b. Data Preprocessing
df = df.drop(['LGA Name', 'LGA'], axis=1, errors='ignore')
df = pd.get_dummies(df, columns=['Region'], drop_first=True)
print("\nData after preprocessing:")
print(df.head())
# c. Select Features and Target
target = 'EGM expenditure per capita'
# Ensure you have the actual target variable in your dataset
if target not in df.columns:
print(f"\nTarget variable '{target}' not found in the dataset. Creating a dummy target for demonstration.")
df[target] = np.random.rand(len(df)) * 1000 # Replace with actual target data
feature_columns = [
'2012',
'IRSD (avg)',
'population',
'Personal income <$400/week, persons',
'Number of families',
'Female-headed lone parent families',
'Male-headed lone parent families',
'Holds degree or higher, persons',
'Did not complete year 12, persons'
]
categorical_features = [col for col in df.columns if 'Region_' in col]
feature_columns.extend(categorical_features)
# Check if all selected features are available
available_features = [col for col in feature_columns if col in df.columns]
if len(available_features) != len(feature_columns):
missing_features = list(set(feature_columns) - set(available_features))
print(f"Warning: The following features are missing and will be ignored: {missing_features}")
# Adjust the feature set accordingly
X = df[available_features]
y = df[target]
# Handle Missing Values
X = X.fillna(X.median())
y = y.fillna(y.median())
# d. Split the Dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# e. Train the Decision Tree Model with Adjusted Hyperparameters
dt_regressor = DecisionTreeRegressor(
random_state=42,
max_depth=None, # Remove depth limitation
min_samples_split=2, # Reduce the minimum samples required to split
min_samples_leaf=1 # Reduce the minimum samples required at a leaf node
)
dt_regressor.fit(X_train, y_train)
# f. Make Predictions and Evaluate
y_pred = dt_regressor.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"\nDecision Tree MSE: {mse:.2f}")
print(f"Decision Tree R² Score: {r2:.2f}")
# g. Feature Importance
importances = dt_regressor.feature_importances_
feature_importances = pd.DataFrame({
'Feature': available_features,
'Importance': importances
}).sort_values(by='Importance', ascending=False)
print("\nFeature Importances:")
print(feature_importances)
# h. Visualize the Decision Tree
plt.figure(figsize=(20, 10))
plot_tree(dt_regressor, feature_names=available_features, filled=True, rounded=True, fontsize=10)
plt.title("Decision Tree for EGM Expenditure per Capita")
plt.show()
# i. Hyperparameter Tuning (Enhanced)
param_grid = {
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10],
'min_samples_leaf': [1, 2, 4],
'max_features': ['auto', 'sqrt', 'log2', None]
}
grid_search = GridSearchCV(
estimator=DecisionTreeRegressor(random_state=42),
param_grid=param_grid,
cv=5,
scoring='r2',
n_jobs=-1
)
grid_search.fit(X_train, y_train)
print("\nBest Parameters from Grid Search:")
print(grid_search.best_params_)
# Train a Decision Tree with Best Parameters
best_dt = grid_search.best_estimator_
best_dt.fit(X_train, y_train)
y_pred_best = best_dt.predict(X_test)
mse_best = mean_squared_error(y_test, y_pred_best)
r2_best = r2_score(y_test, y_pred_best)
print(f"\nBest Decision Tree MSE: {mse_best:.2f}")
print(f"Best Decision Tree R² Score: {r2_best:.2f}")
# j. Cross-Validation
cv_scores = cross_val_score(best_dt, X_train, y_train, cv=5, scoring='r2')
print(f"\nCross-Validation R² Scores: {cv_scores}")
print(f"Average CV R² Score: {cv_scores.mean():.2f}")
# k. Ensemble Method: Random Forest (Optional)
rf_regressor = RandomForestRegressor(
n_estimators=100,
random_state=42,
max_depth=None, # Allow trees to grow without depth limitation
min_samples_split=2,
min_samples_leaf=1,
max_features='auto'
)
rf_regressor.fit(X_train, y_train)
y_pred_rf = rf_regressor.predict(X_test)
mse_rf = mean_squared_error(y_test, y_pred_rf)
r2_rf = r2_score(y_test, y_pred_rf)
print(f"\nRandom Forest MSE: {mse_rf:.2f}")
print(f"Random Forest R² Score: {r2_rf:.2f}")
# Feature Importance for Random Forest
rf_importances = rf_regressor.feature_importances_
rf_feature_importances = pd.DataFrame({
'Feature': available_features,
'Importance': rf_importances
}).sort_values(by='Importance', ascending=False)
print("\nRandom Forest Feature Importances:")
print(rf_feature_importances)
# Visualize Random Forest Feature Importances
plt.figure(figsize=(10, 8))
plt.barh(rf_feature_importances['Feature'], rf_feature_importances['Importance'])
plt.xlabel('Importance')
plt.title('Random Forest Feature Importances')
plt.gca().invert_yaxis()
plt.show()