線形回帰計算機
データポイントから線形回帰を計算:傾き、切片、R²、予測値。
| # | X | Y | |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
よくある質問
コード実装
def linear_regression(x: list, y: list) -> dict:
n = len(x)
if n < 2:
raise ValueError("Need at least 2 data points")
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
sum_x2 = sum(xi ** 2 for xi in x)
mean_x = sum_x / n
mean_y = sum_y / n
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
intercept = mean_y - slope * mean_x
# R-squared
ss_res = sum((yi - (slope * xi + intercept)) ** 2 for xi, yi in zip(x, y))
ss_tot = sum((yi - mean_y) ** 2 for yi in y)
r2 = 1 - ss_res / ss_tot if ss_tot != 0 else 1.0
return {"slope": slope, "intercept": intercept, "r_squared": r2,
"pearson_r": r2 ** 0.5 if r2 >= 0 else 0}
x = [1, 2, 3, 4, 5]
y = [2.1, 3.9, 6.2, 7.8, 10.1]
result = linear_regression(x, y)
print(f"y = {result['slope']:.4f}x + {result['intercept']:.4f}")
print(f"R² = {result['r_squared']:.4f}")
# Predict
x_new = 6
y_pred = result['slope'] * x_new + result['intercept']
print(f"Prediction at x=6: {y_pred:.2f}")Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.