Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement Linear Regression Function

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Implement Linear Regression Function. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Purdue University student-support analytics needs a small baseline model that estimates an outcome from one numeric measurement. Implement univariate linear regression using the ordinary least-squares solution, without using machine-learning libraries.

Given paired feature values x and target values y, compute the line y = slope * x + intercept that minimizes the sum of squared prediction errors.

Formal Specification

Implement fit_linear_regression(x, y), where x and y are nonempty lists of numbers with equal length. Return a two-element list [slope, intercept] containing floating-point values. The input guarantees that x contains at least two distinct values, so the slope is defined.

Use these formulas, where x_mean and y_mean are the respective averages:

  • slope = sum((x[i] - x_mean) * (y[i] - y_mean)) / sum((x[i] - x_mean)^2)
  • intercept = y_mean - slope * x_mean

Constraints

  • 2 <= len(x) == len(y) <= 10^5
  • x and y contain integers or floating-point values
  • At least two values in x are different
  • The feature variance denominator is nonzero
  • Do not use external numerical or machine-learning libraries

Function Signature

def fit_linear_regression(x, y):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output