Linear Models
Linear Models Group 4: Abhinav, Sanket, Utkarsha, Kristin Data Sciences in the Life Sciences
Table of contents Introduction Theoretical Background Design Matrix and lm-function Standard Errors Analysis of Variance
Table of contents Introduction Theoretical Background Design Matrix and lm-function Standard Errors Analysis of Variance Co-linearity and Confounders
Introduction to Linear Models
Introduction to Linear Models For a model to be linear all of its parameters must be linear. The dependent variable and independent variables may be non-linear (for example, a parabolic model is considered linear despite having exponential independent variable)
Estimating Parameters (the Betas)
Estimating Parameters (the Betas) For any given data, virtually infinite amounts of models can be prepared. However, for the model to be useful all the parameters (betas) must be estimated. Furthermore, the model must be tested whether it is a good fit or not. For this the distance between the data points and the model must be minimised. This distance can be calculated using the least squares equation:
Estimating parameters continued..
Estimating parameters continued.. The minimum distance parameters calculated from the above equations are known as least square estimates and denoted using The residual sum of squares (RSS) is a square of sum of all these distances. lm() function in R can be used to obtain a model fit for the data. It calculates the estimate values for us along with several different other parameters.
Linear Models using R (understanding the maths behind)
Linear Models using R (understanding the maths behind) The linear model can be written in matrix form as: Simplifying further we get: The least squares equation can also be simplified further: … equation (1)
We can use calculus to find the minimum. Taking derivative of equation 1 and simplifying further we get: The equation thu
We can use calculus to find the minimum. Taking derivative of equation 1 and simplifying further we get: The equation thus obtained can be used in many data analysis situations For example: We can use this code to simulate measurements of a free falling object with random errors
Then we can calculate the least square estimates for the data and plot the model using R The calculated least square est
Then we can calculate the least square estimates for the data and plot the model using R The calculated least square estimates are saved as betahat: intercept time taken (time taken)2
The Design Matrix
The Design Matrix Measurement Experimental Units Indicator Variables “N” different entities If the experimental units have a certain characteristic or not Y = X.β + 𝟄 Use formula(), and model.matrix()
Why choice of design is important ?
Why choice of design is important ? Encoding which coefficients will fit Inter-relationship between the samples Fitting the model Least Square Estimates Myths ? Follows straightforward dictum of samples Basic information ≠ “Correct” design Define Design Matrix
Which design works ?
Which design works ? For the comparison between different groups ≧ 2 columns: Intercept Column (contains 1’s) Second Column (specifies which samples are second Our Interest ! Why ? group) Population average of the 1st group Difference in population of the 1st and the 2nd group
Encoding in R
Encoding in R factor() is an instrument to indicate the membership of the group by assigned 0’s and 1’s. Need more groups ? Note: names of the levels are irrelevant, but the order matters! Ensure separate coefficients for each group Need more variables ? factor -> group combinations Use of operators ( + , : , * ) in model.matrix().
Releveling The level which is contrasted against is called Reference level. If we want any other group to be the referen
Releveling The level which is contrasted against is called Reference level. If we want any other group to be the reference level except the default one: Use relevel() function or Provide explicit levels to the factor() call model.matrix() grabs the variable from the R Global Environment unless our data is passed explicitly as a data.frame() in the data() argument.
Continuous Vs Indicator Variables
Indicator variables assume a different Continuous Vs Indicator Variables How to do a mathematical transformation of a variable in the design formula ? mean between two groups. Continuous variables assume a very specific relationship between outcome and predictor values. Why are we interested in using the continuous over indicator ? Example : Testing the dosages of Use I() to inhibit interpretation of formula() operators so they can be used as arithmetically, in model.matrix(). treatment to find a specific relationship between a measured quantity and the dosage.
The Mathematics behind lm() function
The Mathematics behind lm() function How well your model fits the data ? Normalized using sample size and # of variables “Global” test to check at least one of the coefficients ≠ 0
Regression gets calculated and .Call calls into the C code (lm.c). The function Cdqrls: concerned with checking invarian
FORTRAN F77_CALL in lm.c calls the function dqlrs in which the LINPACK routines to compute the QR decomposition using household reflections of an n by p matrix x. compute coordinate transformations, projections, and least squares solutions. Convoluted or spaghetti code! C Regression gets calculated and .Call calls into the C code (lm.c). The function Cdqrls: concerned with checking invariants of inputs, and constructing and initializing new objects. R Constructing the design matrix: lm() conveniently works with formulas and data.frames, lm.fit() wants matrices, so moving from lm() to lm.fit() removes one layer of abstraction.
Standard Errors
Standard Errors Introduction: It is useful to think about where variance comes from. It can arise due to measuring errors, inherent randomness of a system, external factors, etc. For example, in the falling object example it comes from measurement errors. Hence, every time the experiment is performed we will get different estimates.
Delving deeper in the falling object model
Delving deeper in the falling object model Running a Monte Carlo simulation on this model will give a different estimate every time These plots represent the distribution of the calculated estimates after performing a Monte Carlo simulation. Furthermore, mean of this distribution is equal to the true parameter (-0.5g or -4.9)
● Furthermore, if Y 1 and Y 2 are independent then:
Variance-covariance matrix ● Assume that you have a vector of random variables Y. Then its covariance matrix Σ with i, j observations will be ● Here, ○ If i = j, covariance = variance, , therefore Σ = σ2I, where I is the identity matrix. ○ If i and j are independent, covariance = 0, Variance of a linear combination ● Variance-covariance matrix of a linear combination of AY of Y can be calculated using: ● Furthermore, if Y1 and Y2 are independent then: a is linear combination of Y : AY with A = (XTX)-1XT and,
Missing piece of the puzzle: σ 2
Missing piece of the puzzle: σ2 We need residuals to calculate σ2, and residuals = Which can then be used in the formula:
Analysis of Covariance (ANCOVA)
Analysis of Covariance (ANCOVA) Input Data
ANOVA Analysis
ANOVA Analysis We create a regression model taking "hp" as the predictor variable and "mpg" as the response variable taking into account the interaction between "am" and "hp". Model with interaction between categorical variable and predictor variable
This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value
This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value in both cases is less than 0.05. But the interaction between these two variables is not significant as the p-value is more than 0.05.
Model without interaction between categorical variable and predictor variable
This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value
This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value in both cases is less than 0.05
Comparing Two Models
Co-linearity
Co-linearity change in one independent variable X by 1 unit when holding all other independent variables constant! mean change in dependent variable by units Co-linearity occurs when some of the independent variables are not independent from each other i.e. they are correlated.
Matrix Algebra behind Co-linearity
Matrix Algebra behind Co-linearity The third column is collinear with the first two columns i.e. it can be written as a linear combination of the other columns.
Matrix Algebra behind Co-linearity
Matrix Algebra behind Co-linearity > infinite number of solutions
Matrix Algebra behind Co-linearity
Matrix Algebra behind Co-linearity Design Matrix X Residuals
Effects of Co-linearity
Effects of Co-linearity coefficients become very sensitive to small changes in the model and hard to interprete reduces precision of estimated coefficients and statistical power but: does not affect the prediction of the model, only the coefficient interpretability
Confounding variables
Confounding variables influence both the dependent variable and independent variable example study design: 4 treatments (A, B, C, D) and two mice per study group Confounder: Sex Treatment (A, B, C, D) Effect
Removing Confounders
Removing Confounders small changes in study design can remove the Co-Linearity within the matrix > unique least square solution exists
Removing Confounders
Removing Confounders rank of a matrix A is defined as the number of linear independent columns of A if Rank(A) < NumberOfColumns(A), then the LSE are not unique in R: qr()$rank function returns the rank of a matrix A= Matrix A has no unique LSE, matrix B has! B= rank(A) = 4 rank(B) = 5
Thank you for paying attention! Any questions?