Sub topic 2
Classification: Predicting a Category
Assume you know basic Python, arrays, functions, and mean and variance. This chapter uses the ideas of features, labels, and training data.
Classification and Regression
Classification predicts a category, called a class. For example, an email classifier might predict spam or not spam. A classifier can also predict several classes, such as the three iris species.
Regression predicts a numeric value. A model could predict tomorrow's temperature, a house price, or a flower's sepal length.
| Task | Output example | Typical question |
|---|---|---|
| Classification | `spam` | Which category is this? |
| Regression | `23.5` | What number should this be? |
A data row contains features, which are input measurements. In supervised learning, the known answer is the label. A classifier learns a relationship between features and labels.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(accuracy_score(y_test, predictions))Training: Parameters, Loss, and Optimization
A model has parameters, which are values it adjusts while learning. Training repeatedly compares predictions with labels. A loss function measures the error. An optimization method changes the parameters to reduce that loss.
For classification, the model may output a probability for each class. The predicted class is usually the one with the highest probability.
Generalization and Model Fit
Generalization is the ability to make accurate predictions on examples not used during training.
- Underfitting occurs when a model is too simple to learn the useful pattern. Training and test performance are both poor.
- Overfitting occurs when a model memorizes training details, including noise. Training performance is high, but test performance is poor.
Evaluation on Unseen Data
Split the data before training. Use the training set to fit parameters and the held-out test set to estimate performance on new data. For balanced classification, accuracy is the fraction of correct predictions. With unequal error costs or rare classes, consider precision, recall, or a confusion matrix.
Exercise
A model scores 99% on training data and 68% on test data. What is the likely problem?
Show answer
The model is overfitting. It memorizes training examples but generalizes poorly.