Simple Linear Regression
MediumMachine LearningStatisticsArray
Description
Given arrays x and y of equal length, fit a simple linear regression y = slope * x + intercept using ordinary least squares. Return [slope, intercept], each rounded to 4 decimal places. The x values are not all equal.
Examples
Input:
[1,2,3,4], [2,4,6,8]Output:
[2,0]Explanation:
Ordinary least squares divides the covariance of x and y by the variance of x to get the slope 2, then chooses the intercept 0 so the line passes through the means of x and y.
Input:
[1,2,3], [1,3,5]Output:
[2,-1]Explanation:
Ordinary least squares divides the covariance of x and y by the variance of x to get the slope 2, then chooses the intercept -1 so the line passes through the means of x and y.
Input:
[0,1,2,3], [1,2,3,4]Output:
[1,1]Explanation:
Ordinary least squares divides the covariance of x and y by the variance of x to get the slope 1, then chooses the intercept 1 so the line passes through the means of x and y.
Constraints
- •
2 ≤ length ≤ 10⁴ - •
x values are not all identical