Certainly! Below is an R script that creates a visualization to illustrate how the Iteratively Reweighted Least Squares (IRLS) algorithm works. This visualization will help explain the main steps of the algorithm in an intuitive manner for readers with a background in linear regression, multivariable calculus, and linear algebra.
# Load necessary libraries
library(ggplot2)
library(dplyr)
library(gridExtra)
# Generate some sample data
set.seed(123)
n <- 100
x <- runif(n, -5, 5)
y <- 2 * x + rnorm(n, sd = 2) # True model: y = 2x + noise
data <- data.frame(x = x, y = y)
# Initial guess for coefficients
beta_0 <- 0
beta_1 <- 0
# Function to calculate weights for IRLS
calculate_weights <- function(y, y_hat) {
# For simplicity, we'll use the identity link function (i.e., no transformation)
# and assume a constant variance, so weights are 1.
# In a real application, weights would be based on the variance function.
return(rep(1, length(y)))
}
# Function to perform one iteration of IRLS
irls_iteration <- function(data, beta_0, beta_1, weights) {
data$y_hat <- beta_0 + beta_1 * data$x
data$residuals <- data$y - data$y_hat
X <- model.matrix(~x, data=data) # Design matrix
W <- diag(weights) # Weight matrix
# Weighted least squares estimation
beta_new <- solve(t(X) %*% W %*% X) %*% t(X) %*% W %*% data$y
beta_0_new <- beta_new[1]
beta_1_new <- beta_new[2]
return(list(beta_0 = beta_0_new, beta_1 = beta_1_new, data = data))
}
# Perform IRLS iterations and store results for visualization
iterations <- 5
results <- vector("list", iterations)
for (i in 1:iterations) {
weights <- calculate_weights(data$y, beta_0 + beta_1 * data$x)
results[[i]] <- irls_iteration(data, beta_0, beta_1, weights)
beta_0 <- results[[i]]$beta_0
beta_1 <- results[[i]]$beta_1
}
# Create plots for each iteration
plots <- lapply(1:iterations, function(i) {
p <- ggplot(data, aes(x = x, y = y)) +
geom_point(color = "blue", alpha = 0.6) +
geom_abline(slope = results[[i]]$beta_1, intercept = results[[i]]$beta_0, color = "red") +
geom_segment(aes(x = x, y = y, xend = x, yend = y_hat),
data = results[[i]]$data,
color = "grey", alpha = 0.6) +
labs(title = sprintf("Iteration %d", i),
x = "x",
y = "y") +
theme_minimal()
return(p)
})
# Arrange plots in a grid
grid.arrange(grobs = plots, ncol = 3)
Explanation of the Code:
-
Data Generation:
- We generate 100 data points with
x values uniformly distributed between -5 and 5.
- The
y values are generated using the true model (y = 2x + \text{noise}), where the noise is normally distributed with a standard deviation of 2.
-
Initial Guess:
- We start with an initial guess for the coefficients (\beta_0) and (\beta_1), both set to 0.
-
Weight Calculation:
- For simplicity, we use uniform weights of 1. In a real application, weights would be based on the variance function.
-
IRLS Iteration Function:
irls_iteration function performs one iteration of the IRLS algorithm.
- It calculates the predicted values (\hat{y}), residuals, and the design matrix (X).
- It then performs weighted least squares estimation to update the coefficients.
-
IRLS Iterations:
- We perform 5 iterations of the IRLS algorithm, storing the results at each iteration.
-
Visualisation:
- For each iteration, we create a plot showing the data points, the current fit line and the residuals (as grey lines).
- We then arrange these plots in a grid for comparison.
Visual Explanation:
-
Data Points:
- Blue points represent the original data.
-
Fit Line:
- The red line represents the current fit after each iteration.
-
Residuals:
- Grey lines represent the residuals, i.e., the differences between the observed values and the predicted values.
How to Read the Visualization:
- Iteration 1:
- The red line is the initial fit with (\beta_0 = 0) and (\beta_1 = 0). The residuals are large because the initial guess is far from the true model.
- Subsequent Iterations:
- With each iteration, the red line (fit) gets closer to the true model. The residuals (grey lines) become shorter, indicating that the fit is improving
- By the final iteration the red line closely matches the true model.
This visualization intuitively shows how the IRLS algorithm iteratively improves the fit by adjusting the coefficients to minimise the weighted sum of squared residuals.