Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Linear Regression From Scratch

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

Your question is Linear Regression From Scratch. 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

Write a function that fits a univariate linear regression model from scratch. Given training data x and y, return the slope and intercept of the best-fit line y = m*x + b using least squares.

Your function must not use machine learning libraries. You may use only basic Python and math if needed.

Formal Specification

Implement: fit_linear_regression(x, y)

  • x: list of numeric feature values
  • y: list of numeric target values
  • Return: a tuple (m, b) where m is the slope and b is the intercept

Use the closed-form least squares solution. Assume x and y have the same length and contain at least 2 points.

Constraints

  • 2 <= len(x) <= 10^5
  • len(x) == len(y)
  • -10^6 <= x[i], y[i] <= 10^6
  • At least one valid least-squares solution exists
  • Return floating-point values for slope and intercept

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