← 中文资源

简体中文版本

statistics 用 linear_regression 拟合直线

一次调用拿到斜率与截距即可外推预测,correlation 给出线性强度;纯标准库完成拟合与检验,不引入任何外部依赖,xs 与 ys 等长即可。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

slope=0.950 intercept=2.300
predict at 35 -> 35.5
correlation=0.9954
r squared=0.9909

实现说明

各个操作都建立在顶层绑定之上:spend、signups。

使用要点

  • 演示输出是带标签的(slope=、predict at 35 ->、correlation=),每个操作都会留下自己的一行标注。

常见问题

除了语言工具链还要下载什么吗?

除了这个语言的工具链,什么都不用再下载。 全部导入都来自标准库:statistics。 跨调用保留的状态放在这些顶层绑定里:spend、signups。

代码示例

from statistics import linear_regression, correlation

# Weekly ad spend (x) versus signups (y): a textbook linear relationship.
spend = [10, 20, 30, 40, 50]
signups = [12, 21, 32, 38, 51]

slope, intercept = linear_regression(spend, signups)
print(f"slope={slope:.3f} intercept={intercept:.3f}")
print(f"predict at 35 -> {intercept + slope * 35:.1f}")

# correlation quantifies how linear the relationship is, from -1 to 1.
r = correlation(spend, signups)
print(f"correlation={r:.4f}")
print(f"r squared={r ** 2:.4f}")

# xs and ys must have equal length; xs need not be sorted.