2024-02-04

Simple Linear Regression

Linear regression aims to fit a linear equation to the observed data such that the line summarizes the relationship between X and Y. The equation of this best- fit line is:

\[Y = \beta_0 + \beta_1X + \epsilon\]

  • \(\beta_0\) is the y-intercept.
  • \(\beta_1\) is the slope of the line.
  • X is the independent variable.
  • \(\epsilon\) is the error term which helps account for variations in Y, that are not explained by values x.
  • Y is the predicted value of the dependent variable.

Using Least Squares method

  • Step 1: for each point \((x, y)\), calculate \(x^2\), and \(xy\)
  • Step 2: sum all x, y, \(x^2\), and \(xy\)
  • Step 3: calculate the slope \(\beta_1\), where N is the number of points:

\[\beta_1 = {N \sum(xy) - \sum(x) \sum(y)\over N \sum(x^2) - (\sum(x))^2}\] - Step 4: Calculate the intercept, \(\beta_0\): \[\beta_0 = {\sum y - b \sum x \over N}\] - Step 5: assemble the components: \[Y = \beta_1X + \beta_0\]

Calculate the error term

  • use the estimated regression line to predict the value of Y for each value of X. Where \(\hat{Y_i}\) is the predicted value. \[\epsilon_i = Y_i -\hat{Y_i}\]
  • You can go a step further and calculate a summary residual such as:
    • Sum of Squared Residuals: \(\sum(\epsilon_i)^2\)
    • Mean Squared Error (MSE): \({ 1\over n} \sum(\epsilon_i)^2\)
    • Root Mean Squared Error (RMSE): \(\sqrt{{ 1\over n} \sum(\epsilon_i)^2}\)

linear regression for Setosa species

Linear regression for Versicolor species

Linear regression for Virginica species

Example code for previous slide

# This code was used to generate the previous slide

# Filter out the Virginica species
virginica <- iris %>% filter(Species == "virginica")

# Plot the data
ggplot(virginica, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() + 
  geom_smooth(formula = y ~ x, method = "lm", se = F, color = "purple") +
  ggtitle("Sepal Length versus Petal Length for Virginica") + 
  xlab("Sepal Length") +
  ylab("Petal Length")