Regression

Linear Regression

  1. Loss Function: The loss function in linear regression quantifies how well the model's predictions match the actual target values. In linear regression, the most common loss function is the Mean Squared Error (MSE). The MSE calculates the average squared difference between the predicted values and the actual target values for all data points.

  2. Optimization Criterion: The optimization criterion is the goal of finding the best-fitting line (or hyperplane in higher dimensions) that minimizes the chosen loss function. In the case of linear regression, the goal is to find the coefficients (slope and intercept) of the linear equation that minimize the MSE. This involves adjusting the coefficients to minimize the overall squared difference between the predicted and actual values.

  3. Optimization Routine: To find the optimal coefficients that minimize the MSE, an optimization routine is used. Gradient Descent is a widely used optimization algorithm for linear regression.

Metrics

Now once you have the model fit next comes the metrics to measure how good the fit is, some of the common metrics are as follows:

Feature selection

📖Explanation

  • Hypothesis testing and using p-values to understand if the feature is important or not

  • Penalized Regression or Regularization:

    📖Explanation

Elastic Net is another useful technique which combines both L1 and L2 regularization.

Assumptions

  • The error terms are normally distributed. This can be checked with a Q-Q plot

  • Error terms are independent of each other. This can be checked with a ACF plot. This can be used while checking independence while using a time-series data

  • Error terms are homoscedastic, i.e. they have constant variance. Residulas Vs Fitted graph should be flat. This means that the variability in the response is changing as the predicted value increases. This is a problem, in part, because the observations with larger errors will have more pull or influence on the fitted model.

    • If a multicollinear variable is present the coefficients swing wildly thereby affecting the interpretability of the model. P-vales are not reliable. But it doesnot affect prediction or the goodness of fit statistics.

    • To deal with multicollinearity

      • drop variables

      • create new features from existing ones

      • PCA/PLS

OLS Stats Model (Ordinary Least Square)

OLS is a stats model, which will help us in identifying the more significant features that can has an influence on the output. OLS model in python is executed as: lm = smf.ols(formula = 'Sales ~ am+constant', data = data).fit() lm.conf_int() lm.summary() And we get the output as below

SVR (Support Vector Regression)

In simple linear regression, try to minimize the error rate. But in SVR, we try to fit the error within a certain threshold.

Our best fit line is the one where the hyperplane has the maximum number of points. We are trying to do here is trying to decide a decision boundary at ‘e’ distance from the original hyperplane such that data points closest to the hyperplane or the support vectors are within that boundary line.

Non-Linear Regression

In some cases, the true relationship between the outcome and a predictor variable might not be linear. There are different solutions extending the linear regression model for capturing these nonlinear effects, some of these are covered below.

Polynomial Regression

The equation of polynomial becomes something like this.

The degree of order which to use is a Hyperparameter, and we need to choose it wisely. But using a high degree of polynomial tries to overfit the data and for smaller values of degree, the model tries to underfit so we need to find the optimum value of a degree. Polynomial Regression on datasets with high variability chances to result in over-fitting.

Regression Splines

📖Explanation

In order to overcome the disadvantages of polynomial regression, we can use an improved regression technique which, instead of building one model for the entire dataset, divides the dataset into multiple bins and fits each bin with a separate model. Such a technique is known as Regression spline.

In polynomial regression, we generated new features by using various polynomial functions on the existing features which imposed a global structure on the dataset. To overcome this, we can divide the distribution of the data into separate portions and fit linear or low degree polynomial functions on each of these portions. The points where the division occurs are called Knots. Functions which we can use for modelling each piece/bin are known as Piecewise functions. There are various piecewise functions that we can use to fit these individual bins.

Generalized additive models

It does the same thing as above but just removes the need to specifying the knots. It fits spline models with automated selection of knots.

Questions

[UPSTART] Regression Coefficient

Answer

Linear Regression in Time Series

Do you think Linear Regression should be used in Time series analysis?

Answer

Linear Regression as per me can be used in Time Series but might not always give good results. Few reasons which come up are:

  • Linear Regression is good for intrapolation but not for extrapolation so the results can vary wildly

  • When Linear Regression is used but observations are correlated (as in time series data) you will have a biased estimate of the variance

  • Moreover, time-series data have a pattern, such as during peak hours, festive seasons, etc., which would most likely be treated as outliers in the linear regression analysis

[AIRBNB] Booking Regression

Let's say we want to build a model to predict booking prices.

  1. Explain the difference between a linear regression versus a random forest regression.

  2. Which one would likely perform better?

Answer

Linear Regression is used to predict continuous outputs where there is a linear relationship between the features of the dataset and the output variable. It is used for regression problems where you are trying to predict something with infinite possible answers such as the price of a house.

In the case of regression, decision trees in random forest learn by splitting the training examples in a way such that the sum of squared residuals is minimized. To classify a new object based on attributes, each tree gives a classification and we say the tree “votes” for that class. The forest chooses the classification having the most votes (over all the trees in the forest) and in case of regression, it takes the average of outputs by different trees. It is useful when there are complex relationships between the features and the output variables. They also work well compared to other Algorithms when there are missing features, when there is a mix of categorical and numerical features and when there is a big difference in the scale of features.

It is difficult to tell which will perform better, it completely depends on the problem statement and the available data. Other than the points mentioned above some of the Key advantages of linear models over tree-based ones are:

  • they can extrapolate (e.g., if labels are between 1-5 in train set, tree-based model will never predict 10, but linear will)

  • could be used for anomaly detection because of extrapolation

  • interpretability (yes, tree-based models have feature importance, but it's only a proxy, weights in linear model are better)

  • need less data to get good results

  • Random Forest is able to discover more complex relation at the cost of time

The first point becomes clearly important in this case as we would need booking price values which might not necessarily be in the training data range.

[GOOGLE] Adding Noise

What is the new objective function? How do you compute it?

Answer (Source)

[UBER] L1 vs L2

What is L1 and L2 regularization? What are the differences between the two?

Answer (Source)

The loss function for the two are:

[TESLA] Choice of Cost Function

You're working with several sensors that are designed to predict a particular energy consumption metric on a vehicle. Using the outputs of the sensors, you build a linear regression model to make the prediction. There are many sensors, and several of the sensors are prone to complete failure.

What are some cost functions you might consider, and which would you decide to minimize in this scenario?

Answer (Source)

[AIRBNB] Prove that maximizing the likelihood is equivalent to minimizing the sum of squared residuals

Suppose you are running a linear regression and model the error terms as being normally distributed. Show that in this setup, maximizing the likelihood of the data is equivalent to minimizing the sum of squared residuals.

Answer (Source)

A mathematical derivation like this requires us to:

  • Define correct Mathematical symbols and their relationships through equations

  • Recall and use the definitions of the terms like likelihood and normally distributed

  • Perform Mathematical manipulation to derive the required result

Problem Setup:

Next, we are give a set of training data points, consisting of

Likelihood:

Take a look at the problem statement again. We are assuming that the error terms are normally distributed. There is an implicit assumption that all the error terms are independent of each other. (Make sure you make this assumption explicit to your interviewer).

Since we are assuming that the error terms are also independent, their joint probability distribution, is given by the product of their likelihood.

Maximum Likelihood Estimator:

The maximum likelihood estimator seeks to maximize the likelihood function defined above. For the maximization,

  • We can also take the log of the likelihood function, converting the product into sum

The log likelihood function of the errors is given by

But this is just the negative of the sum of squared errors!

Thus, if you want to maximize the likelihood (or log likelihood) of the errors, you better minimize the sum of squared errors of the estimates.

Last updated