Download Missing Value Handling in Machine Learning: Imputation Techniques Compared and more Assignments Mathematics in PDF only on Docsity!
Question 14.
The breast cancer data set breast-cancer-wisconsin.data.txt
- Use regression to impute values for the missing data.
- Use regression with perturbation to impute values for the missing data.
- (Optional) Compare the results and quality of classification models (e.g., SVM, KNN) build using (1) the data sets from questions 1,2,3; (2) the data that remains after data points with missing values are removed; and (3) the data set when a binary variable is introduced to indicate missing values.
breast cancer
ues Mean/Mode Imputation
Load necessary libraries
library (dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library (tidyr) library (caret)
Loading required package: ggplot
Loading required package: lattice
library (e1071) library (class)
Read the data
data <- read.csv ("breast-cancer-wisconsin.data.txt", header = FALSE)
Replace ‘?’ with NA
data[data == "?"] <- NA
Mean/Mode Imputation
data <- data %>% mutate ( across ( everything (), ~ ifelse ( is.na (.), ifelse ( is.numeric (.), mean (., na.rm = TRUE), as.numeric ( names ( sort ( table (., useNA = "no"), decreasing = TRUE) [ 1 ]))), .)))
Prepare data for modeling
X <- data[, - ncol (data)] y <- data[, ncol (data)] X <- as.data.frame ( lapply (X, as.numeric)) if ( any ( is.na (X))) { stop ("There are still NA values in the feature set.") }
Split the data into training and testing sets
set.seed ( 42 ) train_index <- createDataPartition (y, p = 0.8, list = FALSE) X_train <- X[train_index, ] y_train <- y[train_index] X_test <- X[ - train_index, ] y_test <- y[ - train_index]
Standardize features
X_train <- scale (X_train) X_test <- scale (X_test)
SVM model with class weights
y_train <- as.factor (y_train) str (y_train)
Factor w/ 2 levels "2","4": 1 1 1 1 1 1 1 1 2 2 ...
svm_model <- svm (X_train, y_train, kernel = "radial", class.weights = list (2 = 1 , 4 = 2 )) svm_predictions <- predict (svm_model, X_test) svm_accuracy <- mean (svm_predictions == y_test)
KNN model
Apply Regression Imputation
data <- regression_imputation (data)
Prepare data for modeling
X <- data[, - ncol (data)] y <- data[, ncol (data)] X <- as.data.frame ( lapply (X, as.numeric)) if ( any ( is.na (X))) { stop ("There are still NA values in the feature set.") }
Split the data into training and testing sets
set.seed ( 42 ) train_index <- createDataPartition (y, p = 0.8, list = FALSE) X_train <- X[train_index, ] y_train <- y[train_index] X_test <- X[ - train_index, ] y_test <- y[ - train_index]
Standardize features
X_train <- scale (X_train) X_test <- scale (X_test)
SVM model with class weights
y_train <- as.factor (y_train) str (y_train)
Factor w/ 2 levels "2","4": 1 1 1 1 1 1 1 1 2 2 ...
svm_model <- svm (X_train, y_train, kernel = "radial", class.weights = list (2 = 1 , 4 = 2 )) svm_predictions <- predict (svm_model, X_test) svm_accuracy <- mean (svm_predictions == y_test)
KNN model
knn_predictions <- knn (train = X_train, test = X_test, cl = y_train, k = 3 ) knn_accuracy <- mean (knn_predictions == y_test)
Output accuracy
cat ("SVM Accuracy:", svm_accuracy, " \n ")
SVM Accuracy: 0.
cat ("KNN Accuracy:", knn_accuracy, " \n ")
KNN Accuracy: 0.
confusion_matrix
confusion_matrix_svm <- table (Predicted = svm_predictions, Actual = y_test) confusion_matrix_knn <- table (Predicted = knn_predictions, Actual = y_test) print (confusion_matrix_svm)
Actual
Predicted 2 4
2 94 1
4 5 39
print (confusion_matrix_knn)
Actual
Predicted 2 4
2 94 3
4 5 37
use Regression with Perturbation
Function for Regression with Perturbation
regression_with_perturbation <- function (data) { for (col in colnames (data)) { if ( any ( is.na (data[[col]]))) { model_data <- data %>% select ( - all_of (col)) model_data <- model_data[ complete.cases (model_data), ] target <- data[[col]][ !is.na (data[[col]])] model <- lm (target ~ ., data = model_data) missing_data <- data[ is.na (data[[col]]), ] predictions <- predict (model, newdata = missing_data) noise <- rnorm ( length (predictions), mean = 0 , sd = 0.1) data[[col]][ is.na (data[[col]])] <- predictions + noise } } return (data) } data <- regression_with_perturbation (data)
Prepare data for modeling
X <- data[, - ncol (data)] y <- data[, ncol (data)] X <- as.data.frame ( lapply (X, as.numeric)) y <- as.factor (y) set.seed ( 42 ) train_index <- createDataPartition (y, p = 0.8, list = FALSE) X_train <- X[train_index, ] y_train <- y[train_index] X_test <- X[ - train_index, ]
From the results, both SVM and KNN perform well after using mean/mode
imputation, with accuracies of 0.9568 and 0.9424 respectively. Although this
method may introduce some bias (especially as mean imputation may
underestimate the data variance), for your dataset, this simple imputation method
still provides relatively good results.
2. Regression Imputation Results
SVM Accuracy: 0.
KNN Accuracy: 0.
Analysis:
Regression Imputation uses other variables to predict missing values through a
regression model, considering the correlations between variables. This method is
generally more accurate than simple mean or mode imputation.
However, the results show that the accuracies of SVM and KNN are identical to those
obtained with mean/mode imputation. This indicates that for this specific dataset
and models, regression imputation did not significantly improve model
performance. A possible reason is that the correlations between variables in the
dataset are weak, or the regression model’s predicted values are not very different
from the mean imputed values, leading to similar effects on model performance.
3. Regression with Perturbation Results
SVM Accuracy: 0.
KNN Accuracy: 0.
Analysis:
Regression with Perturbation adds a random perturbation to the predicted values
from regression imputation to introduce uncertainty and avoid the determinism and
variance underestimation issues of regression imputation.
However, the results show a slight decline in accuracies for both SVM and KNN,
dropping to 0.9496 (SVM) and 0.9353 (KNN). While adding perturbation better
reflects data uncertainty, the introduction of random noise may cause the predicted
values to deviate from the true values, slightly lowering the model’s accuracy. This
suggests that the introduction of perturbation did not provide significant
improvements for this dataset and may have increased the prediction error.
Summary and Conclusion
Mean/Mode Imputation and Regression Imputation perform nearly identically for
both SVM and KNN models, indicating that in this dataset, using a simple imputation
method can already achieve high classification accuracy. This suggests that in some
cases, regression imputation does not significantly outperform simple imputation
methods.
Regression with Perturbation, while accounting for data uncertainty, performed
slightly worse in this dataset. This may be due to the added random perturbation
introducing additional noise, affecting the model’s accuracy. Perturbation-based
imputation is more suitable in situations where there is significant uncertainty or
severe variance underestimation in the data, but in this dataset, simple regression
imputation already performs well enough.
Remove rows with missing values
library (dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library (tidyr) library (caret)
Loading required package: ggplot
Loading required package: lattice
library (e1071) library (class) data <- read.csv ("breast-cancer-wisconsin.data.txt", header = FALSE) data[data == "?"] <- NA data[] <- lapply (data, function (x) as.numeric ( as.character (x))) data_no_na <- na.omit (data) X_no_na <- data_no_na[, - ncol (data_no_na)] y_no_na <- data_no_na[, ncol (data_no_na)] str (X_no_na)
'data.frame': 683 obs. of 10 variables:
$ V1 : num 1000025 1002945 1015425 1016277 1017023 ...
$ V2 : num 5 5 3 6 4 8 1 2 2 4 ...
$ V3 : num 1 4 1 8 1 10 1 1 1 2 ...
$ V4 : num 1 4 1 8 1 10 1 2 1 1 ...
$ V5 : num 1 5 1 1 3 8 1 1 1 1 ...
$ V6 : num 2 7 2 3 2 7 2 2 2 2 ...
$ V7 : num 1 10 2 4 1 10 10 1 1 1 ...
$ V8 : num 3 3 3 3 3 9 3 3 1 2 ...
data[[i]][ is.na (data[[i]])] <- mean (data[[i]], na.rm = TRUE) } } X <- data[, - ncol (data)] y <- factor (data[[ ncol (data)]]) print ( paste ("Feature matrix dimensions:", paste ( dim (X), collapse = "x"))) print ( paste ("Number of classes in response:", nlevels (y))) print ( paste ("Class distribution:", paste ( table (y), collapse = ", "))) return ( list (X = as.matrix (X), y = y)) } evaluate_models <- function (X, y) { tryCatch ({ set.seed ( 42 ) train_index <- createDataPartition (y, p = 0.8, list = FALSE) X_train <- X[train_index, ] y_train <- y[train_index] X_test <- X[ - train_index, ] y_test <- y[ - train_index] print ( paste ("Training set dimensions:", paste ( dim (X_train), collapse = "x"))) print ( paste ("Training set class distribution:", paste ( table (y_train), collapse = ", "))) X_train_scaled <- scale (X_train) X_test_scaled <- scale (X_test, center = attr (X_train_scaled, "scaled:center"), scale = attr (X_train_scaled, "scaled:scale")) print ("Training SVM model...") svm_model <- svm (x = X_train_scaled, y = y_train, type = "C-classification", kernel = "radial", cost = 1 , scale = FALSE, probability = TRUE) print ("Making SVM predictions...") svm_predictions <- predict (svm_model, X_test_scaled) svm_accuracy <- mean (svm_predictions == y_test) print ("Training KNN model...") knn_predictions <- knn (train = X_train_scaled, test = X_test_scaled, cl = y_train, k = 3 )
knn_accuracy <- mean (knn_predictions == y_test) svm_cm <- table (Predicted = svm_predictions, Actual = y_test) knn_cm <- table (Predicted = knn_predictions, Actual = y_test) return ( list ( svm_accuracy = svm_accuracy, knn_accuracy = knn_accuracy, svm_confusion = svm_cm, knn_confusion = knn_cm, svm_model = svm_model )) }, error = function (e) { print ( paste ("Error details:", e $ message)) print ("Stack trace:") print ( sys.calls ()) return (NULL) }) } main <- function () { tryCatch ({ print ("Preparing data...") data_prep <- prepare_data ("breast-cancer-wisconsin.data.txt") print ("Evaluating models...") results <- evaluate_models (data_prep $ X, data_prep $ y) if ( !is.null (results)) { cat (" \n Model Performance Results: \n ") cat ("SVM Accuracy:", round (results $ svm_accuracy, 4 ), " \n ") cat ("KNN Accuracy:", round (results $ knn_accuracy, 4 ), " \n ") cat (" \n SVM Confusion Matrix: \n ") print (results $ svm_confusion) cat (" \n KNN Confusion Matrix: \n ") print (results $ knn_confusion) cat (" \n SVM Model Summary: \n ") print ( summary (results $ svm_model)) } }, error = function (e) { print ( paste ("Error in main execution:", e $ message)) print ("Stack trace:") print ( sys.calls ()) }) } main ()
[1] "Preparing data..."
[1] "Initial data dimensions: 699x11"
which could lead to biased results, especially if the missing data is not randomly
distributed (i.e., certain types of data points are more likely to be missing).
In this case, it seems the remaining dataset was large enough and representative
enough to yield strong model performance. However, this result could be misleading
if the data points that were removed had some underlying patterns that could affect
the model’s generalizability to new, unseen data.
2. Creating a Binary Indicator for Missingness
SVM Accuracy: 0.
KNN Accuracy: 0.
Analysis:
In this approach, instead of removing missing values, a binary indicator is added to
the dataset to explicitly mark whether a value was missing. This can capture any
potential information or patterns related to missing data (e.g., missing values might
be more frequent in certain classes).
The accuracies for both SVM and KNN decrease compared to the results when
missing data was removed, with SVM accuracy dropping to 0.9496 and KNN
accuracy to 0.9209. While this is still relatively good performance, it is lower than
the previous approach.
The drop in accuracy can be attributed to a few factors:
Increased Model Complexity: The binary indicator introduces additional complexity
to the model. The model now needs to learn how to handle this extra feature, which
may not always provide useful information.
Noisy Data: If the binary indicator does not correlate strongly with the target
variable, it could act as noise and slightly reduce the model’s ability to make
accurate predictions. This could be more pronounced in KNN, which is particularly
sensitive to noisy features since it relies on distance-based metrics.
Loss of Information: While this method retains all data points, it does not actually
"recover" any missing values. If the missing values are important for prediction, the
model might struggle to achieve as high accuracy as it does with complete data (as
in the removal approach).
Summary of Results
Approach SVM Accuracy KNN Accuracy
Removing Rows with Missing Values 0.9852 0.
Binary Indicator for Missingness 0.9496 0.
Approach SVM Accuracy KNN Accuracy
Conclusion and Interpretation:
Removing Rows with Missing Values leads to the highest accuracies for both SVM
and KNN models. This is expected, as removing missing values leaves a clean dataset
that allows the models to make accurate predictions. However, this approach risks
introducing bias if the removed data is not random, potentially reducing the model's
generalizability to unseen data.
Introducing a Binary Indicator to flag missingness results in slightly lower accuracy
for both models. The drop in accuracy suggests that the missingness information is
not strongly related to the target variable in this case, and the additional complexity
may be introducing some noise, particularly for KNN, which is sensitive to irrelevant
or noisy features.
Comparative Analysis Report of Transfer Value Processing Methods
1. Performance Overview
Accuracy Comparison Across Methods:
Removing Rows with Missing Values
SVM: 98.52%
KNN: 97.78%
Mean/Mode Imputation
SVM: 95.68%
KNN: 94.24%
Regression Imputation
SVM: 95.68%
KNN: 94.24%
Regression with Perturbation
SVM: 94.96%
KNN: 93.53%
Binary Indicator for Missingness
SVM: 94.96%
A quick, straightforward solution is needed.
2.3 Regression Imputation (Moderate Performance)
Advantages:
Accounts for correlations between variables, providing a more informed estimate.
Delivers stable performance (comparable to mean imputation).
Supported by a solid theoretical foundation.
Disadvantages:
More computationally complex.
May lead to overfitting, especially with smaller datasets.
Performance heavily depends on the accuracy of the regression model.
When to Use:
When strong relationships exist between variables.
Sufficient computational resources are available.
The dataset is large enough to build reliable regression models.
2.4 Regression with Perturbation (Slightly Lower Performance)
Advantages:
Introduces randomness, helping to prevent overfitting.
Better preserves the variability in the data.
Still achieves good performance (SVM: 94.96%).
Disadvantages:
Performance is slightly lower compared to standard regression imputation.
Adds uncertainty to the model, which could reduce stability.
Results may be less consistent across different runs.
When to Use:
Situations where maintaining natural variability is important.
When working with large datasets that can tolerate some randomness.
When the model's stability is less critical.
2.5 Binary Indicator for Missingness (Lowest Performance)
Advantages:
Retains missing information by treating missingness itself as a feature.
Relatively easy to implement.
Can capture patterns related to missing data.
Disadvantages:
Achieves the lowest performance (especially in KNN: 92.09%).
Increases the dimensionality of the data.
May introduce spurious correlations, leading to poorer generalization.
When to Use:
When missingness may carry important information.
To preserve missingness patterns in the dataset.
When increasing feature dimensions has a minimal impact on the model's
performance.
3. Model Performance Analysis
3.1 SVM vs. KNN
SVM outperformed KNN across all methods.
SVM exhibited stronger robustness to different imputation methods.
KNN was more sensitive to data quality, showing greater performance variation
across methods.
3.2 Stability of Results
Mean/Mode Imputation and Regression Imputation yielded similar performance.
Regression with Perturbation slightly reduced performance but could enhance
generalization.
Row Removal achieved the highest performance but may be prone to overfitting due
to reduced sample size.
4. Recommendations and Best Practices
Data Evaluation
Start by assessing the proportion and pattern of missing values.
Analyze the missingness mechanism (MCAR, MAR, MNAR).
Consider the correlation between variables when choosing an imputation strategy.
Describe a situation or problem from your job, everyday life, current events, etc., for
which optimization would be appropriate. What data would you need?
Bus System Optimization Process Flow
In many cities, bus systems face competing objectives: they need to serve as many
passengers as possible, maintain reasonable wait times, minimize transit duration,
and do all this within budget constraints. Some specific pain points include:
Overcrowded buses during peak hours
Nearly empty buses during off-peak times
Long wait times at certain stops
Inefficient routes that take too long
To optimize this system, we'd need several key data points:
1. Ridership Data:
Number of passengers getting on/off at each stop by time of day
Origin-destination patterns
Peak usage times
Common transfer points
2. Operational Data:
Current route maps and schedules
Fuel/maintenance costs per route
Driver schedules and labor costs
Bus fleet capacity and availability
3. Performance Metrics:
Average wait times at stops
On-time performance
Average trip duration
Number of transfers required for common journeys
4. Geographic/Infrastructure Data:
Road network layout
Traffic patterns throughout the day
Road construction/maintenance schedules
Population density near stops
5. Customer Feedback:
Satisfaction surveys
Common complaints
Most requested route changes or additions
1.Initial Analysis:
Cross-reference ridership data with time of day to identify peak demand periods
Map origin-destination patterns to understand common travel paths
Calculate load factors (passengers/capacity) for each route segment
Identify bottlenecks and underutilized routes
2.Route Optimization:
Create express routes for heavily traveled corridors
Adjust route frequencies based on demand patterns
Optimize transfer points to minimize wait times
Consider smaller buses for low-demand routes/times
3.Cost Efficiency:
Calculate cost per passenger mile for each route
Identify opportunities to consolidate overlapping routes
Optimize driver schedules to match demand patterns
Balance service quality with operational costs
4.Implementation Strategy:
Simulate changes to predict impact
Phase in changes gradually to minimize disruption
Monitor key performance indicators
Gather feedback and make adjustments
5.The goal is to find the sweet spot between:
Maximizing ridership and revenue
Minimizing operational costs
Maintaining high service quality
Meeting community needs