One of the most famous scientific discoveries was Newton's laws of motion. The laws allowed people to make predictions. For example, the acceleration for an object can be predicted given the applied force and the mass of the object. Making predictions remains a popular endeavour. This post explains the simplest way to predict an outcome for a new value, given a set of points.
To explain the concepts, data on apples and pears is generated. Underlying relations for the generated data are known. The known relations can be compared to the results from the regression.
The goal is to predict whether a fruit is an apple or a pear. Say we have a sample of size . Say the sample consist of two properties for each fruit, namely
The properties for the fruit at index are respectively denoted by and . Prediction will be done for the fruit type, which is denoted by . The sample indices can be visualised as follows.
Let half of the elements be apples and half of the elements be pears. So, is even. Let
Let the height and fruit type be correlated. To this end define
Let the height and width also be correlated. Define the width to be 0.6 times the height. Specifically,
In Julia, this can be defined as
using DataFrames using Distributions using Random using Statistics r_2(x) = round(x; digits=2) Random.seed!(18) n = 12 I = 1:n Y = [i % 2 != 0 for i in I] H = r_2.([y == "apple" ? rand(Normal(10, 1)) : rand(Normal(12, 1)) for y in Y]) W = r_2.([0.6h for h in H]) df = DataFrame(I = I, H = H, W = W, Y = Y)
A simple linear regression fits a line through points in two dimensions. It should be able to infer the relation between and .
using Gadfly # These two are useful for plotting. wmin = minimum(W) - 0.2 wmax = maximum(W) + 0.2 plot(df, x = :W, y = :H)
The algorithmic way to fit a line is via the method of least squares. Any straight line can be described by a linear equation of the form , where the first parameter is the intercept with and the second parameter is the slope. Adding an error , and rewriting gives
An algorithm could now be defined to naively minimize the sum of all the errors
with respect to the choice of and . This would not always result in a well fitted line because errors might cancel each other out. For example, when and , then . This is solved by squaring the errors. The method of least squares minimizes
with respect to the choice of and (Rice (2006)). The simplest estimator for the points is the mean. We can plot this and show horizontal lines for the errors.
# Linear and generalized linear models (GLMs). using GLM m = mean(H) plot(df, x = :W, y = :H, Geom.point, yintercept = [m], Geom.hline(), layer(xend = :W, yend = [m], Geom.segment()) )
We can generalize the sum of squares error calculation to
for arrays and .
S(U, V) = sum((U .- V).^2)
Then, the squared sum of the errors for this simplest estimator is
r_2(S(H, repeat([mean(H)], length(H))))
This error cannot be compared to other errors, since it is not standardized. A standardized metric would be the Pearson correlation coefficient . See the blog post on correlations for more information.
m1 = lm(@formula(H ~ W), df) # This is just a convenience function around `GLM.predict`. predict_value(model, x) = first(skipmissing(predict(model, DataFrame(W = [x])))) plot(df, x = :W, y = :H, Geom.point, layer(x -> predict_value(m1, x), wmin, wmax) )
The intercept and slope for the fitted line are
intercept(linear_model) = coef(linear_model) slope(linear_model) = coef(linear_model)
r_2(intercept(m1)) = -0.03 r_2(slope(m1)) = 1.67
Next, lets try to estimate the relation between and . The method of least squares is unable to calculate an error for "apple" and "pear". A work-around is to encode "apple" as 0 and "pear" as 1. A line can now be fitted.
digits = [i % 2 != 0 ? 0 : 1 for i in I] df[:, :Y_digit] = digits m2 = lm(@formula(Y_digit ~ W), df) plot(df, x = :W, y = :Y_digit, xmin = [wmin], xmax = [wmax], Geom.point, layer(x -> predict_value(m2, x), wmin, wmax), layer(y = predict(m2), Geom.point) )
As can be observed, the model does not take into account that is a binary variable. The model even predicts values outside the expected range, that is, values outside the range 0 to 1. A better fit is the logistic function.
m3 = glm(@formula(Y_digit ~ W), df, Binomial(), LogitLink()) plot(df, x = :W, y = :Y_digit, Geom.point, layer(x -> predict_value(m3, x), wmin, wmax), layer(y = predict(m3), Geom.point) )
The correlation coefficient should not be used to compare the models, since the logistic model only predicts the class. In other words, the logistic model is a classificatier. Classification accuracy is a better metric:
accuracy(trues, pred) = count(trues .== pred) / length(pred)
The threshold is set to 0.5 to get a binary prediction from both models. More precisely: let denote the prediction for , and denote the binary prediction for . For each prediction
binary_values(model) = [0.5 < x ? 1 : 0 for x in predict(model)]
The least squares error and accuracy for both models are as follows.
DataFrame( model = ["Linear regression", "Logistic regression"], S = r_2.([S(digits, predict(m2)), S(digits, predict(m3))]), accuracy = r_2.([accuracy(digits, binary_values(m2)), accuracy(digits, binary_values(m3))]) )
As can be seen, the error is lower for the logistic regression. However, for the accuracy both models score the same in this case. This is due to the fact that there is only a very small area where the linear and logistic model make different predictions. When this area becomes bigger (for example, when doing regression in multiple dimensions) or when more points lie in this area, then the accuracy for the logistic regression will be better compared to the linear regression.