2024-02-03

What is Linear Regression?

Simple Linear Regression is a statistical estimation of the linear relationship between one response variable and one explanatory variable.

  • Response or Dependent variable (Y)
  • Explanatory or Independent variable (X)
  • Assumes a linear relationship exists.

Linear Regression produces a line best fitted to the data set.

Formulation

Line of “best fit” for all observed pairs \(y_i=\alpha x_i+\beta+\epsilon\)

-\(\beta\) is the y-intercept

-\(\alpha\) is the slope

-\(\epsilon\) is random deviation

The Slope and Intercept are calculated from the sum of least squares of the vertical deviation from the line.

In other terms the fitted line will that of the line where the sum of distance from the points is the smallest.

This is where R can excel for its ability to compute this intensive equation.

Least Squares Estimation

\(Slope = \alpha = \frac{\Sigma(x_i-\bar{x})(y_i-\bar{y})}{\Sigma(x_i-\bar{x})^2}\) , \(Intercept = \beta = \frac{\Sigma(y_i-\alpha\Sigma x_i)}{n}\)

Data Suitability

Begin with visual observation of data distribution

Data Suitability Cont…

Calling function summary() on lm() provides many useful statistics including \(R^2\) value

petals = lm(iris$Petal.Width~iris$Petal.Length)
cars = lm(mtcars$drat~mtcars$disp)
petals = summary(petals)
cars = summary(cars)

The regression summary shows the iris model covering 92.66% of all cases, whereas; the mtcars linear regression model only explains 48.79% of the data.

A higher Adjusted \(R^2\) value is generally a good indicator of data compatibility with linear regression.

Multiple regression visualized with Plotly

A 3d visualization of the relationship displacement has on the horsepower, weight and fuel economy.

Code:

fig = plot_ly(mtcars, x = ~disp, y = ~hp, z = ~mpg, height = 600,
               marker = list(color = ~wt, showscale = TRUE))
fig = fig %>% add_markers()
fig = fig %>% layout(scene = list(xaxis = list(
  title = 'Engine Displacement'),
yaxis = list(title = 'Gross horsepower'),zaxis = list(
  title = 'Miles per Gallon')),
annotations = list(x = 1.13, y = 1.03, text = 'Weight in Tons', 
xref = 'paper', yref = 'paper', showarrow = FALSE))
line3d = lm(mpg ~ hp + disp, data = mtcars)
fig = fig %>% add_trace(x = mtcars$disp , y = 45.738+.438*mtcars$disp,
z = 30.7359-0.02484*mtcars$hp-0.03035*mtcars$disp,mode = 'lines', 
type = "scatter3d", showlegend = FALSE)