문제
Linear regression finds the line y = slope × x + intercept that best fits the data, meaning the sum of squared errors is as small as possible. For one input variable there is an exact formula:
- slope = Σ(x - x̄)(y - ȳ) / Σ(x - x̄)²
- intercept = ȳ - slope × x̄
where x̄ and ȳ are the means of xs and ys. If all xs are equal, return slope 0 and intercept ȳ.
Implement linear_regression(xs, ys).
Input
xs, ys: The x and y values of the data points (same length).
Output
Return [slope, intercept].
제약 조건
1 ≤ number of points ≤ 10,000
-10,000 ≤ each value ≤ 10,000
예시
입력:
xs = [1.0, 2.0, 3.0, 4.0]
ys = [3.0, 5.0, 7.0, 9.0]
예상 출력:
expected = [2.0, 1.0]
입력:
std::vector<double> xs = {1.0, 2.0, 3.0, 4.0};
std::vector<double> ys = {3.0, 5.0, 7.0, 9.0};
예상 출력:
std::vector<double> expected = {2.0, 1.0};
입력:
double[] xs = new double[] {1.0, 2.0, 3.0, 4.0};
double[] ys = new double[] {3.0, 5.0, 7.0, 9.0};
예상 출력:
double[] expected = new double[] {2.0, 1.0};
설명
The points lie exactly on y = 2x + 1. x̄ = 2.5, ȳ = 6, Σ(x - x̄)(y - ȳ) = 10 and Σ(x - x̄)² = 5, so slope = 2 and intercept = 6 - 2 × 2.5 = 1.
입력:
xs = [0.0, 1.0, 2.0]
ys = [1.0, 3.0, 2.0]
예상 출력:
expected = [0.5, 1.5]
입력:
std::vector<double> xs = {0.0, 1.0, 2.0};
std::vector<double> ys = {1.0, 3.0, 2.0};
예상 출력:
std::vector<double> expected = {0.5, 1.5};
입력:
double[] xs = new double[] {0.0, 1.0, 2.0};
double[] ys = new double[] {1.0, 3.0, 2.0};
예상 출력:
double[] expected = new double[] {0.5, 1.5};
설명
x̄ = 1 and ȳ = 2. Σ(x - x̄)(y - ȳ) = (-1)(-1) + 0 + (1)(0) = 1 and Σ(x - x̄)² = 2, so slope = 0.5 and intercept = 2 - 0.5 × 1 = 1.5.
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.