muthuk1 commited on
Commit
53c7569
·
verified ·
1 Parent(s): 232e073

Upload training/train_models.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. training/train_models.py +323 -0
training/train_models.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ALWAS ML Models — Train and evaluate all 3 models:
3
+ 1. Hours Estimation (XGBoost Regressor)
4
+ 2. Complexity Classification (XGBoost + LightGBM Ensemble)
5
+ 3. Bottleneck Risk Prediction (Gradient Boosting Classifier)
6
+ """
7
+ import numpy as np
8
+ import pandas as pd
9
+ import json
10
+ import joblib
11
+ import os
12
+ from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
13
+ from sklearn.preprocessing import LabelEncoder, OrdinalEncoder
14
+ from sklearn.metrics import (
15
+ mean_absolute_error, mean_squared_error, r2_score,
16
+ classification_report, confusion_matrix, accuracy_score,
17
+ f1_score, roc_auc_score
18
+ )
19
+ from sklearn.calibration import CalibratedClassifierCV
20
+ import xgboost as xgb
21
+ import lightgbm as lgb
22
+
23
+ # === Load Data ===
24
+ print("=" * 60)
25
+ print("ALWAS ML MODEL TRAINING")
26
+ print("=" * 60)
27
+
28
+ df = pd.read_csv('/app/alwas_blocks_dataset.csv')
29
+ print(f"\nLoaded {len(df)} blocks ({df['is_completed'].sum()} completed, {(~df['is_completed'].astype(bool)).sum()} in-progress)")
30
+
31
+ # === Feature Engineering ===
32
+ print("\n--- Feature Engineering ---")
33
+
34
+ # Encode categoricals
35
+ tech_node_encoder = LabelEncoder()
36
+ block_type_encoder = LabelEncoder()
37
+ priority_encoder = OrdinalEncoder(categories=[['P4-Low', 'P3-Medium', 'P2-High', 'P1-Critical']])
38
+ engineer_encoder = LabelEncoder()
39
+
40
+ df['tech_node_encoded'] = tech_node_encoder.fit_transform(df['tech_node'])
41
+ df['block_type_encoded'] = block_type_encoder.fit_transform(df['block_type'])
42
+ df['priority_encoded'] = priority_encoder.fit_transform(df[['priority']]).astype(int).flatten()
43
+ df['engineer_encoded'] = engineer_encoder.fit_transform(df['engineer_id'])
44
+
45
+ # Create interaction features
46
+ df['type_node_interaction'] = df['tech_node_encoded'] * 10 + df['block_type_encoded']
47
+ df['complexity_score'] = df['constraint_complexity'] * df['transistor_count_log']
48
+ df['size_priority_interaction'] = df['transistor_count_log'] * df['priority_numeric']
49
+
50
+ # Encode targets early so slices have them
51
+ complexity_encoder = LabelEncoder()
52
+ df['complexity_encoded'] = complexity_encoder.fit_transform(df['complexity'])
53
+ bottleneck_encoder = LabelEncoder()
54
+ df['bottleneck_encoded'] = bottleneck_encoder.fit_transform(df['bottleneck_risk'])
55
+
56
+ # === MODEL 1: Hours Estimation ===
57
+ print("\n" + "=" * 60)
58
+ print("MODEL 1: Hours Estimation (XGBoost Regressor)")
59
+ print("=" * 60)
60
+
61
+ # Use completed blocks for training hours estimation
62
+ completed = df[df['is_completed'] == 1].copy()
63
+
64
+ HOURS_FEATURES = [
65
+ 'tech_node_encoded', 'block_type_encoded', 'priority_encoded',
66
+ 'transistor_count', 'transistor_count_log', 'has_dependencies',
67
+ 'num_dependencies', 'constraint_complexity', 'drc_iterations',
68
+ 'engineer_skill_factor', 'type_node_interaction', 'complexity_score',
69
+ 'size_priority_interaction'
70
+ ]
71
+
72
+ X_hours = completed[HOURS_FEATURES]
73
+ y_hours = completed['actual_hours']
74
+
75
+ X_train_h, X_test_h, y_train_h, y_test_h = train_test_split(
76
+ X_hours, y_hours, test_size=0.2, random_state=42
77
+ )
78
+
79
+ # XGBoost model
80
+ hours_model = xgb.XGBRegressor(
81
+ n_estimators=500,
82
+ learning_rate=0.05,
83
+ max_depth=7,
84
+ subsample=0.8,
85
+ colsample_bytree=0.8,
86
+ min_child_weight=3,
87
+ reg_alpha=0.1,
88
+ reg_lambda=1.0,
89
+ objective='reg:squarederror',
90
+ tree_method='hist',
91
+ random_state=42,
92
+ early_stopping_rounds=50,
93
+ )
94
+ hours_model.fit(
95
+ X_train_h, y_train_h,
96
+ eval_set=[(X_test_h, y_test_h)],
97
+ verbose=False
98
+ )
99
+
100
+ # Evaluate
101
+ y_pred_h = hours_model.predict(X_test_h)
102
+ mae = mean_absolute_error(y_test_h, y_pred_h)
103
+ rmse = np.sqrt(mean_squared_error(y_test_h, y_pred_h))
104
+ r2 = r2_score(y_test_h, y_pred_h)
105
+ mape = np.mean(np.abs((y_test_h - y_pred_h) / y_test_h)) * 100
106
+
107
+ print(f"\nHours Estimation Results:")
108
+ print(f" MAE: {mae:.2f} hours")
109
+ print(f" RMSE: {rmse:.2f} hours")
110
+ print(f" R²: {r2:.4f}")
111
+ print(f" MAPE: {mape:.1f}%")
112
+
113
+ # Feature importance
114
+ importance = pd.DataFrame({
115
+ 'feature': HOURS_FEATURES,
116
+ 'importance': hours_model.feature_importances_
117
+ }).sort_values('importance', ascending=False)
118
+ print(f"\nTop features for hours estimation:")
119
+ print(importance.to_string(index=False))
120
+
121
+ # Cross-validation
122
+ cv_scores = cross_val_score(
123
+ xgb.XGBRegressor(n_estimators=500, learning_rate=0.05, max_depth=7,
124
+ subsample=0.8, colsample_bytree=0.8, tree_method='hist', random_state=42),
125
+ X_hours, y_hours, cv=5, scoring='r2'
126
+ )
127
+ print(f"\n5-Fold CV R²: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
128
+
129
+ # === MODEL 2: Complexity Classification ===
130
+ print("\n" + "=" * 60)
131
+ print("MODEL 2: Complexity Classification (XGBoost + LightGBM Ensemble)")
132
+ print("=" * 60)
133
+
134
+ COMPLEXITY_FEATURES = [
135
+ 'tech_node_encoded', 'block_type_encoded', 'priority_encoded',
136
+ 'transistor_count', 'transistor_count_log', 'has_dependencies',
137
+ 'num_dependencies', 'constraint_complexity', 'drc_iterations',
138
+ 'type_node_interaction', 'complexity_score', 'size_priority_interaction'
139
+ ]
140
+
141
+ X_comp = completed[COMPLEXITY_FEATURES]
142
+ y_comp = completed['complexity_encoded']
143
+
144
+ X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(
145
+ X_comp, y_comp, test_size=0.2, random_state=42, stratify=y_comp
146
+ )
147
+
148
+ # XGBoost classifier
149
+ xgb_clf = xgb.XGBClassifier(
150
+ n_estimators=500,
151
+ learning_rate=0.05,
152
+ max_depth=6,
153
+ subsample=0.8,
154
+ colsample_bytree=0.8,
155
+ objective='multi:softprob',
156
+ num_class=3,
157
+ tree_method='hist',
158
+ random_state=42,
159
+ early_stopping_rounds=50,
160
+ )
161
+ xgb_clf.fit(X_train_c, y_train_c, eval_set=[(X_test_c, y_test_c)], verbose=False)
162
+
163
+ # LightGBM classifier
164
+ lgb_clf = lgb.LGBMClassifier(
165
+ n_estimators=500,
166
+ learning_rate=0.05,
167
+ num_leaves=63,
168
+ subsample=0.8,
169
+ colsample_bytree=0.8,
170
+ random_state=42,
171
+ verbose=-1,
172
+ )
173
+ lgb_clf.fit(X_train_c, y_train_c)
174
+
175
+ # Ensemble predictions (average probabilities)
176
+ xgb_proba = xgb_clf.predict_proba(X_test_c)
177
+ lgb_proba = lgb_clf.predict_proba(X_test_c)
178
+ ensemble_proba = (xgb_proba + lgb_proba) / 2
179
+ y_pred_c = np.argmax(ensemble_proba, axis=1)
180
+
181
+ accuracy = accuracy_score(y_test_c, y_pred_c)
182
+ f1 = f1_score(y_test_c, y_pred_c, average='weighted')
183
+
184
+ print(f"\nComplexity Classification Results (Ensemble):")
185
+ print(f" Accuracy: {accuracy:.4f}")
186
+ print(f" F1 (weighted): {f1:.4f}")
187
+ print(f"\nClassification Report:")
188
+ target_names = complexity_encoder.classes_
189
+ print(classification_report(y_test_c, y_pred_c, target_names=target_names))
190
+
191
+ # Per-model scores
192
+ xgb_acc = accuracy_score(y_test_c, xgb_clf.predict(X_test_c))
193
+ lgb_acc = accuracy_score(y_test_c, lgb_clf.predict(X_test_c))
194
+ print(f" XGBoost alone: {xgb_acc:.4f}")
195
+ print(f" LightGBM alone: {lgb_acc:.4f}")
196
+ print(f" Ensemble: {accuracy:.4f}")
197
+
198
+ # === MODEL 3: Bottleneck Risk Prediction ===
199
+ print("\n" + "=" * 60)
200
+ print("MODEL 3: Bottleneck Risk Prediction (Gradient Boosting)")
201
+ print("=" * 60)
202
+
203
+ # For bottleneck prediction, use ALL blocks (including in-progress)
204
+ BOTTLENECK_FEATURES = [
205
+ 'tech_node_encoded', 'block_type_encoded', 'priority_encoded',
206
+ 'transistor_count_log', 'has_dependencies', 'num_dependencies',
207
+ 'constraint_complexity', 'estimated_hours', 'hours_logged',
208
+ 'hours_over_estimate_ratio', 'drc_iterations', 'drc_violations_total',
209
+ 'lvs_mismatches_total', 'current_stage_idx', 'days_in_current_stage',
210
+ 'engineer_skill_factor', 'is_overdue', 'complexity_score'
211
+ ]
212
+
213
+ X_bn = df[BOTTLENECK_FEATURES]
214
+ y_bn = df['bottleneck_encoded']
215
+
216
+ X_train_b, X_test_b, y_train_b, y_test_b = train_test_split(
217
+ X_bn, y_bn, test_size=0.2, random_state=42, stratify=y_bn
218
+ )
219
+
220
+ # XGBoost classifier with calibration
221
+ base_bn_model = xgb.XGBClassifier(
222
+ n_estimators=500,
223
+ learning_rate=0.05,
224
+ max_depth=6,
225
+ subsample=0.8,
226
+ colsample_bytree=0.8,
227
+ scale_pos_weight=1,
228
+ objective='multi:softprob',
229
+ num_class=3,
230
+ tree_method='hist',
231
+ random_state=42,
232
+ )
233
+
234
+ # Calibrate probabilities
235
+ bn_model = CalibratedClassifierCV(base_bn_model, cv=3, method='isotonic')
236
+ bn_model.fit(X_train_b, y_train_b)
237
+
238
+ y_pred_b = bn_model.predict(X_test_b)
239
+ y_proba_b = bn_model.predict_proba(X_test_b)
240
+
241
+ bn_accuracy = accuracy_score(y_test_b, y_pred_b)
242
+ bn_f1 = f1_score(y_test_b, y_pred_b, average='weighted')
243
+
244
+ print(f"\nBottleneck Risk Prediction Results:")
245
+ print(f" Accuracy: {bn_accuracy:.4f}")
246
+ print(f" F1 (weighted): {bn_f1:.4f}")
247
+ print(f"\nClassification Report:")
248
+ bn_target_names = bottleneck_encoder.classes_
249
+ print(classification_report(y_test_b, y_pred_b, target_names=bn_target_names))
250
+
251
+ # === Save All Models & Artifacts ===
252
+ print("\n" + "=" * 60)
253
+ print("SAVING MODELS")
254
+ print("=" * 60)
255
+
256
+ os.makedirs('/app/models', exist_ok=True)
257
+
258
+ # Save models
259
+ joblib.dump(hours_model, '/app/models/hours_estimator.joblib')
260
+ joblib.dump(xgb_clf, '/app/models/complexity_xgb.joblib')
261
+ joblib.dump(lgb_clf, '/app/models/complexity_lgb.joblib')
262
+ joblib.dump(bn_model, '/app/models/bottleneck_predictor.joblib')
263
+
264
+ # Save encoders
265
+ joblib.dump(tech_node_encoder, '/app/models/tech_node_encoder.joblib')
266
+ joblib.dump(block_type_encoder, '/app/models/block_type_encoder.joblib')
267
+ joblib.dump(priority_encoder, '/app/models/priority_encoder.joblib')
268
+ joblib.dump(engineer_encoder, '/app/models/engineer_encoder.joblib')
269
+ joblib.dump(complexity_encoder, '/app/models/complexity_encoder.joblib')
270
+ joblib.dump(bottleneck_encoder, '/app/models/bottleneck_encoder.joblib')
271
+
272
+ # Save feature lists
273
+ feature_config = {
274
+ 'hours_features': HOURS_FEATURES,
275
+ 'complexity_features': COMPLEXITY_FEATURES,
276
+ 'bottleneck_features': BOTTLENECK_FEATURES,
277
+ 'tech_nodes': list(tech_node_encoder.classes_),
278
+ 'block_types': list(block_type_encoder.classes_),
279
+ 'priorities': ['P4-Low', 'P3-Medium', 'P2-High', 'P1-Critical'],
280
+ 'complexity_classes': list(complexity_encoder.classes_),
281
+ 'bottleneck_classes': list(bottleneck_encoder.classes_),
282
+ }
283
+ with open('/app/models/feature_config.json', 'w') as f:
284
+ json.dump(feature_config, f, indent=2)
285
+
286
+ # Save model evaluation metrics
287
+ metrics = {
288
+ 'hours_estimation': {
289
+ 'mae': round(mae, 2),
290
+ 'rmse': round(rmse, 2),
291
+ 'r2': round(r2, 4),
292
+ 'mape_percent': round(mape, 1),
293
+ 'cv_r2_mean': round(cv_scores.mean(), 4),
294
+ 'cv_r2_std': round(cv_scores.std(), 4),
295
+ },
296
+ 'complexity_classification': {
297
+ 'accuracy': round(accuracy, 4),
298
+ 'f1_weighted': round(f1, 4),
299
+ 'xgb_accuracy': round(xgb_acc, 4),
300
+ 'lgb_accuracy': round(lgb_acc, 4),
301
+ 'ensemble_accuracy': round(accuracy, 4),
302
+ },
303
+ 'bottleneck_prediction': {
304
+ 'accuracy': round(bn_accuracy, 4),
305
+ 'f1_weighted': round(bn_f1, 4),
306
+ },
307
+ 'training_data': {
308
+ 'total_samples': len(df),
309
+ 'completed_blocks': int(df['is_completed'].sum()),
310
+ 'in_progress_blocks': int((~df['is_completed'].astype(bool)).sum()),
311
+ }
312
+ }
313
+ with open('/app/models/metrics.json', 'w') as f:
314
+ json.dump(metrics, f, indent=2)
315
+
316
+ print(f"\nModels saved to /app/models/:")
317
+ for f in sorted(os.listdir('/app/models')):
318
+ size = os.path.getsize(f'/app/models/{f}')
319
+ print(f" {f} ({size:,} bytes)")
320
+
321
+ print("\n" + "=" * 60)
322
+ print("ALL MODELS TRAINED SUCCESSFULLY")
323
+ print("=" * 60)