| |
| |
|
|
| robust_regression <- function(X, y) { |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| X_with_intercept <- cbind(1, X) |
| |
| |
| |
| XtX <- t(X_with_intercept) %*% X_with_intercept |
| Xty <- t(X_with_intercept) %*% y |
| |
| |
| coefficients <- solve(XtX, Xty) |
| |
| |
| predictions <- X_with_intercept %*% coefficients |
| |
| |
| residuals <- y - predictions |
| |
| |
| return(list( |
| coefficients = coefficients, |
| predictions = predictions, |
| residuals = residuals |
| )) |
| |
| } |
|
|
| |
| calculate_metrics <- function(y_true, y_pred, residuals) { |
| n <- length(y_true) |
| |
| |
| mse <- mean(residuals^2) |
| |
| |
| mae <- mean(abs(residuals)) |
| |
| |
| ss_res <- sum(residuals^2) |
| ss_tot <- sum((y_true - mean(y_true))^2) |
| r_squared <- 1 - (ss_res / ss_tot) |
| |
| |
| |
| medae <- median(abs(residuals)) |
| |
| |
| outlier_threshold <- 2 * sd(residuals) |
| outlier_percentage <- sum(abs(residuals) > outlier_threshold) / n |
| |
| return(list( |
| mse = mse, |
| mae = mae, |
| r_squared = r_squared, |
| medae = medae, |
| outlier_robustness = 1 - outlier_percentage |
| )) |
| } |
|
|
| |
| main <- function() { |
| |
| |
| |
| |
| result <- robust_regression(X, y) |
| |
| |
| metrics <- calculate_metrics(y, result$predictions, result$residuals) |
| |
| return(metrics) |
| } |