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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.optim as optim
|
4 |
+
from torch.utils.data import DataLoader, TensorDataset
|
5 |
+
from sklearn.model_selection import train_test_split
|
6 |
+
import numpy as np
|
7 |
+
import pandas as pd
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
from datetime import datetime
|
10 |
+
import json
|
11 |
+
import os
|
12 |
+
|
13 |
+
from model import (
|
14 |
+
LoanPredictionANN,
|
15 |
+
LoanPredictionLightANN,
|
16 |
+
LoanPredictionDeepANN,
|
17 |
+
load_processed_data,
|
18 |
+
calculate_class_weights,
|
19 |
+
evaluate_model,
|
20 |
+
plot_training_history,
|
21 |
+
plot_confusion_matrix,
|
22 |
+
model_summary
|
23 |
+
)
|
24 |
+
|
25 |
+
class LoanPredictionTrainer:
|
26 |
+
"""
|
27 |
+
Comprehensive trainer for Loan Prediction Neural Networks
|
28 |
+
"""
|
29 |
+
|
30 |
+
def __init__(self, model_type='standard', learning_rate=0.001, batch_size=512,
|
31 |
+
device=None, use_class_weights=True):
|
32 |
+
"""
|
33 |
+
Initialize the trainer
|
34 |
+
|
35 |
+
Args:
|
36 |
+
model_type: 'light', 'standard', or 'deep'
|
37 |
+
learning_rate: Learning rate for optimizer
|
38 |
+
batch_size: Batch size for training
|
39 |
+
device: Device to use ('cuda' or 'cpu')
|
40 |
+
use_class_weights: Whether to use class weights for imbalanced data
|
41 |
+
"""
|
42 |
+
self.model_type = model_type
|
43 |
+
self.learning_rate = learning_rate
|
44 |
+
self.batch_size = batch_size
|
45 |
+
self.use_class_weights = use_class_weights
|
46 |
+
|
47 |
+
# Set device
|
48 |
+
if device is None:
|
49 |
+
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
50 |
+
else:
|
51 |
+
self.device = torch.device(device)
|
52 |
+
|
53 |
+
print(f"Using device: {self.device}")
|
54 |
+
|
55 |
+
# Initialize model
|
56 |
+
self.model = self._create_model()
|
57 |
+
self.model.to(self.device)
|
58 |
+
|
59 |
+
# Training history
|
60 |
+
self.train_losses = []
|
61 |
+
self.val_losses = []
|
62 |
+
self.train_accuracies = []
|
63 |
+
self.val_accuracies = []
|
64 |
+
|
65 |
+
def _create_model(self):
|
66 |
+
"""Create model based on specified type"""
|
67 |
+
if self.model_type == 'light':
|
68 |
+
return LoanPredictionLightANN()
|
69 |
+
elif self.model_type == 'standard':
|
70 |
+
return LoanPredictionANN()
|
71 |
+
elif self.model_type == 'deep':
|
72 |
+
return LoanPredictionDeepANN()
|
73 |
+
else:
|
74 |
+
raise ValueError("model_type must be 'light', 'standard', or 'deep'")
|
75 |
+
|
76 |
+
def prepare_data(self, data_path='data/processed', validation_split=0.2):
|
77 |
+
"""Load and prepare data for training"""
|
78 |
+
print("Loading processed data...")
|
79 |
+
X_train, y_train, X_test, y_test, feature_names = load_processed_data(data_path)
|
80 |
+
|
81 |
+
# Split training data into train/validation
|
82 |
+
X_train, X_val, y_train, y_val = train_test_split(
|
83 |
+
X_train, y_train, test_size=validation_split,
|
84 |
+
random_state=42, stratify=y_train
|
85 |
+
)
|
86 |
+
|
87 |
+
# Convert to PyTorch tensors
|
88 |
+
self.X_train = torch.FloatTensor(X_train).to(self.device)
|
89 |
+
self.y_train = torch.FloatTensor(y_train).unsqueeze(1).to(self.device)
|
90 |
+
|
91 |
+
self.X_val = torch.FloatTensor(X_val).to(self.device)
|
92 |
+
self.y_val = torch.FloatTensor(y_val).unsqueeze(1).to(self.device)
|
93 |
+
|
94 |
+
self.X_test = torch.FloatTensor(X_test).to(self.device)
|
95 |
+
self.y_test = torch.FloatTensor(y_test).unsqueeze(1).to(self.device)
|
96 |
+
|
97 |
+
# Store original numpy arrays for evaluation
|
98 |
+
self.X_test_np = X_test
|
99 |
+
self.y_test_np = y_test
|
100 |
+
|
101 |
+
self.feature_names = feature_names
|
102 |
+
|
103 |
+
# Create data loaders
|
104 |
+
train_dataset = TensorDataset(self.X_train, self.y_train)
|
105 |
+
val_dataset = TensorDataset(self.X_val, self.y_val)
|
106 |
+
|
107 |
+
self.train_loader = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)
|
108 |
+
self.val_loader = DataLoader(val_dataset, batch_size=self.batch_size, shuffle=False)
|
109 |
+
|
110 |
+
# Calculate class weights if needed
|
111 |
+
if self.use_class_weights:
|
112 |
+
self.class_weights = calculate_class_weights(y_train)
|
113 |
+
print(f"Class weights: {self.class_weights}")
|
114 |
+
else:
|
115 |
+
self.class_weights = None
|
116 |
+
|
117 |
+
print(f"Data prepared:")
|
118 |
+
print(f" Training samples: {len(X_train):,}")
|
119 |
+
print(f" Validation samples: {len(X_val):,}")
|
120 |
+
print(f" Test samples: {len(X_test):,}")
|
121 |
+
print(f" Features: {len(feature_names)}")
|
122 |
+
|
123 |
+
return self
|
124 |
+
|
125 |
+
def setup_training(self, weight_decay=1e-5):
|
126 |
+
"""Setup optimizer and loss function"""
|
127 |
+
# Optimizer
|
128 |
+
self.optimizer = optim.Adam(
|
129 |
+
self.model.parameters(),
|
130 |
+
lr=self.learning_rate,
|
131 |
+
weight_decay=weight_decay
|
132 |
+
)
|
133 |
+
|
134 |
+
# Learning rate scheduler
|
135 |
+
self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(
|
136 |
+
self.optimizer, mode='min', factor=0.5, patience=10, verbose=True
|
137 |
+
)
|
138 |
+
|
139 |
+
# Loss function
|
140 |
+
if self.use_class_weights and self.class_weights is not None:
|
141 |
+
# Weighted BCE loss for imbalanced data
|
142 |
+
pos_weight = self.class_weights[1] / self.class_weights[0]
|
143 |
+
self.criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight.to(self.device))
|
144 |
+
else:
|
145 |
+
self.criterion = nn.BCELoss()
|
146 |
+
|
147 |
+
print(f"Training setup complete:")
|
148 |
+
print(f" Optimizer: Adam (lr={self.learning_rate}, weight_decay={weight_decay})")
|
149 |
+
print(f" Scheduler: ReduceLROnPlateau")
|
150 |
+
print(f" Loss function: {'Weighted BCE' if self.use_class_weights else 'BCE'}")
|
151 |
+
|
152 |
+
return self
|
153 |
+
|
154 |
+
def train_epoch(self):
|
155 |
+
"""Train for one epoch"""
|
156 |
+
self.model.train()
|
157 |
+
total_loss = 0.0
|
158 |
+
correct = 0
|
159 |
+
total = 0
|
160 |
+
|
161 |
+
for batch_idx, (data, target) in enumerate(self.train_loader):
|
162 |
+
self.optimizer.zero_grad()
|
163 |
+
|
164 |
+
output = self.model(data)
|
165 |
+
|
166 |
+
if isinstance(self.criterion, nn.BCEWithLogitsLoss):
|
167 |
+
# Remove sigmoid from model output for BCEWithLogitsLoss
|
168 |
+
output_logits = output # Assuming output is logits
|
169 |
+
loss = self.criterion(output_logits, target)
|
170 |
+
predicted = torch.sigmoid(output_logits) > 0.5
|
171 |
+
else:
|
172 |
+
loss = self.criterion(output, target)
|
173 |
+
predicted = output > 0.5
|
174 |
+
|
175 |
+
loss.backward()
|
176 |
+
self.optimizer.step()
|
177 |
+
|
178 |
+
total_loss += loss.item()
|
179 |
+
total += target.size(0)
|
180 |
+
correct += predicted.eq(target > 0.5).sum().item()
|
181 |
+
|
182 |
+
avg_loss = total_loss / len(self.train_loader)
|
183 |
+
accuracy = 100. * correct / total
|
184 |
+
|
185 |
+
return avg_loss, accuracy
|
186 |
+
|
187 |
+
def validate_epoch(self):
|
188 |
+
"""Validate for one epoch"""
|
189 |
+
self.model.eval()
|
190 |
+
total_loss = 0.0
|
191 |
+
correct = 0
|
192 |
+
total = 0
|
193 |
+
|
194 |
+
with torch.no_grad():
|
195 |
+
for data, target in self.val_loader:
|
196 |
+
output = self.model(data)
|
197 |
+
|
198 |
+
if isinstance(self.criterion, nn.BCEWithLogitsLoss):
|
199 |
+
output_logits = output
|
200 |
+
loss = self.criterion(output_logits, target)
|
201 |
+
predicted = torch.sigmoid(output_logits) > 0.5
|
202 |
+
else:
|
203 |
+
loss = self.criterion(output, target)
|
204 |
+
predicted = output > 0.5
|
205 |
+
|
206 |
+
total_loss += loss.item()
|
207 |
+
total += target.size(0)
|
208 |
+
correct += predicted.eq(target > 0.5).sum().item()
|
209 |
+
|
210 |
+
avg_loss = total_loss / len(self.val_loader)
|
211 |
+
accuracy = 100. * correct / total
|
212 |
+
|
213 |
+
return avg_loss, accuracy
|
214 |
+
|
215 |
+
def train(self, num_epochs=100, early_stopping_patience=20, save_best=True):
|
216 |
+
"""Train the model"""
|
217 |
+
print(f"\nStarting training for {num_epochs} epochs...")
|
218 |
+
print("=" * 60)
|
219 |
+
|
220 |
+
best_val_loss = float('inf')
|
221 |
+
patience_counter = 0
|
222 |
+
|
223 |
+
for epoch in range(1, num_epochs + 1):
|
224 |
+
# Train
|
225 |
+
train_loss, train_acc = self.train_epoch()
|
226 |
+
|
227 |
+
# Validate
|
228 |
+
val_loss, val_acc = self.validate_epoch()
|
229 |
+
|
230 |
+
# Update learning rate
|
231 |
+
self.scheduler.step(val_loss)
|
232 |
+
|
233 |
+
# Store history
|
234 |
+
self.train_losses.append(train_loss)
|
235 |
+
self.val_losses.append(val_loss)
|
236 |
+
self.train_accuracies.append(train_acc)
|
237 |
+
self.val_accuracies.append(val_acc)
|
238 |
+
|
239 |
+
# Print progress
|
240 |
+
if epoch % 10 == 0 or epoch == 1:
|
241 |
+
print(f'Epoch {epoch:3d}/{num_epochs}: '
|
242 |
+
f'Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.2f}% | '
|
243 |
+
f'Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.2f}%')
|
244 |
+
|
245 |
+
# Early stopping
|
246 |
+
if val_loss < best_val_loss:
|
247 |
+
best_val_loss = val_loss
|
248 |
+
patience_counter = 0
|
249 |
+
if save_best:
|
250 |
+
self.save_model('best_model.pth')
|
251 |
+
else:
|
252 |
+
patience_counter += 1
|
253 |
+
|
254 |
+
if patience_counter >= early_stopping_patience:
|
255 |
+
print(f"Early stopping triggered after {epoch} epochs")
|
256 |
+
break
|
257 |
+
|
258 |
+
print("=" * 60)
|
259 |
+
print("Training completed!")
|
260 |
+
|
261 |
+
# Load best model if saved
|
262 |
+
if save_best and os.path.exists('best_model.pth'):
|
263 |
+
self.load_model('best_model.pth')
|
264 |
+
print("Loaded best model weights.")
|
265 |
+
|
266 |
+
return self
|
267 |
+
|
268 |
+
def evaluate(self, threshold=0.5):
|
269 |
+
"""Evaluate the model on test set"""
|
270 |
+
print("\nEvaluating model on test set...")
|
271 |
+
|
272 |
+
metrics, y_pred, y_pred_proba = evaluate_model(
|
273 |
+
self.model, self.X_test_np, self.y_test_np, threshold
|
274 |
+
)
|
275 |
+
|
276 |
+
print("\nTest Set Performance:")
|
277 |
+
print("-" * 30)
|
278 |
+
for metric, value in metrics.items():
|
279 |
+
print(f"{metric.capitalize()}: {value:.4f}")
|
280 |
+
|
281 |
+
# Plot confusion matrix
|
282 |
+
cm = plot_confusion_matrix(self.y_test_np, y_pred)
|
283 |
+
|
284 |
+
# Plot training history
|
285 |
+
plot_training_history(
|
286 |
+
self.train_losses, self.val_losses,
|
287 |
+
self.train_accuracies, self.val_accuracies
|
288 |
+
)
|
289 |
+
|
290 |
+
return metrics, y_pred, y_pred_proba
|
291 |
+
|
292 |
+
def save_model(self, filepath):
|
293 |
+
"""Save model and training state"""
|
294 |
+
torch.save({
|
295 |
+
'model_state_dict': self.model.state_dict(),
|
296 |
+
'optimizer_state_dict': self.optimizer.state_dict(),
|
297 |
+
'model_type': self.model_type,
|
298 |
+
'learning_rate': self.learning_rate,
|
299 |
+
'batch_size': self.batch_size,
|
300 |
+
'train_losses': self.train_losses,
|
301 |
+
'val_losses': self.val_losses,
|
302 |
+
'train_accuracies': self.train_accuracies,
|
303 |
+
'val_accuracies': self.val_accuracies,
|
304 |
+
'feature_names': self.feature_names
|
305 |
+
}, filepath)
|
306 |
+
|
307 |
+
def load_model(self, filepath):
|
308 |
+
"""Load model and training state"""
|
309 |
+
checkpoint = torch.load(filepath, map_location=self.device)
|
310 |
+
self.model.load_state_dict(checkpoint['model_state_dict'])
|
311 |
+
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
|
312 |
+
|
313 |
+
# Load training history if available
|
314 |
+
if 'train_losses' in checkpoint:
|
315 |
+
self.train_losses = checkpoint['train_losses']
|
316 |
+
self.val_losses = checkpoint['val_losses']
|
317 |
+
self.train_accuracies = checkpoint['train_accuracies']
|
318 |
+
self.val_accuracies = checkpoint['val_accuracies']
|
319 |
+
|
320 |
+
print(f"Model loaded from {filepath}")
|
321 |
+
|
322 |
+
def get_model_summary(self):
|
323 |
+
"""Print model summary"""
|
324 |
+
model_summary(self.model)
|
325 |
+
|
326 |
+
|
327 |
+
def main():
|
328 |
+
"""Main training function"""
|
329 |
+
print("Loan Prediction Neural Network Training")
|
330 |
+
print("=" * 50)
|
331 |
+
|
332 |
+
# Configuration
|
333 |
+
config = {
|
334 |
+
'model_type': 'standard', # 'light', 'standard', 'deep'
|
335 |
+
'learning_rate': 0.001,
|
336 |
+
'batch_size': 512,
|
337 |
+
'num_epochs': 100,
|
338 |
+
'weight_decay': 1e-5,
|
339 |
+
'early_stopping_patience': 20,
|
340 |
+
'use_class_weights': True,
|
341 |
+
'validation_split': 0.2
|
342 |
+
}
|
343 |
+
|
344 |
+
print("Configuration:")
|
345 |
+
for key, value in config.items():
|
346 |
+
print(f" {key}: {value}")
|
347 |
+
|
348 |
+
# Initialize trainer
|
349 |
+
trainer = LoanPredictionTrainer(
|
350 |
+
model_type=config['model_type'],
|
351 |
+
learning_rate=config['learning_rate'],
|
352 |
+
batch_size=config['batch_size'],
|
353 |
+
use_class_weights=config['use_class_weights']
|
354 |
+
)
|
355 |
+
|
356 |
+
# Show model architecture
|
357 |
+
trainer.get_model_summary()
|
358 |
+
|
359 |
+
# Prepare data and setup training
|
360 |
+
trainer.prepare_data(validation_split=config['validation_split'])
|
361 |
+
trainer.setup_training(weight_decay=config['weight_decay'])
|
362 |
+
|
363 |
+
# Train the model
|
364 |
+
trainer.train(
|
365 |
+
num_epochs=config['num_epochs'],
|
366 |
+
early_stopping_patience=config['early_stopping_patience']
|
367 |
+
)
|
368 |
+
|
369 |
+
# Evaluate the model
|
370 |
+
metrics, predictions, probabilities = trainer.evaluate()
|
371 |
+
|
372 |
+
# Save final model
|
373 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
374 |
+
model_filename = f"loan_prediction_model_{config['model_type']}_{timestamp}.pth"
|
375 |
+
trainer.save_model(model_filename)
|
376 |
+
print(f"\nFinal model saved as: {model_filename}")
|
377 |
+
|
378 |
+
# Save training results
|
379 |
+
results = {
|
380 |
+
'config': config,
|
381 |
+
'final_metrics': metrics,
|
382 |
+
'training_history': {
|
383 |
+
'train_losses': trainer.train_losses,
|
384 |
+
'val_losses': trainer.val_losses,
|
385 |
+
'train_accuracies': trainer.train_accuracies,
|
386 |
+
'val_accuracies': trainer.val_accuracies
|
387 |
+
}
|
388 |
+
}
|
389 |
+
|
390 |
+
results_filename = f"training_results_{timestamp}.json"
|
391 |
+
with open(results_filename, 'w') as f:
|
392 |
+
json.dump(results, f, indent=2)
|
393 |
+
|
394 |
+
print(f"Training results saved as: {results_filename}")
|
395 |
+
print("\nTraining complete!")
|
396 |
+
|
397 |
+
|
398 |
+
if __name__ == "__main__":
|
399 |
+
main()
|