Slide by: Dr. Indranath Chatterjee (AI-2025) Week 4: Data preprocessing and cleaning Dr. Indranath Chatterjee Department of Computing and Mathematics, Manchester Metropolitan University, UK Email: i.Chatterjee@mmu.ac.uk 1 Why is data preprocessing important? Before feeding data to models, it’s essential to ensure the data is clean and wellstructured. “Garbage In, Garbage Out” – A key rule in Machine Learning. Slide by: Dr. Indranath Chatterjee (AI2025) 2 Slide by: Dr. Indranath Chatterjee (AI-2025) Can we directly use raw data? • Data in its raw form may look fine to us, but models are highly sensitive to noise, inconsistencies, and missing values. • Raw data often has errors, missing pieces, or even patterns that are harmful for learning. What do you think happens if we skip data preprocessing? 3 What happens with raw data? Biased predictions: ….leading to unfair or incorrect outputs. Poor generalization: …overfitting to irrelevant features in noisy data. Erratic behavior: ….high variance in raw data. Longer training time: …noise increases the complexity, forcing the model to “learn” irrelevant details. The Dirty Laundry Analogy What if we skip preprocessing? • Skipping preprocessing is like driving a car without checking its engine – it might run, but it’s bound to fail unexpectedly. • Real-world data is often noisy, inconsistent, and incomplete. Without cleaning it, the model can’t perform reliably. • Important steps like normalization, handling missing values, and stratification are ignored. • example: • Models trained on biased datasets (underrepresenting certain groups) can lead to discriminatory hiring practices. • Missing or incorrect data can cause faulty risk assessments, leading to financial losses. • Customer churn predictions failing due to noisy data. Slide by: Dr. Indranath Chatterjee (AI2025) 6 Preprocessing is Not optional! • Clean, structured data is critical for ensuring that your machine learning model performs well. • we remove biases, fix errors, and create a more uniform dataset for learning. • …without it, even the best algorithms will fail. Slide by: Dr. Indranath Chatterjee (AI-2025) 7 Data cleaning: what does “clean" data mean? • Does clean data mean perfect data? • …. not necessarily, but in ML, clean data is consistent, free of errors, and ready for analysis. • What makes data "Dirty"? • Void in data where information is unavailable (missing values). • Some data points that differ significantly from the rest of the dataset (outliers). • Irrelevant or random variations that obscure true patterns (noise). Slide by: Dr. Indranath Chatterjee (AI2025) 8 Maths notation • Missing values: • A dataset π ∈ βπ∗π , where some entries are missing, represented as πππ = πππ. • Outliers: • An outlier is a point ( π₯π ) where: π₯π − π > 3π, i.e., more than 3 standard deviations away from the mean. • Noise: • In a time series (π¦ π‘ = π π‘ + π π‘ ), noise is the random component(π π‘ ). Slide by: Dr. Indranath Chatterjee (AI2025) 9 How do missing values affect models? • Missing values can lead to incomplete training data, biased results, or failed model training. • If 20% of the data is missing, what does that mean for your model’s understanding? How would you handle this? ID Age Salary Department 1 25 50000 Sales 2 30 3 Marketing 60000 4 28 55000 5 35 70000 IT HR Slide by: Dr. Indranath Chatterjee (AI2025) 10 Alternatives for missing values: Drop or Fill? • Dropping rows: • Pros: Simple, no introduced bias. • Cons: Risk of losing important data. • Filling (process of “imputation”): • Pros: Keeps data intact. • Cons: Introduces bias if the values aren’t accurately estimated. • Dropping rows: • Removing all rows (ππ ) where any entry is (πππ). • Imputation (mean): 1 πππ = π π πππ π=1 • where (π ππ = πππ ) is replaced by the mean of the column. Slide by: Dr. Indranath Chatterjee (AI2025) 11 How do outlier s affect models? • Outliers can skew models, especially those based on distance (like KNN or regression). • In models like linear regression, a single outlier can dramatically change the slope Slide by: Indranath Chatterjee (AIofDr.the line. 12 2025) Alternatives for outliers • Remove or Keep outliers? • Removing outliers: If outliers are due to data entry errors, it makes sense to remove them. • Keeping outliers: In some cases (e.g., fraud detection), outliers may be the most important part of the data. • Transformation: Use log transformation or normalization to reduce the effect of outliers. • Log Transformation: π¦ ′ = πππ π¦ π¦ which reduces the impact of extreme values. Slide by: Dr. Indranath Chatterjee (AI2025) 13 How does noise affect models? • Noise obscures the true patterns in data, causing models to fit irrelevant fluctuations. It’s particularly problematic in timeseries and sensor data. • Noisy data model: • In time series, (π¦ π‘ = π π‘ + π π‘ ), where noise (π π‘ ) is random and can be reduced using techniques like smoothing. • Using a moving average to reduce noise: • π¦ π‘ = 1 2π+1 π π=−π π¦ π‘ + π where (π) is the window size. Slide by: Dr. Indranath Chatterjee (AI2025) 14 Handling missing data • Cleaning data with SimpleImputer • In Python’s Scikit-learn, we can use SimpleImputer to handle missing values automatically. We can replace missing values with the mean, median, or a constant. • When to use imputation? - is imputation always the best choice??? • Imputation works best when missing data is random and there are small gaps. • If large portions of data are missing, imputation may introduce too much bias. What if 30% of a column is missing? What would you do? Slide by: Dr. Indranath Chatterjee (AI2025) 15 Converting data types • Numerical to categorical: • We can find the DataFrame’s [dtypes] property to see the data type of each column. • Note that if they are all numeric. This is fine in terms of our predictive features, • ….but we would expect a “categorical” target feature. We can make this conversion by using the DataFrame’s [replace()] method. Slide by: Dr. Indranath Chatterjee (AI2025) 16 One-hot encoding • Categorical to numerical: • Another commonly required step is to convert a categorical predictive feature into a numerical one. • Performing one-hot encoding is important because it ensures that different categories look equally different to a model. We can do it using [get_dummies()] function: • … detailed lecture on Moodle video…. Slide by: Dr. Indranath Chatterjee (AI2025) 17 Stratified sampling Slide by: Dr. Indranath Chatterjee (AI2025) 18 What if our dataset is imbalanced? • Imbalanced datasets can lead to poor model performance, especially in classification tasks. • A model might become biased towards the majority class, ignoring the minority class. • What is “stratified sampling”? • Stratified sampling divides the data into distinct strata (subgroups) based on class labels. • Each stratum is sampled proportionally to its representation in the whole dataset. Slide by: Dr. Indranath Chatterjee (AI2025) 19 Slide by: Dr. Indranath Chatterjee (AI-2025) Why use stratified sampling for classificatio n? • Ensures that each class is represented proportionally in both training and test sets. • Helps in better evaluation of the model performance for each class. • Stratified sampling proportion: ππ Stratum Proportion = π where ππ is the number of samples in class (π) and (π) is the total number of samples. 20 Risks of Random Sampling • What if we used Random Sampling instead? • …can result in an imbalanced representation of classes in the training/test sets. This can lead to overfitting on the majority class and poor generalization for the minority class. • Risk of imbalance: • πΆπππ π πππ‘ππ ππ π πππππ = ππ. ππ π ππππππ ππ ππππ π πππ‘ππ ππ. ππ π ππππππ • When might Random Sampling be fine? • If the dataset is large and balanced, random sampling might still provide good results. • For certain algorithms that handle imbalance well, like tree-based methods. Slide by: Dr. Indranath Chatterjee (AI2025) 21 Normalization vs. Standardization Slide by: Dr. Indranath Chatterjee (AI2025) 22 Why do we need to scale data? • Scaling ensures that features contribute equally to the distance calculations and model training. • Algorithms that rely on distance measures (like KNN, SVMs) are sensitive to the scale of features. Slide by: Dr. Indranath Chatterjee (AI2025) 23 Normalization vs. Standardization • Normalization: scales data to a fixed range, typically [0, 1]. x − xmin x′ = xmax − xmin • Standardization: scales data to have a mean of 0 and a standard deviation of 1. x−μ x′ = σ Slide by: Dr. Indranath Chatterjee (AI-2025) 24 When to use Normalization vs. Standardization? • Normalization is useful when features have different units or scales. • Standardization is useful when features are normally distributed or when the algorithm assumes data is centered around zero. Tip: Normalization is often used for neural networks; standardization is preferred for SVMs. Slide by: Dr. Indranath Chatterjee (AI2025) 25 Consequences of not scaling data… • What happens if we don’t scale data? • … lead to poor model performance and biased results. • … unscaled data can skew distance calculations (for algorithms sensitive to feature scaling). • unscaled features can disproportionately affect the distance measure calculation (for two points π₯ and π¦ in a highdimensional space). Slide by: Dr. Indranath Chatterjee (AI2025) 26 Cross-validation: why not just a Train-Test split? Slide by: Dr. Indranath Chatterjee (AI-2025) 27 Why isn’t splitting the data once (TrainTest) good enough? • A single train-test split may not provide a robust estimate of model performance. • Performance metrics can be sensitive to how the data is split. • What is cross-validation? • … involves splitting the dataset into multiple subsets to ensure a more reliable estimate of model performance. • commonly used method: k-fold cross-validation. • k-Fold Cross-Validation Formula: 1 CV Error = π π Errorπ π=1 where Errorπ is the error on the π−th fold. • Example: for k=5, the dataset is divided into 5 parts. The model trains on 4 parts andSlide tests the remaining by: Dr.on Indranath Chatterjee (AI- 1 part. This process 28 2025) is repeated 5 times. Why isn’t splitting the data once (TrainTest) good enough? • Alternatives: Leave-One-Out, Stratified k-Fold, and more. • Leave-One-Out (LOO): Each data point is used as a single test set while the rest are training data (for a dataset with 100 samples, the model will be trained 100 times, each time leaving out one sample for testing). • Stratified k-Fold: Ensures each fold has a proportional representation of each class. • When to use each method? Slide by: Dr. Indranath Chatterjee • Choosing the(AI-2025) right method depends on 29 dataset size and characteristics. Choosing the right (CV) method - when to use which method? •Large datasets: •k-Fold (e.g., 10fold) is practical and efficient. •Small datasets: •LOOCV provides a more thorough validation but is computationally expensive. •Imbalanced datasets: •Stratified k-Fold ensures balanced class representation. Slide by: Dr. Indranath Chatterjee (AI2025) 30 Preventing overfitting with cross-validation Overfitting happens when the model learns patterns that are specific to the training data but don't generalize well to unseen data. • Signs of overfitting: • High accuracy on training data, low accuracy on validation/test data. • Model is too complex (e.g., too many parameters, over-engineered features). How cross-validation helps prevent overfitting? • … by training on different subsets of the data and testing on others, crossvalidation helps the model generalize better. • … each fold acts as a mini validation set, ensuring that no single part of the data dominates the model's learning. • … helps ensure the model generalizes well to unseen data. Slide by: Dr. Indranath Chatterjee (AI2025) 31 Bias-variance tradeoff in CV • Cross-validation helps strike a balance between bias and variance: • High Bias (underfitting): model is too simple, cannot capture the underlying patterns. • High Variance (overfitting): model is too complex, learns noise and random fluctuations in the training data. Cross-validation helps us find the "sweet spot." Slide by: Dr. Indranath Chatterjee (AI2025) 32 Validation and Testing: what’s the difference? Why do we need separate validation and test sets? Validation set: Used to tune model parameters and select the best model. After training a model on a training set, the validation set helps adjust hyperparameters. Finally, the test set evaluates how well the model performs on completely unseen data. Test set: Used to evaluate the final model’s performance, providing an unbiased assessment. Slide by: Dr. Indranath Chatterjee (AI2025) 33 Validation and Testing: what’s the difference? • Purpose of the Validation set: • …is used to fine-tune model parameters, select the best model, and avoid overfitting to the training set. • Adjusting learning rate or regularization strength based on validation set performance. • Purpose of the Test set: • The test set provides a final, unbiased performance evaluation of the model. • It is crucial for understanding how the model will perform on new, unseen data. • Final model accuracy or F1 score on the test set. Slide by: Dr. Indranath Chatterjee (AI2025) 34 Validation and Testing: what’s the difference? • Risks of overfitting to Validation data (danger of overfitting to validation data): • Repeated tuning on the validation set can lead to a model that performs well on validation but poorly on the test set. Ensures that validation and test sets remain untouched until final evaluation. • Frequent adjustments based on validation results can lead to models that are too specifically tuned to validation data, reducing generalization. Slide by: Dr. Indranath Chatterjee (AI2025) 35 Data Leakage: what is it and why is it dangerous? Slide by: Dr. Indranath Chatterjee (AI2025) 36 Real-world problem: too good to be true? • What if our model performs too well? • For example, “Your model achieves 99% accuracy on the training set” —sounds great, right? But what if this performance is inflated? What might be going wrong? Slide by: Dr. Indranath Chatterjee (AI2025) 37 What is data leakage? • Data leakage happens when the model accidentally gets access to information from the test or validation set during training. • This gives an unfair advantage and inflates performance metrics. • Using target features (like salary, age, or income) directly in your training data. Improper scaling by fitting a scaler on the entire dataset rather than only on training data. • Let (πtrain , πtest , π¦train , π¦test ) represent the train/test sets. Data leakage occurs if: π πtrain ∪ πtest = π¦train ∪ π¦test where the model π ⋅ mistakenly learns patterns from both the train and test data, inflating accuracy. Slide by: Dr. Indranath Chatterjee (AI2025) 38 Why Is data leakage dangerous? • It falsely inflates the model's performance metrics. • Models appear to perform well during training but fail to generalize to new data. “In a credit scoring model, if a future payment history (target) leaks into the training data, the model will have perfect accuracy but be useless in the real world.” Slide by: Dr. Indranath Chatterjee (AI2025) 39 How to detect and avoid data leakage • Common signs of data leakage: • unrealistically high accuracy on the training set?? • identical or nearly identical predictions on the training and validation sets?? • Ways to avoid….. : • Always split data into train/validation/test before any processing. • Ensure that scalers, encoders, or transformations are fitted only on training data, not test/validation sets. If you scale data using StandardScaler, make sure you fit it on X_train only: scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) Slide by: Dr. Indranath Chatterjee (AIX_test_scaled = scaler.transform(X_test) 2025) 40 Key takeaways… Data cleaning: Stratified sampling: •Why clean data? To remove noise, handle missing values, and ensure data integrity. •Alternatives: Drop vs. Impute missing values. •Why stratify? To maintain class balance in training and test sets. Normalization vs. Standardization: •Why scale? To prevent features with larger scales from dominating the model. •When to use: Neural networks (Normalization), SVMs (Standardization). Cross-validation: •Why use it? To get a better estimate of model performance across different data splits. •Alternatives: K-fold vs. Stratified K-fold. Data leakage: Pipelines: •Why dangerous? It gives models access to future data and falsely inflates metrics. •Solution: Ensure separation of training and testing processes. •Why use them? To automate and organize the preprocessing steps while ensuring consistency. Slide by: Dr. Indranath Chatterjee (AI2025) 41 Thank you… Slide by: Dr. Indranath Chatterjee (AI2025) 42
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )