Jak funguje lineární regrese

Intermediate Regression in R

Richie Cotton

Data Evangelist at DataCamp

Standardní graf jednoduché lineární regrese

Bodový graf s regresní přímkou lineární regrese.

Intermediate Regression in R

Vizualizace reziduí

Bodový graf s regresní přímkou a úsečkami od bodů k přímce znázorňujícími rezidua.

Intermediate Regression in R

Metrika pro nejlepší přizpůsobení

Nejjednodušší nápad (který nefunguje)

  • Sečtěte všechna rezidua.
  • Některá rezidua jsou záporná.

Další nejjednodušší nápad (který funguje)

  • Umocněte každé reziduum a tyto čtverce sečtěte.
  • Tato hodnota se nazývá součet čtverců.
Intermediate Regression in R

Odbočka k numerické optimalizaci

Spojnicový graf kvadratické rovnice

xy_data <- tibble(
  x = seq(-4, 5, 0.1),
  y = x ^ 2 - x + 10
)

ggplot(xy_data, aes(x, y)) + 
  geom_line()

line-quad.png

Intermediate Regression in R

Řešení rovnice pomocí kalkulu

$y = x ^ 2 - x + 10$

$\frac{\partial y}{\partial x} = 2 x - 1$

$0 = 2 x - 1$

$x = 0.5$

$y = 0.5 ^ 2 - 0.5 + 10 = 9.75$

  • Ne všechny rovnice lze takto vyřešit.
  • Řešení lze přenechat na R.

line-quad-soln.png

Intermediate Regression in R

optim()

calc_quadratic <- function(x) {
  x ^ 2 - x + 10
}
optim(par = 3, fn = calc_quadratic)
$par
[1] 0.4998047

$value
[1] 9.75

$counts
function gradient 
      30       NA 

$convergence
[1] 0

$message
NULL
Intermediate Regression in R

Drobná upřesnění

calc_quadratic <- function(coeffs) {
  x <- coeffs[1]
  x ^ 2 - x + 10
}
optim(par = c(x = 3), fn = calc_quadratic)
$par
        x 
0.4998047 

$value
[1] 9.75

$counts
function gradient 
      30       NA 

$convergence
[1] 0

$message
NULL
Intermediate Regression in R

Algoritmus lineární regrese

  1. Definujte funkci pro výpočet metriky součtu čtverců.
  2. Zavolejte optim() k nalezení koeficientů minimalizujících tuto funkci.
calc_sum_of_squares <- function(coeffs) {

intercept <- coeffs[1] slope <- coeffs[2]
# More calculation!
}
optim(
  par = ???,
  fn = ???
)
Intermediate Regression in R

Lass uns üben!

Intermediate Regression in R

Preparing Video For Download...