At Lyft, a small analytics tool needs a basic linear regression function without using external ML libraries. Given paired numeric observations, compute the best-fit line y = mx + b using ordinary least squares.
Write a function that takes two arrays, x_values and y_values, and returns the slope and intercept of the regression line.
x_values: list of numbers of length ny_values: list of numbers of length n[slope, intercept]x_values are identical, return [].Use the formulas:
slope = sum((xi - mean_x) * (yi - mean_y)) / sum((xi - mean_x)^2)intercept = mean_y - slope * mean_xExample 1
x_values = [1, 2, 3, 4], y_values = [2, 4, 6, 8][2.0, 0.0]y = 2x.Example 2
x_values = [1, 2, 3], y_values = [2, 2, 2][0.0, 2.0]2 <= n <= 10^5x_values.length == y_values.length for valid input-10^6 <= x_values[i], y_values[i] <= 10^6x_values = [1, 2, 3, 4], y_values = [2, 4, 6, 8]Output[2.0, 0.0]WhyEach increase of 1 in `x` increases `y` by 2, so the fitted line is exactly `y = 2x`.x_values = [1, 2, 3], y_values = [2, 2, 2]Output[0.0, 2.0]WhySince all `y` values are equal, the best-fit line has slope 0 and intercept 2.x_values = [5, 5, 5], y_values = [1, 2, 3]Output[]WhyAll `x` values are identical, so the slope denominator is zero and the regression line is undefined.2 <= n <= 10^5x_values.length == y_values.length for valid input-10^6 <= x_values[i], y_values[i] <= 10^6Return [] for invalid input or when all x_values are identicalDo not use external regression or machine learning librariesdef linear_regression(x_values, y_values):