File size: 4,550 Bytes
687bd84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import pandas as pd
import numpy as np
import joblib
from pathlib import Path
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report, confusion_matrix, f1_score, accuracy_score
import xgboost as xgb
import matplotlib.pyplot as plt
import seaborn as sns
import json

df = pd.read_csv('data/task_assignments.csv')

df['workload_ratio'] = df['total_story_points_assigned'] / 40
df['urgency_score'] = (31 - df['days_until_deadline']) / 30
df['capacity_indicator'] = (
    df['current_task_count'] / 8 * 0.4 + 
    df['task_switch_frequency'] / 10 * 0.3 +
    df['workload_ratio'] * 0.3
)
df['overtime_risk'] = (df['recent_overtime_hours'] / 20).clip(0, 1)
df['skill_deficit'] = (100 - df['skill_match_score']) / 100

le = LabelEncoder()
df['required_skill_encoded'] = le.fit_transform(df['required_skill'])

Path('models').mkdir(exist_ok=True)
joblib.dump(le, 'models/label_encoder.pkl')

feature_cols = [
    'current_task_count', 
    'avg_completion_time_days', 
    'skill_match_score',
    'total_story_points_assigned', 
    'recent_overtime_hours', 
    'task_switch_frequency', 
    'pr_review_pending', 
    'priority',
    'estimated_story_points', 
    'days_until_deadline', 
    'required_skill_encoded', 
    'has_dependencies', 
    'task_type',
    'team_size', 
    'sprint_days_remaining', 
    'team_avg_velocity',
    'workload_ratio', 
    'urgency_score', 
    'capacity_indicator',
    'overtime_risk',
    'skill_deficit'
]

X = df[feature_cols]
y = df['overload_risk']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

model = xgb.XGBClassifier(
    n_estimators=200,
    max_depth=6,
    learning_rate=0.1,
    subsample=0.8,
    colsample_bytree=0.8,
    objective='multi:softmax',
    num_class=3,
    random_state=42,
    eval_metric='mlogloss',
    tree_method='hist'
)

model.fit(X_train, y_train, verbose=False)

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(model, X_train, y_train, cv=cv, scoring='f1_weighted')

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
f1_weighted = f1_score(y_test, y_pred, average='weighted')

print(f"Accuracy: {accuracy:.4f}")
print(f"F1-Score: {f1_weighted:.4f}")
print(f"CV F1-Score: {cv_scores.mean():.4f} (+/- {cv_scores.std():.4f})")

target_names = ['Green (0)', 'Yellow (1)', 'Red (2)']
print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=target_names, digits=3))

print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred)
print(cm)

Path('results').mkdir(exist_ok=True)

plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', 
            xticklabels=target_names, yticklabels=target_names)
plt.title('Confusion Matrix')
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.tight_layout()
plt.savefig('results/confusion_matrix.png', dpi=150, bbox_inches='tight')
plt.close()

importance_df = pd.DataFrame({
    'feature': feature_cols,
    'importance': model.feature_importances_
}).sort_values('importance', ascending=False)

print("\nTop 10 Feature Importance:")
for idx, row in importance_df.head(10).iterrows():
    print(f"{row['feature']:30s} {row['importance']:.4f}")

importance_df.to_csv('results/feature_importance.csv', index=False)

plt.figure(figsize=(10, 6))
top_features = importance_df.head(15)
plt.barh(range(len(top_features)), top_features['importance'], color='steelblue')
plt.yticks(range(len(top_features)), top_features['feature'])
plt.xlabel('Importance Score')
plt.title('Top 15 Feature Importance')
plt.gca().invert_yaxis()
plt.tight_layout()
plt.savefig('results/feature_importance.png', dpi=150, bbox_inches='tight')
plt.close()

joblib.dump(model, 'models/xgboost_overload_classifier.pkl')

model_metadata = {
    'model_type': 'XGBoost Classifier',
    'n_estimators': 200,
    'max_depth': 6,
    'learning_rate': 0.1,
    'n_features': len(feature_cols),
    'n_classes': 3,
    'accuracy': float(accuracy),
    'f1_score': float(f1_weighted),
    'cv_mean': float(cv_scores.mean()),
    'cv_std': float(cv_scores.std()),
    'train_samples': len(X_train),
    'test_samples': len(X_test),
    'feature_names': feature_cols,
    'class_names': ['Green', 'Yellow', 'Red']
}

with open('models/model_metadata.json', 'w') as f:
    json.dump(model_metadata, f, indent=2)

print("\nTraining complete. Model saved.")