πŸ€– AI/ML

Model

Model

A trained ML algorithm. Predicts output from input. Training, validation, and test stages.

πŸ“– Detailed Explanation

Model is a mathematical representation learned from data in machine learning, which makes predictions on new inputs. A model contains parameters (weights, biases), and during training these parameters are optimized to capture the relationship between inputs and outputs.

The lifecycle of a model consists of Training, Validation, Test, and Deployment. In training, parameters are updated with the training data; in validation, hyperparameters are tuned; and in testing, the final performance is evaluated.

Model types are broadly divided into supervised learning (classification, regression), unsupervised learning (clustering, dimensionality reduction), and reinforcement learning. Architectures include linear models, tree-based models (Random Forest, XGBoost), and neural networks (CNN, RNN, Transformer).

In practice, model management is the core of MLOps. By building model versioning, A/B testing, monitoring, and retraining pipelines, model performance is continuously maintained. Hugging Face, MLflow, Weights & Biases, and others are used for model management.

Model Types Representative Algorithms Main use Parameter Scale
Linear Models Linear Regression, Logistic Interpretable prediction Hundreds to thousands
Tree-Based XGBoost, LightGBM Structured data prediction Tens of thousands to hundreds of thousands
CNN ResNet, EfficientNet Image classification/detection Millions to tens of millions
Transformer BERT, GPT, Llama NLP, generative AI Hundreds of millions to trillions
Diffusion Stable Diffusion, DALL-E Image generation Hundreds of millions to billions

πŸ’» Code Example

A model training and evaluation example using PyTorch and scikit-learn.

import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import numpy as np

# 1. 데이터 μ€€λΉ„
X = np.random.randn(1000, 20).astype(np.float32)
y = (X[:, 0] + X[:, 1] > 0).astype(np.int64)

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

# DataLoader 생성
train_loader = DataLoader(
    TensorDataset(torch.tensor(X_train), torch.tensor(y_train)),
    batch_size=32, shuffle=True
)
val_loader = DataLoader(
    TensorDataset(torch.tensor(X_val), torch.tensor(y_val)),
    batch_size=32
)


# 2. λͺ¨λΈ μ •μ˜
class BinaryClassifier(nn.Module):
    def __init__(self, input_dim, hidden_dim=64):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(hidden_dim, hidden_dim // 2),
            nn.ReLU(),
            nn.Linear(hidden_dim // 2, 2)
        )

    def forward(self, x):
        return self.layers(x)


model = BinaryClassifier(input_dim=20)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)


# 3. ν›ˆλ ¨ 루프
def train_epoch(model, loader, criterion, optimizer):
    model.train()
    total_loss = 0
    for X_batch, y_batch in loader:
        optimizer.zero_grad()
        outputs = model(X_batch)
        loss = criterion(outputs, y_batch)
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    return total_loss / len(loader)


def evaluate(model, loader):
    model.eval()
    predictions, labels = [], []
    with torch.no_grad():
        for X_batch, y_batch in loader:
            outputs = model(X_batch)
            preds = outputs.argmax(dim=1)
            predictions.extend(preds.numpy())
            labels.extend(y_batch.numpy())
    return accuracy_score(labels, predictions)


# ν›ˆλ ¨ μ‹€ν–‰
best_val_acc = 0
for epoch in range(50):
    train_loss = train_epoch(model, train_loader, criterion, optimizer)
    val_acc = evaluate(model, val_loader)

    if val_acc > best_val_acc:
        best_val_acc = val_acc
        torch.save(model.state_dict(), "best_model.pt")

    if epoch % 10 == 0:
        print(f"Epoch {epoch}: Loss={train_loss:.4f}, Val Acc={val_acc:.4f}")


# 4. ν…ŒμŠ€νŠΈ 평가
model.load_state_dict(torch.load("best_model.pt"))
model.eval()

with torch.no_grad():
    test_preds = model(torch.tensor(X_test)).argmax(dim=1).numpy()

print("\n=== Test Results ===")
print(classification_report(y_test, test_preds))


# 5. λͺ¨λΈ μ €μž₯ (배포용)
torch.save({
    'model_state_dict': model.state_dict(),
    'model_config': {'input_dim': 20, 'hidden_dim': 64},
    'accuracy': accuracy_score(y_test, test_preds)
}, "model_checkpoint.pt")

A simple model example using scikit-learn:

from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import joblib

# νŒŒμ΄ν”„λΌμΈ μ •μ˜ (μ „μ²˜λ¦¬ + λͺ¨λΈ)
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('classifier', RandomForestClassifier(
        n_estimators=100,
        max_depth=10,
        random_state=42
    ))
])

# ν›ˆλ ¨
pipeline.fit(X_train, y_train)

# 평가
train_acc = pipeline.score(X_train, y_train)
test_acc = pipeline.score(X_test, y_test)
print(f"Train Accuracy: {train_acc:.4f}")
print(f"Test Accuracy: {test_acc:.4f}")

# λͺ¨λΈ μ €μž₯
joblib.dump(pipeline, "sklearn_model.joblib")

# λͺ¨λΈ λ‘œλ“œ 및 μΆ”λ‘ 
loaded_model = joblib.load("sklearn_model.joblib")
predictions = loaded_model.predict(X_test[:5])
print(f"Predictions: {predictions}")

πŸ—£οΈ Practical Conversation Examples

πŸ’Ό In a Meeting

"The current model accuracy is 92%, but it is high only on the validation set and drops to 85% on the test set. There are signs of overfitting, so we plan to retrain after increasing regularization strength and adding data augmentation."

🎀 In an Interview

"A model is a set of learned parameters. It updates the weights by minimizing the loss function on the training data, and tunes the hyperparameters with the validation set. The test set is used only for the final evaluation, which prevents data leakage."

πŸ”§ In a Technical Discussion

"Version control is important when deploying models. We operate by creating a model registry with MLflow, running shadow tests in staging, and then promoting to production. We also need to set up model drift detection alerts."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

❌ Wrong approach: Tuning hyperparameters with test data causes test performance to be overestimated.

βœ… Correct approach: Clearly separate the training/validation/test sets, and tune only with the validation set. Use the test set only once, for the final evaluation.

❌ Wrong approach: Saving only the model without a preprocessing pipeline causes preprocessing mismatches during inference.

βœ… Correct approach: Save it with an sklearn Pipeline or a checkpoint that includes preprocessing. The scaler parameters used during training must be applied identically during inference.

❌ Wrong approach: Leaving a model unmonitored after deployment degrades performance due to data drift.

βœ… Correct approach: Monitor the prediction distribution and input feature distribution, and set up a retraining trigger for when performance degrades.

πŸ”— Related Terms

πŸ“š Learn More