Python Implementation
Random Forest with Scikit-learn
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import matplotlib.pyplot as plt
import numpy as np
X, y = make_classification(n_samples=1000, n_features=20,
n_informative=15, n_redundant=5,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
rf_model = RandomForestClassifier(
n_estimators=100,
max_depth=10,
min_samples_split=5,
min_samples_leaf=2,
random_state=42
)
rf_model.fit(X_train, y_train)
y_pred = rf_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f'Random Forest Accuracy: {accuracy:.4f}')
feature_importance = rf_model.feature_importances_
print('\nTop 5 Feature Importances:')
for i in sorted(enumerate(feature_importance), key=lambda x: x[1], reverse=True)[:5]:
print(f'Feature {i[0]}: {i[1]:.4f}')
Gradient Boosting Implementation
from sklearn.ensemble import GradientBoostingClassifier
gb_model = GradientBoostingClassifier(
n_estimators=100,
learning_rate=0.1,
max_depth=3,
random_state=42
)
gb_model.fit(X_train, y_train)
gb_pred = gb_model.predict(X_test)
gb_accuracy = accuracy_score(y_test, gb_pred)
print(f'Gradient Boosting Accuracy: {gb_accuracy:.4f}')
print(f'\nComparison:')
print(f'Random Forest: {accuracy:.4f}')
print(f'Gradient Boosting: {gb_accuracy:.4f}')
Voting Classifier (Ensemble of Ensembles)
from sklearn.ensemble import VotingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
dt_model = DecisionTreeClassifier(random_state=42)
svm_model = SVC(probability=True, random_state=42)
lr_model = LogisticRegression(random_state=42)
voting_model = VotingClassifier(
estimators=[
('dt', dt_model),
('svm', svm_model),
('lr', lr_model)
],
voting='soft'
)
voting_model.fit(X_train, y_train)
voting_pred = voting_model.predict(X_test)
voting_accuracy = accuracy_score(y_test, voting_pred)
print(f'Voting Classifier Accuracy: {voting_accuracy:.4f}')
print(f'\nModel Comparison:')
print(f'Decision Tree: {accuracy_score(y_test, dt_model.predict(X_test)):.4f}')
print(f'SVM: {accuracy_score(y_test, svm_model.predict(X_test)):.4f}')
print(f'Logistic Regression: {accuracy_score(y_test, lr_model.predict(X_test)):.4f}')
print(f'Voting Classifier: {voting_accuracy:.4f}')
Real-World Application
Credit Risk Assessment with Ensemble Methods
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
data = {
'age': np.random.randint(18, 80, 1000),
'income': np.random.randint(20000, 200000, 1000),
'credit_score': np.random.randint(300, 850, 1000),
'debt_to_income': np.random.uniform(0, 1, 1000),
'loan_amount': np.random.randint(5000, 100000, 1000),
'employment_years': np.random.randint(0, 40, 1000)
}
risk_score = (
(850 - data['credit_score']) / 850 * 0.4 +
data['debt_to_income'] * 0.3 +
(40 - data['employment_years']) / 40 * 0.2 +
np.random.uniform(0, 0.1, 1000)
)
data['default_risk'] = (risk_score > 0.5).astype(int)
df = pd.DataFrame(data)
X = df.drop('default_risk', axis=1)
y = df['default_risk']
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
credit_risk_model = RandomForestClassifier(
n_estimators=200,
max_depth=15,
min_samples_split=10,
random_state=42
)
cv_scores = cross_val_score(credit_risk_model, X_scaled, y, cv=5, scoring='accuracy')
print('Credit Risk Model Performance:')
print(f'Cross-validation scores: {cv_scores}')
print(f'Mean accuracy: {cv_scores.mean():.4f} (+/- {cv_scores.std() * 2:.4f})')
credit_risk_model.fit(X_scaled, y)
feature_names = X.columns
importances = credit_risk_model.feature_importances_
print('\nFeature Importance for Credit Risk:')
for name, importance in sorted(zip(feature_names, importances), key=lambda x: x[1], reverse=True):
print(f'{name}: {importance:.4f}')