ML Model Training
Training machine learning models involves selecting appropriate algorithms, preparing data, and optimizing model parameters to achieve strong predictive performance.
Training Phases
- Data Preparation: Cleaning, encoding, normalization
- Feature Engineering: Creating meaningful features
- Model Selection: Choosing appropriate algorithms
- Hyperparameter Tuning: Optimizing model settings
- Validation: Cross-validation and evaluation metrics
- Deployment: Preparing models for production
Common Algorithms
- Regression: Linear, Ridge, Lasso, Random Forest
- Classification: Logistic, SVM, Random Forest, Gradient Boosting
- Clustering: K-Means, DBSCAN, Hierarchical
- Neural Networks: MLPs, CNNs, RNNs, Transformers
Python Implementation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, precision_score, recall_score,
f1_score, confusion_matrix, roc_auc_score)
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
import tensorflow as tf
from tensorflow import keras
# 1. Generate synthetic dataset
np.random.seed(42)
n_samples = 1000
n_features = 20
X = np.random.randn(n_samples, n_features)
y = (X[:, 0] + X[:, 1] - X[:, 2] + np.random.randn(n_samples) * 0.5 > 0).astype(int)
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Normalize features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("Dataset shapes:")
print(f"Training: {X_train_scaled.shape}, Testing: {X_test_scaled.shape}")
print(f"Class distribution: {np.bincount(y_train)}")
# 2. Scikit-learn models
print("\n=== Scikit-learn Models ===")
models = {
'Logistic Regression': LogisticRegression(max_iter=1000),
'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),
'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42),
}
sklearn_results = {}
for name, model in models.items():
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled)
y_pred_proba = model.predict_proba(X_test_scaled)[:, 1]
sklearn_results[name] = {
'accuracy': accuracy_score(y_test, y_pred),
'precision': precision_score(y_test, y_pred),
'recall': recall_score(y_test, y_pred),
'f1': f1_score(y_test, y_pred),
'roc_auc': roc_auc_score(y_test, y_pred_proba)
}
print(f"\n{name}:")
for metric, value in sklearn_results[name].items():
print(f" {metric}: {value:.4f}")
# 3. PyTorch neural network
print("\n=== PyTorch Model ===")
class NeuralNetPyTorch(nn.Module):
def __init__(self, input_size):
super().__init__()
self.fc1 = nn.Linear(input_size, 64)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 1)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(0.3)
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.dropout(x)
x = self.relu(self.fc2(x))
x = self.dropout(x)
x = torch.sigmoid(self.fc3(x))
return x
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
pytorch_model = NeuralNetPyTorch(n_features).to(device)
criterion = nn.BCELoss()
optimizer = torch.optim.Adam(pytorch_model.parameters(), lr=0.001)
# Create data loaders
train_dataset = TensorDataset(torch.FloatTensor(X_train_scaled),
torch.FloatTensor(y_train).unsqueeze(1))
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
# Train PyTorch model
epochs = 50
pytorch_losses = []
for epoch in range(epochs):
total_loss = 0
for batch_X, batch_y in train_loader:
batch_X, batch_y = batch_X.to(device), batch_y.to(device)
optimizer.zero_grad()
outputs = pytorch_model(batch_X)
loss = criterion(outputs, batch_y)
loss.backward()
optimizer.step()
total_loss += loss.item()
pytorch_losses.append(total_loss / len(train_loader))
if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch + 1}/{epochs}, Loss: {pytorch_losses[-1]:.4f}")
# Evaluate PyTorch
pytorch_model.eval()
with torch.no_grad():
y_pred_pytorch = pytorch_model(torch.FloatTensor(X_test_scaled).to(device))
y_pred_pytorch = (y_pred_pytorch.cpu().numpy() > 0.5).astype(int).flatten()
print(f"\nPyTorch Accuracy: {accuracy_score(y_test, y_pred_pytorch):.4f}")
# 4. TensorFlow/Keras model
print("\n=== TensorFlow/Keras Model ===")
tf_model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(n_features,)),
keras.layers.Dropout(0.3),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dropout(0.3),
keras.layers.Dense(1, activation='sigmoid')
])
tf_model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
history = tf_model.fit(
X_train_scaled, y_train,
batch_size=32,
epochs=50,
validation_split=0.2,
verbose=0
)
y_pred_tf = (tf_model.predict(X_test_scaled) > 0.5).astype(int).flatten()
print(f"TensorFlow Accuracy: {accuracy_score(y_test, y_pred_tf):.4f}")
# 5. Visualization
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Model comparison
models_names = list(sklearn_results.keys()) + ['PyTorch', 'TensorFlow']
accuracies = [sklearn_results[m]['accuracy'] for m in sklearn_results.keys()] + \
[accuracy_score(y_test, y_pred_pytorch),
accuracy_score(y_test, y_pred_tf)]
axes[0, 0].bar(range(len(models_names)), accuracies, color='steelblue')
axes[0, 0].set_xticks(range(len(models_names)))
axes[0, 0].set_xticklabels(models_names, rotation=45)
axes[0, 0].set_ylabel('Accuracy')
axes[0, 0].set_title('Model Comparison')
axes[0, 0].set_ylim([0, 1])
# Training loss curves
axes[0, 1].plot(pytorch_losses, label='PyTorch', linewidth=2)
axes[0, 1].plot(history.history['loss'], label='TensorFlow', linewidth=2)
axes[0, 1].set_xlabel('Epoch')
axes[0, 1].set_ylabel('Loss')
axes[0, 1].set_title('Training Loss Comparison')
axes[0, 1].legend()
axes[0, 1].grid(True, alpha=0.3)
# Scikit-learn metrics
metrics = ['accuracy', 'precision', 'recall', 'f1']
rf_metrics = [sklearn_results['Random Forest'][m] for m in metrics]
axes[1, 0].bar(metrics, rf_metrics, color='coral')
axes[1, 0].set_ylabel('Score')
axes[1, 0].set_title('Random Forest Metrics')
axes[1, 0].set_ylim([0, 1])
# Validation accuracy over epochs
axes[1, 1].plot(history.history['accuracy'], label='Training', linewidth=2)
axes[1, 1].plot(history.history['val_accuracy'], label='Validation', linewidth=2)
axes[1, 1].set_xlabel('Epoch')
axes[1, 1].set_ylabel('Accuracy')
axes[1, 1].set_title('TensorFlow Training History')
axes[1, 1].legend()
axes[1, 1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('model_training_comparison.png', dpi=100, bbox_inches='tight')
print("\nVisualization saved as 'model_training_comparison.png'")
print("\nModel training completed!")
Training Best Practices
- Data Split: 70/15/15 for train/validation/test
- Scaling: Normalize features before training
- Cross-validation: Use K-fold for robust evaluation
- Early Stopping: Prevent overfitting
- Class Balancing: Handle imbalanced datasets
Key Metrics
- Accuracy: Overall correctness
- Precision: Positive prediction accuracy
- Recall: True positive detection rate
- F1 Score: Harmonic mean of precision/recall
- ROC-AUC: Threshold-independent metric
Deliverables
- Trained model checkpoint
- Performance metrics on test set
- Feature importance analysis
- Learning curves
- Hyperparameter configuration
- Model evaluation report
1---2name: ml-model-training3description: Build and train machine learning models using scikit-learn, PyTorch, and TensorFlow for classification, regression, and clustering tasks4---5
6# ML Model Training
7
8Training machine learning models involves selecting appropriate algorithms, preparing data, and optimizing model parameters to achieve strong predictive performance.
9
10## Training Phases
11
12- **Data Preparation**: Cleaning, encoding, normalization
13- **Feature Engineering**: Creating meaningful features
14- **Model Selection**: Choosing appropriate algorithms
15- **Hyperparameter Tuning**: Optimizing model settings
16- **Validation**: Cross-validation and evaluation metrics
17- **Deployment**: Preparing models for production
18
19## Common Algorithms
20
21- **Regression**: Linear, Ridge, Lasso, Random Forest
22- **Classification**: Logistic, SVM, Random Forest, Gradient Boosting
23- **Clustering**: K-Means, DBSCAN, Hierarchical
24- **Neural Networks**: MLPs, CNNs, RNNs, Transformers
25
26## Python Implementation
27
28```python
29import numpy as np
30import pandas as pd
31import matplotlib.pyplot as plt
32from sklearn.model_selection import train_test_split, cross_val_score
33from sklearn.preprocessing import StandardScaler
34from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
35from sklearn.linear_model import LogisticRegression
36from sklearn.metrics import (accuracy_score, precision_score, recall_score,
37 f1_score, confusion_matrix, roc_auc_score)
38import torch
39import torch.nn as nn
40from torch.utils.data import DataLoader, TensorDataset
41import tensorflow as tf
42from tensorflow import keras
43
44# 1. Generate synthetic dataset
45np.random.seed(42)
46n_samples = 1000
47n_features = 20
48
49X = np.random.randn(n_samples, n_features)
50y = (X[:, 0] + X[:, 1] - X[:, 2] + np.random.randn(n_samples) * 0.5 > 0).astype(int)
51
52# Split data
53X_train, X_test, y_train, y_test = train_test_split(
54 X, y, test_size=0.2, random_state=42
55)
56
57# Normalize features
58scaler = StandardScaler()
59X_train_scaled = scaler.fit_transform(X_train)
60X_test_scaled = scaler.transform(X_test)
61
62print("Dataset shapes:")
63print(f"Training: {X_train_scaled.shape}, Testing: {X_test_scaled.shape}")
64print(f"Class distribution: {np.bincount(y_train)}")
65
66# 2. Scikit-learn models
67print("\n=== Scikit-learn Models ===")
68
69models = {
70 'Logistic Regression': LogisticRegression(max_iter=1000),
71 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),
72 'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42),
73}
74
75sklearn_results = {}
76for name, model in models.items():
77 model.fit(X_train_scaled, y_train)
78 y_pred = model.predict(X_test_scaled)
79 y_pred_proba = model.predict_proba(X_test_scaled)[:, 1]
80
81 sklearn_results[name] = {
82 'accuracy': accuracy_score(y_test, y_pred),
83 'precision': precision_score(y_test, y_pred),
84 'recall': recall_score(y_test, y_pred),
85 'f1': f1_score(y_test, y_pred),
86 'roc_auc': roc_auc_score(y_test, y_pred_proba)
87 }
88
89 print(f"\n{name}:")
90 for metric, value in sklearn_results[name].items():
91 print(f" {metric}: {value:.4f}")
92
93# 3. PyTorch neural network
94print("\n=== PyTorch Model ===")
95
96class NeuralNetPyTorch(nn.Module):
97 def __init__(self, input_size):
98 super().__init__()
99 self.fc1 = nn.Linear(input_size, 64)
100 self.fc2 = nn.Linear(64, 32)
101 self.fc3 = nn.Linear(32, 1)
102 self.relu = nn.ReLU()
103 self.dropout = nn.Dropout(0.3)
104
105 def forward(self, x):
106 x = self.relu(self.fc1(x))
107 x = self.dropout(x)
108 x = self.relu(self.fc2(x))
109 x = self.dropout(x)
110 x = torch.sigmoid(self.fc3(x))
111 return x
112
113device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
114pytorch_model = NeuralNetPyTorch(n_features).to(device)
115criterion = nn.BCELoss()
116optimizer = torch.optim.Adam(pytorch_model.parameters(), lr=0.001)
117
118# Create data loaders
119train_dataset = TensorDataset(torch.FloatTensor(X_train_scaled),
120 torch.FloatTensor(y_train).unsqueeze(1))
121train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
122
123# Train PyTorch model
124epochs = 50
125pytorch_losses = []
126for epoch in range(epochs):
127 total_loss = 0
128 for batch_X, batch_y in train_loader:
129 batch_X, batch_y = batch_X.to(device), batch_y.to(device)
130
131 optimizer.zero_grad()
132 outputs = pytorch_model(batch_X)
133 loss = criterion(outputs, batch_y)
134 loss.backward()
135 optimizer.step()
136 total_loss += loss.item()
137
138 pytorch_losses.append(total_loss / len(train_loader))
139 if (epoch + 1) % 10 == 0:
140 print(f"Epoch {epoch + 1}/{epochs}, Loss: {pytorch_losses[-1]:.4f}")
141
142# Evaluate PyTorch
143pytorch_model.eval()
144with torch.no_grad():
145 y_pred_pytorch = pytorch_model(torch.FloatTensor(X_test_scaled).to(device))
146 y_pred_pytorch = (y_pred_pytorch.cpu().numpy() > 0.5).astype(int).flatten()
147 print(f"\nPyTorch Accuracy: {accuracy_score(y_test, y_pred_pytorch):.4f}")
148
149# 4. TensorFlow/Keras model
150print("\n=== TensorFlow/Keras Model ===")
151
152tf_model = keras.Sequential([
153 keras.layers.Dense(64, activation='relu', input_shape=(n_features,)),
154 keras.layers.Dropout(0.3),
155 keras.layers.Dense(32, activation='relu'),
156 keras.layers.Dropout(0.3),
157 keras.layers.Dense(1, activation='sigmoid')
158])
159
160tf_model.compile(
161 optimizer='adam',
162 loss='binary_crossentropy',
163 metrics=['accuracy']
164)
165
166history = tf_model.fit(
167 X_train_scaled, y_train,
168 batch_size=32,
169 epochs=50,
170 validation_split=0.2,
171 verbose=0
172)
173
174y_pred_tf = (tf_model.predict(X_test_scaled) > 0.5).astype(int).flatten()
175print(f"TensorFlow Accuracy: {accuracy_score(y_test, y_pred_tf):.4f}")
176
177# 5. Visualization
178fig, axes = plt.subplots(2, 2, figsize=(12, 10))
179
180# Model comparison
181models_names = list(sklearn_results.keys()) + ['PyTorch', 'TensorFlow']
182accuracies = [sklearn_results[m]['accuracy'] for m in sklearn_results.keys()] + \
183 [accuracy_score(y_test, y_pred_pytorch),
184 accuracy_score(y_test, y_pred_tf)]
185
186axes[0, 0].bar(range(len(models_names)), accuracies, color='steelblue')
187axes[0, 0].set_xticks(range(len(models_names)))
188axes[0, 0].set_xticklabels(models_names, rotation=45)
189axes[0, 0].set_ylabel('Accuracy')
190axes[0, 0].set_title('Model Comparison')
191axes[0, 0].set_ylim([0, 1])
192
193# Training loss curves
194axes[0, 1].plot(pytorch_losses, label='PyTorch', linewidth=2)
195axes[0, 1].plot(history.history['loss'], label='TensorFlow', linewidth=2)
196axes[0, 1].set_xlabel('Epoch')
197axes[0, 1].set_ylabel('Loss')
198axes[0, 1].set_title('Training Loss Comparison')
199axes[0, 1].legend()
200axes[0, 1].grid(True, alpha=0.3)
201
202# Scikit-learn metrics
203metrics = ['accuracy', 'precision', 'recall', 'f1']
204rf_metrics = [sklearn_results['Random Forest'][m] for m in metrics]
205axes[1, 0].bar(metrics, rf_metrics, color='coral')
206axes[1, 0].set_ylabel('Score')
207axes[1, 0].set_title('Random Forest Metrics')
208axes[1, 0].set_ylim([0, 1])
209
210# Validation accuracy over epochs
211axes[1, 1].plot(history.history['accuracy'], label='Training', linewidth=2)
212axes[1, 1].plot(history.history['val_accuracy'], label='Validation', linewidth=2)
213axes[1, 1].set_xlabel('Epoch')
214axes[1, 1].set_ylabel('Accuracy')
215axes[1, 1].set_title('TensorFlow Training History')
216axes[1, 1].legend()
217axes[1, 1].grid(True, alpha=0.3)
218
219plt.tight_layout()
220plt.savefig('model_training_comparison.png', dpi=100, bbox_inches='tight')
221print("\nVisualization saved as 'model_training_comparison.png'")
222
223print("\nModel training completed!")
224```
225
226## Training Best Practices
227
228- **Data Split**: 70/15/15 for train/validation/test
229- **Scaling**: Normalize features before training
230- **Cross-validation**: Use K-fold for robust evaluation
231- **Early Stopping**: Prevent overfitting
232- **Class Balancing**: Handle imbalanced datasets
233
234## Key Metrics
235
236- **Accuracy**: Overall correctness
237- **Precision**: Positive prediction accuracy
238- **Recall**: True positive detection rate
239- **F1 Score**: Harmonic mean of precision/recall
240- **ROC-AUC**: Threshold-independent metric
241
242## Deliverables
243
244- Trained model checkpoint
245- Performance metrics on test set
246- Feature importance analysis
247- Learning curves
248- Hyperparameter configuration
249- Model evaluation report