III. Model Refinement


Advanced Machine Learning

     

Lecturer: Dr. HAS Sothea

1 Polynomial features (Beyond linearity)

1.1 Polynomial Features

  • Linear boundary assumption might be too weak in real situation.
  • Polynomial features: \(X_1,\dots,X_d\to X_i^{\color{red}{k}}X_j^{{\color{green}{p}}-{\color{red}{k}}}, {\color{red}{k}}=0,1,\dots,{\color{green}{p}}\).
  • Original data:
x1 x2
0 -0.752759 2.704286
1 1.391964 0.591951
2 -2.063888 -2.064033
  • Polynomial features of degree 2:
x1 x2 x1^2 x1 x2 x2^2
0 -0.752759 2.704286 0.566647 -2.035676 7.313162
1 1.391964 0.591951 1.937563 0.823974 0.350406
2 -2.063888 -2.064033 4.259634 4.259933 4.260232
  • Other transformations: \(\log(x),\sqrt{x}, 1/(1+x),...\) may also be used according to the nature of the data to improve the model performance.
  • In regression, spearman & pearson correlation may signal if a transformation is needed, and scatterplot may help to identify it.
  • In classification, scatterplot with decision boundary is a helpful tool.
  • Linear boundary assumption might be too weak in real situation.
  • Polynomial features of degree \(p\) \(X_1,\dots,X_d\to X_i^kX_j^{p-k}, k=0,\dots,p\).
  • Offer more flexible boundaries.
  • May be more suitable in complex problems.
  • Higher risk of overfitting!!!
  • Overfitting: happens when a model learns the training data too well, capturing noise and fluctuations rather than the underlying pattern.

2 Regularization / penalization methods

Why Regularization?

  • In many cases, linear assumption is not suitable or too simple.
  • However, when a model is too flexible (high-order polynomial features), it’s prone to overfitting.
  • Building a good model is capturing the pattern of data, NOT to fit all the training points.
  • There are mainly two ways to control the flexibility of parametric models:
  1. Control the complexity of the model (e.g., polynomial degree).
  1. Control the magnitude of the parameters (e.g., regularization/penalization).

Impact of Regularization

  • Regularization aims to control the magnitude of the parameters, which can help to prevent overfitting and improve the generalization of the model.

2.1 \(L_2\) Penalization

  • \(L_2\) regularized loss function: for any \(\alpha>0\), \[{\cal L}_2({\color{blue}{\beta_0,\vec{\beta}}})=\underbrace{{\color{red}{{\cal L}}}({\color{red}{\beta_0,\vec{\beta}}})}_{\text{loss function}}+\alpha\underbrace{\color{green}{\sum_{j=0}^d}{\color{blue}{\beta_j^2}}}_{\text{Control}}.\]
    • \(\alpha\) is called Penalty Strength.
    • Large \(\alpha\Leftrightarrow\) strong penalty \(\Leftrightarrow\) small \({\color{blue}{\beta_j^2}}\).
    • Small \(\alpha\Leftrightarrow\) light penalty \(\Leftrightarrow\) large \({\color{blue}{\beta_j^2}}\).
  • Parameter \(\alpha\) balances goodness of fit (loss \(\color{red}{{\cal L}}\)) and flexibility of the model (\(\color{green}{\sum_{j=0}^d}{\color{blue}{\beta_j}}^2\)).
  • 🔑 Key idea: Tune a suitable penalization strength \(\alpha\) that balances these two terms.

2.2 \(L_1\) Penalization

  • \(L_1\) regularized loss function: for any \(\alpha>0\), \[{\cal L}_1(\beta_0,\vec{\beta})=\underbrace{\color{red}{{\cal L}(\beta_0,\vec{\beta})}}_{\text{loss function}}+\alpha\underbrace{\color{green}{\sum_{j=0}^d|\beta_j|}}_{\text{Control}}.\]
  • By its nature, \(L_1\) regularization performs feature selection.
  • This means that it tends to force unimportant variables to be \(0\).
  • 🔑 Key idea: Tune a suitable penalization strength \(\alpha\).

Regularization is an important method that can be used with any parametric models not only logtistic regression.

3 Hyperparameter Tuning

3.1 Train/Validate/Test

  • A good model is the one that can generalize/predict new unseen data.
  • The first attempt: splitting the data into 3 parts.
Set Common % Purpose
Train 70%–80% For training the model
Validation 10%–15% For tuning hyperparameters (\(\alpha\))
Test 10%–15% Evaluate final model performance
  • In this case, the best hyperparameter is the one achieving the best performance on Validation set.
  • The final performance is measured using the Test set.

3.2 \(K\)-fold Cross-Validation

  • In the previous scheme, the best \(k\) depends strongly on validation set.
  • To reduce this dependency, a more stable scheme is proposed called \(K\)-fold Cross-Validation technique.

Pseudocode

  • For \(\color{blue}{\alpha}\) [min,...,max]:
    • For f in [1,...,K]:
      • Train model with hyperparameter \(\color{blue}{\alpha}\) on all data except for fold f.
      • Predict & measure performance on fold f denoted by \(\color{red}{\epsilon_f}\).
    • Compute CV performance for \(\color{blue}{\alpha}\): \[\text{CV}(\color{blue}{\alpha})=\frac{1}{K}\sum_{f=1}^K\color{red}{\epsilon_f}.\]

Tuning polynomial degree

Tuning Optimal Polynomial Degree using \(10\)-fold Cross-Validation

from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score

# List of degrees to search over
degrees = list(range(1,11))

# List for storing accuracy
acc = []
for deg in degrees:
    poly = PolynomialFeatures(degree=deg, include_bias=False)
    x_poly = poly.fit_transform(
        pd.DataFrame(x1[:,1], columns=['x1'])
    )
    x_poly = np.column_stack([x_poly,x1[:,2],x1[:,1]*x1[:,2]])

    # model
    model = LogisticRegression()
    score = cross_val_score(model, x_poly, y_, cv=10, 
                scoring='accuracy'
            ).mean()
    acc.append(score)

Tuning Penalty Strength \(\alpha\) in \(L_2\) Penalty

Tuning Penalty Strength \(\alpha\) using \(10\)-fold Cross-Validation

from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
# Data
poly = PolynomialFeatures(degree=5, include_bias=False)
x_poly = poly.fit_transform(
        pd.DataFrame(x1[:,1], columns=['x1']))
x_poly = np.column_stack([x_poly,x1[:,2],x1[:,1]*x1[:,2]])
# Penalty strength
alphas = np.concatenate([
    np.linspace(1e-3,10, 50), 
    np.linspace(10.1, 1000, 50)]
)
coefficients = {f'{alp}': [] for alp in alphas}
acc = []
for alp in alphas:
    # model
    model = LogisticRegression(penalty="l2", C=1/alp)
    score = cross_val_score(model, x_poly, y_, cv=10, 
                scoring='balanced_accuracy').mean()
    acc.append(score)
    # Fitting
    model.fit(x_poly, y_)
    coefficients[f'{alp}'] = model.coef_[0]

Tuning Penalty Strength \(\alpha\) in \(L_2\) Penalty

Tuning Penalty Strength \(\alpha\) using \(10\)-fold Cross-Validation

Tuning Penalty Strength \(\alpha\) in \(L_1\) Penalty

Tuning Penalty Strength \(\alpha\) using \(10\)-fold Cross-Validation

from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
# Data
poly = PolynomialFeatures(degree=5, include_bias=False)
x_poly = poly.fit_transform(
        pd.DataFrame(x1[:,1], columns=['x1']))
x_poly = np.column_stack([x_poly,x1[:,2],x1[:,1]*x1[:,2]])
# Penalty strength
alphas = np.concatenate([
    np.linspace(1e-3,10, 50), 
    np.linspace(10.1, 1000, 50)]
)
coefficients = {f'{alp}': [] for alp in alphas}
acc = []
for alp in alphas:
    # model
    model = LogisticRegression(penalty="l1", 
                               C=1/alp, solver='saga')
    score = cross_val_score(model, x_poly, y_, cv=10, 
                scoring='balanced_accuracy').mean()
    acc.append(score)
    # Fitting
    model.fit(x_poly, y_)
    coefficients[f'{alp}'] = model.coef_[0]

Tuning Penalty Strength \(\alpha\) in \(L_1\) Penalty

Tuning Penalty Strength \(\alpha\) using \(10\)-fold Cross-Validation

3.3 🎉 Conclusion

  • Logistic Regression is a powerful classification algorithm especially for binary outcomes.

  • It’s an interpretable model that provides insights into the relationship between features and the target variable.

  • It can be extended to handle non-linear decision boundaries using polynomial features.

  • Regularization techniques like \(L_1\) and \(L_2\) help prevent overfitting (especially with working with polynomial features) and improve model generalization.

  • Hyperparameter tuning, especially using cross-validation, is crucial for selecting the best model parameters.

🥳 It’s party time 🥂