Handling Overfitting and Imbalanced Data
Two common problems can ruin a model: learning too much from the training data and ignoring rare cases. This topic shows you how to recognize both and apply practical fixes.
Understanding Overfitting and Underfitting
Overfitting happens when a model learns the training data too closely, including its noise. It scores very high on training data but poorly on new data. It is like a student who memorizes answers but cannot solve new questions.
Underfitting is the opposite. The model is too simple to capture the real patterns, so it performs poorly on both training and test data.
To spot these, compare training and test scores. A big gap points to overfitting. Low scores on both point to underfitting. The goal is a balanced model that performs well on both.
Regularization Techniques
Regularization adds a penalty for complexity, which keeps the model from fitting noise. In linear models, Ridge regression and Lasso regression are the most common forms. Ridge shrinks coefficients, and Lasso can shrink some to zero, which also selects features.
from sklearn.linear_model import Ridge
model = Ridge(alpha=1.0)
model.fit(X_train, y_train)For tree models, you can limit the depth, the number of leaves, or the minimum samples per split. For ensembles, you can use fewer trees or a smaller learning rate.
Other ways to reduce overfitting include getting more data, removing unnecessary features, and using cross-validation. Often a combination works best.
Handling Imbalanced Classes
Imbalanced data means one class is much rarer than the others. Fraud, disease, and customer churn are typical cases. Models trained on such data often learn to predict only the common class.
First, use the right metrics. Look at precision, recall, F1-score, and AUC instead of accuracy alone. This shows how well the model handles the rare class.
Next, check that your split keeps the class ratio. Use stratify=y in train_test_split so both the training and test sets have the same balance.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)Resampling and Class Weights
Resampling changes the training data to balance the classes. Oversampling adds more copies or synthetic examples of the rare class. Undersampling removes some examples of the common class.
SMOTE is a popular oversampling method that creates new synthetic samples. It comes from the imbalanced-learn library. Apply resampling only to the training data, never to the test data.
Another simple option is class weights. Many models accept class_weight="balanced", which makes the model pay more attention to the rare class. It is easy to use and often works well.
model = RandomForestClassifier(class_weight="balanced", random_state=42)Data Science Lifecycle Tutorial
Wesline Rinisha








