跳到内容
🛠️ToolsShed

线性回归计算器

从数据点计算线性回归:斜率、截距、R²和预测。

#XY
1
2
3
4
5

关于此工具

线性回归是一种基本的统计方法,通过在一组数据点上拟合一条直线来模拟两个变量之间的关系。此计算器帮助您找到最佳拟合线,计算斜率和截距,并通过 R² 值衡量数据与线性模式的拟合程度。无论您是在分析销售数据趋势、比较实验结果,还是在科学研究中探索相关性,理解线性关系对于数据驱动决策都是至关重要的。

要使用此工具,只需输入您的 X 和 Y 值数据点对,然后点击计算按钮。您将立即获得斜率(变化率)、截距(直线与 Y 轴的交点)、R² 系数(拟合质量度量,范围从 0 到 1,其中 1 表示完美拟合)和预测方程。该工具还允许您输入一个新的 X 值,以基于拟合的模型预测相应的 Y 值。

此计算器非常适合学习统计学的学生、验证假设的研究人员和识别业务指标趋势的专业人士。请注意,线性回归假设您的数据关系大致是线性的;如果您的数据显示曲线模式或分散度较大,该模型可能不可靠。对于更复杂的关系,请考虑使用多项式或其他非线性回归方法。

常见问题

代码实现

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.