Model
Model
A trained machine learning algorithm. Predicts outputs from inputs. Developed through training, validation, and testing stages.
Model
A trained machine learning algorithm. Predicts outputs from inputs. Developed through training, validation, and testing stages.
In machine learning, a model is a mathematical representation that encapsulates patterns learned from data. It can be viewed as a function that takes input data and produces outputs such as predictions, classifications, and generation. There are various architectures, from linear regression to Transformers, and choosing the right model for the problem is the first step to success.
Model development generally goes through three stages: 1) Training - optimizing model parameters with training data, 2) Validation - hyperparameter tuning and overfitting monitoring, 3) Test - final performance evaluation with unseen data. Splitting the data appropriately in this process is important.
A model's complexity is directly tied to the bias-variance tradeoff. A model that is too simple causes underfitting, and a model that is too complex causes overfitting. These are controlled with techniques such as regularization, dropout, and early stopping.
Recently, the paradigm of fine-tuning pre-trained large models (Foundation Models) has become mainstream. By adapting GPT, BERT, ResNet, and others to a specific task, high performance can be achieved even with little data.
This is the entire pipeline of model definition, training, and evaluation using PyTorch:
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.utils.data import DataLoader, TensorDataset
from sklearn.model_selection import train_test_split
# 1. 모델 정의
class ClassificationModel(nn.Module):
def __init__(self, input_dim, hidden_dim, num_classes):
super().__init__()
self.model = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(hidden_dim, hidden_dim // 2),
nn.ReLU(),
nn.Linear(hidden_dim // 2, num_classes)
)
def forward(self, x):
return self.model(x)
# 2. 데이터 분할 (Train/Val/Test)
def prepare_data(X, y, val_ratio=0.15, test_ratio=0.15):
X_temp, X_test, y_temp, y_test = train_test_split(
X, y, test_size=test_ratio, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_temp, y_temp, test_size=val_ratio/(1-test_ratio),
stratify=y_temp, random_state=42
)
return (X_train, y_train), (X_val, y_val), (X_test, y_test)
# 3. 학습 루프
def train_model(model, train_loader, val_loader, epochs=100, lr=1e-3):
optimizer = Adam(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
best_val_acc = 0
for epoch in range(epochs):
# Training
model.train()
for X_batch, y_batch in train_loader:
pred = model(X_batch)
loss = criterion(pred, y_batch)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Validation
model.eval()
correct = total = 0
with torch.no_grad():
for X_batch, y_batch in val_loader:
pred = model(X_batch).argmax(dim=1)
correct += (pred == y_batch).sum().item()
total += len(y_batch)
val_acc = correct / total
if val_acc > best_val_acc:
best_val_acc = val_acc
torch.save(model.state_dict(), 'best_model.pt')
if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch+1}: Val Acc = {val_acc:.4f}")
return best_val_acc
# 사용 예시
model = ClassificationModel(input_dim=128, hidden_dim=256, num_classes=10)
print(f"모델 파라미터 수: {sum(p.numel() for p in model.parameters()):,}")| Model Type | Number of Parameters | Training Time | Inference speed |
|---|---|---|---|
| Linear Regression | ~100 | Seconds | <1ms |
| Random Forest | ~100K | Minutes | ~10ms |
| ResNet-50 | 25M | Hours (GPU) | ~20ms |
| BERT-base | 110M | Days (Multi-GPU) | ~50ms |
| GPT-4 | ~1.7T (estimated) | Months (cluster) | ~100ms/token |
"Let's build a simple baseline model first, and then gradually increase the complexity."
Used when proposing a proven approach at the start of a project.
"The validation set performance is starting to plateau, so I'll apply Early Stopping."
Used when discussing when to stop training in order to prevent overfitting.
"This model's latency is too high to deploy to production. It needs to be made lighter."
Used when explaining the tradeoff between service requirements and model complexity.
1. Selecting a model with test data: The test set should be used only for the final evaluation. If it is used for model selection or hyperparameter tuning, overfitting occurs.
2. Data Leakage: Be careful of cases where future information is included in the training data, or where test data information leaks during preprocessing.
3. Ignoring class imbalance: With imbalanced data, looking only at accuracy means even a model that only predicts the majority class can get a high score. Check F1, AUC-ROC, and so on together.
4. Failing to ensure reproducibility: If you do not record random_state, the model version, and the data version, reproducing the experiment becomes impossible.