用 Theil–Sen 估计年化衰减:所有点对斜率的中位数,能挡住什么、挡不住什么
本文目录
手上有一串按月汇总的数,想回答一个简单的问题:**它每年变化多少?**比如电动车每个月一个“满电续航折算值”(以最初几个月为 100%),想说“电池每年衰减约 2 个百分点”;或者服务每月的 P95 延迟,想说“每年慢了多少毫秒”。
最顺手的做法是拿普通最小二乘(OLS)拟合一条直线,取斜率。问题是这类数据里总有几个月不正常:那个月只在寒冷天气充满电,那个月估算方式出了岔子,那个月做过一次压测。OLS 对每个点一视同仁地平方误差,一两个离谱的点就能把斜率拽歪。
最近看到一段代码的做法是:先给月度值做 3 个月滚动中位数,再算所有两两点对斜率的中位数,换算成每年的变化;点数少于 6 个、跨度不足 180 天就不给结论。后一步就是 Theil–Sen 估计(也叫 Sen 斜率)。这篇只讲这一件事:Theil–Sen 稳在哪里、置信区间怎么算、季节起伏和“先平滑”会带来什么,以及它挡不住的情况。全部结论都用一个可独立运行的 Go 小程序实测,并在一组样例上和 SciPy 的实现对照。
测试环境:
- Go 1.27.4(当前最新版),示例的
go.mod写的是go 1.24,用 Go 1.24.0 也跑过测试; - SciPy 1.18.1、NumPy 2.5.3(当前最新版),只用来交叉核对;
- 4 核 Intel Xeon 2.30GHz,Linux。
Theil–Sen 是什么
给定点 (x₁, y₁) … (xₙ, yₙ),对每一对 i < j 且 xᵢ ≠ xⱼ 的点算斜率 (yⱼ − yᵢ) / (xⱼ − xᵢ),一共最多 n(n−1)/2 个,取它们的中位数作为直线的斜率。截距有几种取法,常见的是 median(y) − 斜率 × median(x)。
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
if dx := x[j] - x[i]; dx != 0 {
slopes = append(slopes, (y[j]-y[i])/dx)
}
}
}
slope := median(slopes)
它由 Henri Theil(1950)提出、Pranab K. Sen(1968)推广到 x 可以重复的情况,并给出了基于 Kendall τ 的置信区间(维基百科条目列出了原始文献)。几个性质决定了它适合干这件事:
- 崩溃点约 29.3%:可以容忍最多约 29.3% 的点被任意篡改,估计值仍然有界(理论值为 1 − 1/√2,见 Rousseeuw & Leroy 2003,维基条目有引用)。OLS 的崩溃点是 0:一个点就能把斜率拉到任意值。
- 只依赖顺序:取的是中位数,单个斜率多大都无所谓,只要它落在中位数的哪一侧不变。
- x 不必等距:直接用真实时间差算斜率,漏掉的月份不用插值。
- 代价:要算 O(n²) 个斜率。月度数据 n 也就几十到一百多,这不是问题;后面会测到点数上万时的耗时。
和它一起比较的还有 Siegel 的重复中位数(1982):先对每个点取“它和其余各点斜率的中位数”,再对这 n 个中位数取中位数。崩溃点是 50%,代价是精度更低,下面会看到。
实现:和 SciPy 对照
完整代码在文末。TheilSen 做了四件容易出错的事:
- x 相同的点对直接跳过。同一个月有两条记录时,它们之间没有斜率,不能除以零,也不能当成 0 或无穷大塞进去。
- 偶数个斜率时取中间两个的平均。
- 置信区间按 Sen (1968):Kendall S 统计量的方差 σ² = [n(n−1)(2n+5) − Σt(t−1)(2t+5)] / 18,求和项对 x 和 y 里的每组并列值各算一次(t 是这组并列的个数)。记 N 为点对数、z 为标准正态的 1 − α/2 分位数,M1 = round((N − zσ)/2),M2 = round((N + zσ)/2),区间就是排好序的斜率里第 M1 个到第 M2 + 1 个。
- 缺失值和无效参数直接拒绝。x、y 里有 NaN 或 ±Inf 时返回
ErrNonFinite,置信水平不是 (0, 1) 之间的有限数时返回ErrBadConf。月度数据里缺一个月很常见,但 NaN 和任何数比较都为假:混进排序和并列计数,轻则结果错,重则循环停不下来(第一版的并列计数就是这样,遇到 NaN 会原地打转,测试里加了回归用例)。缺失的月份由调用方把 x 和 y 一起删掉再算,Theil–Sen 本来就不要求等距。
第 3 条里的舍入方式、并列修正、下标边界都会影响结果。为了确认没有写错,cmd/dump 造了一组 40 个点的数据,x 每个值出现两次,y 也有一处并列,还混了几个异常点;crosscheck.py 用 SciPy 1.18.1 的 scipy.stats.theilslopes 和 siegelslopes 复算:
scipy 1.18.1
theil slope scipy=-0.148183914737 go=-0.148183914737 diff=0.0e+00
theil intercept scipy=99.756237380401 go=99.756237380401 diff=0.0e+00
theil low scipy=-0.181861457524 go=-0.181861457524 diff=0.0e+00
theil high scipy=-0.103198404561 go=-0.103198404561 diff=0.0e+00
siegel slope scipy=-0.156063035721 go=-0.156063035721 diff=0.0e+00
siegel intercept scipy=99.873503223004 go=99.873503223004 diff=0.0e+00
这组样例的六个值完全相等,crosscheck.py 断言的就是差为 0(Go 的 JSON 编码输出能精确还原的最短十进制,Python 读回来是同一个 double)。这只说明这一组输入两边一致,不能推广成任意输入都逐位相同;TestMatchesSciPy 里另一组 12 个点的数据是按 1e-9 的容差核对的。对齐 SciPy 时踩到两个细节:SciPy 的 round 是 NumPy 的就近取偶,Go 里要用 math.RoundToEven 而不是 math.Round;SciPy 里 theilslopes 的 alpha 参数表示置信水平(默认 0.95),不是显著性水平。另外 SciPy 默认的截距是 method="separate",即 median(y) − 斜率 × median(x),和上面的做法一致。
实验场景
下面的实验都用同一个模型:24 个月(或另行说明)的月度值,真实趋势是每年下降 2 个百分点,叠加标准差 0.6 个百分点的正态噪声。x 以年为单位,所以斜率的单位直接是“百分点/年”。随机数用固定种子,每组重复 4000 次。
A. 异常月份:位置比数量更要命
让 24 个月里的 m 个月比正常低 8 个百分点,分两种摆法:随机分布在整段时间里,或者集中在最近的 m 个月(比如最近的估算方式出了问题、最近几个月都是冬天)。表里是斜率误差(绝对值)的中位数:
位置 m 占比 OLS Theil–Sen 重复中位数
随机 0 0% 0.14 0.15 0.16
随机 2 8% 0.58 0.18 0.19
随机 4 17% 0.77 0.21 0.22
随机 6 25% 0.86 0.24 0.27
随机 8 33% 0.97 0.30 0.35
随机 12 50% 0.99 0.32 0.54
最近 0 0% 0.14 0.15 0.17
最近 2 8% 1.84 0.33 0.25
最近 4 17% 3.34 0.86 0.50
最近 6 25% 4.51 2.04 1.02
最近 7 29% 4.97 3.27 1.45
最近 8 33% 5.34 4.35 2.16
最近 10 42% 5.84 5.02 4.76
最近 12 50% 6.01 5.20 5.74
几点观察:
- 两个异常月份就够 OLS 受的。集中在末尾时误差 1.84 个百分点/年,和真实值 2 差不多一样大,结论从“每年掉 2 个点”变成“每年掉 4 个点”。
- 随机散布的异常点,Theil–Sen 一直很稳,到 50% 误差也只有 0.32。散布的低点在早期和晚期各占一些,点对斜率有的被拉高、有的被拉低,中位数基本不动。
- 集中在一端才是最坏情况。末尾 6 个月(25%)异常时 Theil–Sen 的误差已到 2.04,7 个月(29%)时 3.27,和理论崩溃点 29.3% 吻合:超过这个比例,被污染的点对已经多到能决定中位数。
- 重复中位数在 25%~33% 这一段明显更好,崩溃点 50% 的优势在这里体现出来;到了 42% 以上,有限样本加上噪声,它也撑不住了。
工程上的意思是:如果数据里会出现“最近一段整体不对劲”(换了口径、换了传感器、某个季节),Theil–Sen 帮不了太多,要靠数据层面先识别出来。
B. 季节起伏:平滑的起伏躲不过,短促的下陷挡得住
续航折算值冬天偏低、夏天偏高,这是季节性,不是异常。这里不加噪声,只看偏差:每个窗口长度下,把起点从一月到十二月各取一次,看估出的斜率范围。季节形状取三种:
- 平滑:整年按余弦起伏,一月最低、七月最高,振幅 1.5 个百分点;
- 短促:只有十二月到二月低 3 个百分点,其余月份正常;
- 平滑+半年:在“平滑”上再叠一个半年周期的小起伏,偏差为 −1.5·cos(2π·m/12) − 0.5·sin(2π·m/6),m 是月份(0 = 一月),起伏不再左右对称。
“季节 Sen”是 Hirsch、Slack 和 Smith(1982)提出的变体:只在同一个月份的点之间取斜率,比如今年三月和去年三月,再取中位数。
形状 窗口(月) OLS Theil–Sen 季节 Sen
平滑 12 -4.82 ~ 0.82 -5.00 ~ 1.00 不可用
平滑 18 -2.26 ~ -1.74 -2.00 ~ -2.00 -2.00 ~ -2.00
平滑 24 -2.70 ~ -1.30 -2.72 ~ -1.28 -2.00 ~ -2.00
平滑 36 -2.31 ~ -1.69 -2.23 ~ -1.77 -2.00 ~ -2.00
短促 12 -5.40 ~ 1.40 -2.00 ~ -2.00 不可用
短促 18 -2.67 ~ -1.33 -2.00 ~ -2.00 -2.00 ~ -2.00
短促 24 -2.85 ~ -1.15 -2.00 ~ -2.00 -2.00 ~ -2.00
短促 36 -2.38 ~ -1.62 -2.00 ~ -2.00 -2.00 ~ -2.00
平滑+半年 12 -5.25 ~ 0.38 -5.96 ~ 0.31 不可用
平滑+半年 18 -2.26 ~ -1.55 -2.60 ~ -1.75 -2.00 ~ -2.00
平滑+半年 24 -2.81 ~ -1.41 -3.17 ~ -1.49 -2.00 ~ -2.00
平滑+半年 36 -2.36 ~ -1.74 -2.51 ~ -1.80 -2.00 ~ -2.00
- 12 个月的窗口,OLS 和 Theil–Sen 在平滑季节下都完全不可信:同样的数据,从一月开始算是每年 −4.8,从七月开始算是每年 +0.8,季节振幅直接变成了斜率。所以“至少 6 个点、跨度 180 天”这种门槛只能防止点太少,防不住季节。
- “凑满整年”也不够。24 个月正好两个整周期,OLS 和 Theil–Sen 的范围反而比 18 个月更宽(约 ±0.7)。原因是余弦在整周期上虽然均值为 0,但它和时间的协方差不为 0:窗口里前半年高、后半年低,就像多了一段斜坡。
- 短促的冬季下陷,Theil–Sen 全部挡住了,12 个月窗口也是精确的 −2。每年只有 3 个月偏低,占 25%,并且散布在窗口里,对它来说就是“少量异常点”。平滑起伏不同,每个点都偏离直线,不存在“多数正常点”可依靠。
- 季节 Sen 三种形状都精确,代价是至少要有某个月份出现两次,严格说要两年以上的数据才有足够的同月点对。
表里“平滑 18 个月 Theil–Sen 恰好全是 −2.00”是纯余弦形状的巧合,不要指望它:看“平滑+半年”那几行,只多了一个振幅 0.5 的半年周期,同样 18 个月,Theil–Sen 的范围就成了 −2.60 ~ −1.75。
C. 先平滑再算区间:区间会说谎
开头那段代码先做 3 个月滚动中位数再算斜率。对斜率本身,这一步影响不大;但如果还要给出置信区间,就有问题了。Sen 的区间建立在“各点误差相互独立”的前提上,滚动窗口让相邻的值共享了原始数据,这个前提不成立。实测 95% 区间实际覆盖真值的比例:
数据 覆盖率 平均宽度 斜率误差中位数
独立噪声 95.8% 0.94 0.15
独立噪声 + 3 月滚动中位数 77.0% 0.61 0.17
AR(1) 噪声 φ=0.6 71.6% 0.85 0.27
- 原始数据上,区间名副其实(95.8%)。
- 平滑之后,区间变窄了三分之一,覆盖率却掉到 77%:看起来更确定,其实更常错。斜率误差的中位数还从 0.15 涨到了 0.17,平滑没有让斜率更准。
- 数据本身就有自相关(这里用一阶自回归 AR(1)、系数 0.6 模拟“这个月偏低,下个月大概率也偏低”)时,即使不平滑,覆盖率也只有 71.6%。
所以:算斜率的区间要用未平滑的原始月度值;平滑后的曲线可以拿去画图。如果数据有明显的自相关(月度运营数据很常见),Sen 区间需要按自相关做修正,或者改用分块 bootstrap 这类不依赖独立假设的方法,否则别把它当 95% 区间展示给人看。
D. 稳健的代价:正常数据上损失多少精度
没有异常点、噪声是正态分布时,OLS 是最优的线性无偏估计。稳健估计要付出多少?4000 次模拟里斜率估计的标准差:
月数 OLS Theil–Sen 重复中位数 OLS方差/TS方差 OLS方差/RM方差
12 0.608 0.647 0.731 0.88 0.69
24 0.208 0.218 0.246 0.91 0.72
60 0.052 0.054 0.061 0.93 0.73
Theil–Sen 的方差只比 OLS 大约 10%(相对效率 0.88~0.93),换来的是 A 节里那样的抗干扰能力,很划算。重复中位数的方差要大约 40%(效率约 0.7)。维基条目也提到 Theil–Sen 相对最小二乘有较高的渐近效率,正态数据下也能和最小二乘竞争。
E. 点多了以后
Go 1.27.4,单次计算,x 随机分布:
点数 点对数 Theil–Sen 重复中位数 斜率切片大小
120 7140 452µs 1.185ms 0.1 MB
1000 499500 46.531ms 93.825ms 4.0 MB
3000 4498500 458.511ms 962.919ms 36.0 MB
10000 49995000 6.01813s 12.340732s 400.0 MB
十年的月度数据才 120 个点,不到 1 毫秒,直接暴力算即可。如果拿原始事件(每次充电、每个请求)去算,点数上万时耗时和内存都会成问题。两条路:先按天或按月聚合成稳健的汇总值(比如中位数)再算,这通常也是更合理的统计口径;或者用专门的算法,已有确定性和随机化的 O(n log n) 精确算法(Cole 等 1989、Matoušek 1991 等,维基条目有汇总),也可以随机抽取一部分点对近似。
F. 台阶:它挡不住的另一种情况
假设某次软件更新后估算方式变了,从第 k 个月起每个月都高 3 个百分点。36 个月,无噪声:
k OLS Theil–Sen 重复中位数
6 -1.17 -2.00 -2.00
18 -0.50 -0.87 -0.64
30 -1.17 -2.00 -2.00
台阶靠近两端时,台阶一侧的点少于 29.3%,Theil–Sen 当它们是异常点,结果精确。台阶在正中间时,跨过台阶的点对占了一半以上,所有方法都错得很离谱:真实趋势每年掉 2 个点,Theil–Sen 说只掉 0.87。这不是哪个估计方法能解决的,需要识别出变更点,分段计算,或者在台阶处做数据校正。
取舍
把上面的结果落到一个年化变化的计算里,我会这么做:
- 先聚合再估计。每月一个稳健的汇总值(中位数、加权分位数都行),让 n 保持在几十到一百多,暴力 O(n²) 毫无压力。
- 默认用 Theil–Sen 而不是 OLS。正常数据上只多约 10% 的方差,偶发异常月份几乎不影响结果。担心末尾整段异常时,可以同时算重复中位数做对照,两者差距大就说明数据有问题。
- 数据满两年就用季节 Sen。不满两年、又有明显季节性时,别给出年化数字,或者明确标注“受季节影响”。“至少 N 个点”的门槛防不住季节。
- 区间用原始值算,并检查自相关。平滑后的值只用来画图。
- 单独检测台阶。口径变更、硬件更换这类事件要在数据层记下来,分段处理。
完整代码
一个独立的 Go 模块,只用标准库;crosscheck.py 需要 SciPy。目录结构:
robustslope/
├── go.mod
├── trend/trend.go
├── trend/trend_test.go
├── cmd/experiments/main.go
├── cmd/dump/main.go
└── crosscheck.py
go.mod:
module example.com/robustslope
go 1.24
trend/trend.go:
// Package trend 用几种方法估计 y 随 x 变化的直线斜率。
package trend
import (
"errors"
"math"
"slices"
)
// 输入策略:x、y 里只要有 NaN 或 ±Inf,所有函数都直接返回 ErrNonFinite,不做任何计算。
// 缺失的月份由调用方先成对删掉(x 和 y 一起删);这些方法本来就不要求 x 等距,
// 删掉之后直接用剩下的点算即可。之所以拒绝而不是悄悄跳过,是因为 NaN 和任何数比较都为假,
// 混进排序、并列计数、中位数里会产生错误结果,甚至让循环停不下来。
var (
// ErrTooFewPoints 表示 x 互不相同的点不足两个,斜率无从谈起。
ErrTooFewPoints = errors.New("trend: need at least two points with distinct x")
// ErrNonFinite 表示 x 或 y 含 NaN 或 ±Inf。
ErrNonFinite = errors.New("trend: x and y must be finite (drop missing points first)")
// ErrBadConf 表示置信水平不是 (0, 1) 之间的有限数。
ErrBadConf = errors.New("trend: confidence level must be a finite number in (0, 1)")
)
// Fit 是一条拟合直线 y = Intercept + Slope*x。
// Lo、Hi 是 Theil–Sen 斜率的置信区间,其他方法不填(为 NaN)。
type Fit struct {
Slope, Intercept float64
Lo, Hi float64
Pairs int // 参与计算的点对数(x 相同的点对不算)
}
// validate 检查输入。长度不同是调用方的编程错误,直接 panic;非有限值返回 ErrNonFinite。
func validate(x, y []float64) error {
if len(x) != len(y) {
panic("trend: x and y have different lengths")
}
for i := range x {
if math.IsNaN(x[i]) || math.IsInf(x[i], 0) || math.IsNaN(y[i]) || math.IsInf(y[i], 0) {
return ErrNonFinite
}
}
return nil
}
// OLS 是普通最小二乘。
func OLS(x, y []float64) (Fit, error) {
if err := validate(x, y); err != nil {
return Fit{}, err
}
n := float64(len(x))
var mx, my float64
for i := range x {
mx += x[i]
my += y[i]
}
mx /= n
my /= n
var sxx, sxy float64
for i := range x {
sxx += (x[i] - mx) * (x[i] - mx)
sxy += (x[i] - mx) * (y[i] - my)
}
if sxx == 0 {
return Fit{}, ErrTooFewPoints
}
b := sxy / sxx
return Fit{Slope: b, Intercept: my - b*mx, Lo: math.NaN(), Hi: math.NaN()}, nil
}
// pairSlopes 返回所有 i<j 且 x 不同的点对斜率。
func pairSlopes(x, y []float64) []float64 {
n := len(x)
s := make([]float64, 0, n*(n-1)/2)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
dx := x[j] - x[i]
if dx == 0 {
continue
}
s = append(s, (y[j]-y[i])/dx)
}
}
return s
}
// medianInPlace 会打乱 v 的顺序;偶数个时取中间两个的平均。
func medianInPlace(v []float64) float64 {
slices.Sort(v)
return sortedMedian(v)
}
func sortedMedian(v []float64) float64 {
m := len(v) / 2
if len(v)%2 == 1 {
return v[m]
}
return (v[m-1] + v[m]) / 2
}
func median(v []float64) float64 {
return medianInPlace(slices.Clone(v))
}
// TheilSen 计算 Theil–Sen 斜率:所有点对斜率的中位数。
// 截距取 median(y) - slope*median(x),与 SciPy 的默认做法(method="separate")一致。
// conf 是置信水平(例如 0.95),区间按 Sen (1968) 的方法、带并列修正计算。
func TheilSen(x, y []float64, conf float64) (Fit, error) {
if err := validate(x, y); err != nil {
return Fit{}, err
}
if math.IsNaN(conf) || conf <= 0 || conf >= 1 { // conf 为 ±Inf 时也落在这两个比较里
return Fit{}, ErrBadConf
}
s := pairSlopes(x, y)
if len(s) == 0 {
return Fit{}, ErrTooFewPoints
}
slices.Sort(s) // 置信区间也要用排好序的斜率
b := sortedMedian(s)
f := Fit{Slope: b, Intercept: median(y) - b*median(x), Pairs: len(s)}
f.Lo, f.Hi = senInterval(x, y, s, conf)
return f, nil
}
// senInterval 假设 sorted 已升序、没有 NaN,conf 已校验。
// Kendall S 统计量的方差 σ² = [n(n-1)(2n+5) - Σt(t-1)(2t+5)] / 18,
// t 是 x、y 中每组并列值的个数。记 N 为点对数,M1 = round((N-zσ)/2),
// M2 = round((N+zσ)/2),区间就是排好序的点对斜率里第 M1 个到第 M2+1 个(从 1 数)。
func senInterval(x, y, sorted []float64, conf float64) (lo, hi float64) {
alpha := 1 - conf
z := math.Sqrt2 * math.Erfinv(1-alpha) // 标准正态的 1-α/2 分位数
n := float64(len(y))
v := n*(n-1)*(2*n+5) - tieTerm(x) - tieTerm(y)
if v < 0 {
return math.NaN(), math.NaN()
}
sigma := math.Sqrt(v / 18)
N := float64(len(sorted))
// 下标从 0 开始;用就近取偶舍入,和 NumPy 的 round 对齐。
l := int(math.RoundToEven((N-z*sigma)/2)) - 1
u := int(math.RoundToEven((N + z*sigma) / 2))
l = max(l, 0)
u = min(u, len(sorted)-1)
return sorted[l], sorted[u]
}
func tieTerm(v []float64) float64 {
s := slices.Clone(v)
slices.Sort(s)
var sum float64
for i := 0; i < len(s); {
j := i + 1 // 至少前进一步:即使混进 NaN(s[i] == s[i] 为假)也不会原地打转
for j < len(s) && s[j] == s[i] {
j++
}
t := float64(j - i)
sum += t * (t - 1) * (2*t + 5)
i = j
}
return sum
}
// RepeatedMedian 是 Siegel 的重复中位数:先对每个点取它和其余各点斜率的中位数,
// 再对这些中位数取中位数。截距用同样的两层中位数。
func RepeatedMedian(x, y []float64) (Fit, error) {
if err := validate(x, y); err != nil {
return Fit{}, err
}
n := len(x)
perPoint := make([]float64, 0, n)
perPointIntercept := make([]float64, 0, n)
buf := make([]float64, 0, n)
ibuf := make([]float64, 0, n)
for i := 0; i < n; i++ {
buf, ibuf = buf[:0], ibuf[:0]
for j := 0; j < n; j++ {
dx := x[j] - x[i]
if dx == 0 {
continue
}
sl := (y[j] - y[i]) / dx
buf = append(buf, sl)
ibuf = append(ibuf, y[i]-sl*x[i])
}
if len(buf) == 0 {
continue
}
perPoint = append(perPoint, medianInPlace(buf))
perPointIntercept = append(perPointIntercept, medianInPlace(ibuf))
}
if len(perPoint) == 0 {
return Fit{}, ErrTooFewPoints
}
return Fit{
Slope: medianInPlace(perPoint),
Intercept: medianInPlace(perPointIntercept),
Lo: math.NaN(), Hi: math.NaN(),
}, nil
}
// SeasonalSen 是季节 Sen 斜率(Hirsch 等, 1982):只在同一季节(例如同一个月份)
// 的点之间取斜率,再取中位数。季节周期内的起伏因此互相抵消。
// 至少要有一个季节出现在两个不同的 x 上。
func SeasonalSen(x []float64, season []int, y []float64) (Fit, error) {
if err := validate(x, y); err != nil {
return Fit{}, err
}
if len(season) != len(x) {
panic("trend: season has a different length")
}
bySeason := map[int][]int{}
for i, s := range season {
bySeason[s] = append(bySeason[s], i)
}
var s []float64
for _, idx := range bySeason {
for a := 0; a < len(idx); a++ {
for b := a + 1; b < len(idx); b++ {
i, j := idx[a], idx[b]
dx := x[j] - x[i]
if dx == 0 {
continue
}
s = append(s, (y[j]-y[i])/dx)
}
}
}
if len(s) == 0 {
return Fit{}, ErrTooFewPoints
}
pairs := len(s)
b := medianInPlace(s)
return Fit{Slope: b, Intercept: median(y) - b*median(x), Lo: math.NaN(), Hi: math.NaN(), Pairs: pairs}, nil
}
trend/trend_test.go:
package trend
import (
"errors"
"math"
"testing"
"time"
)
func near(t *testing.T, name string, got, want float64) {
t.Helper()
// 先单独判 NaN:math.Abs(NaN-want) > 1e-9 为假,不拦一下 NaN 会被当成通过。
if math.IsNaN(got) || math.IsNaN(want) || math.Abs(got-want) > 1e-9 {
t.Errorf("%s = %.12f, want %.12f", name, got, want)
}
}
func TestExactLine(t *testing.T) {
x := []float64{0, 1, 2, 3, 4, 5}
y := []float64{10, 8, 6, 4, 2, 0}
for name, fit := range map[string]func(x, y []float64) (Fit, error){
"OLS": OLS, "RepeatedMedian": RepeatedMedian,
"TheilSen": func(x, y []float64) (Fit, error) { return TheilSen(x, y, 0.95) },
} {
f, err := fit(x, y)
if err != nil {
t.Fatal(name, err)
}
near(t, name+" slope", f.Slope, -2)
near(t, name+" intercept", f.Intercept, 10)
}
}
// 一个离谱的点就能把 OLS 拽歪,Theil–Sen 和重复中位数纹丝不动。
func TestSingleOutlier(t *testing.T) {
x := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y := make([]float64, len(x))
for i := range x {
y[i] = 100 - 0.5*x[i]
}
y[9] = 0
ols, _ := OLS(x, y)
ts, _ := TheilSen(x, y, 0.95)
rm, _ := RepeatedMedian(x, y)
if math.Abs(ols.Slope+0.5) < 1 {
t.Errorf("OLS slope %.3f should be pulled far away by the outlier", ols.Slope)
}
near(t, "TheilSen", ts.Slope, -0.5)
near(t, "RepeatedMedian", rm.Slope, -0.5)
}
// x 相同的点对没有斜率,必须跳过,不能除以零。
func TestTiedX(t *testing.T) {
x := []float64{0, 0, 1, 1, 2, 2}
y := []float64{0, 1, 2, 3, 4, 5}
f, err := TheilSen(x, y, 0.95)
if err != nil {
t.Fatal(err)
}
if f.Pairs != 12 { // 15 对里有 3 对 x 相同
t.Errorf("pairs = %d, want 12", f.Pairs)
}
// 排序后的 12 个斜率中间两个都是 2
near(t, "slope", f.Slope, 2)
if _, err := TheilSen([]float64{3, 3, 3}, []float64{1, 2, 3}, 0.95); !errors.Is(err, ErrTooFewPoints) {
t.Errorf("all-equal x: err = %v", err)
}
if _, err := RepeatedMedian([]float64{3, 3}, []float64{1, 2}); !errors.Is(err, ErrTooFewPoints) {
t.Errorf("RepeatedMedian all-equal x: err = %v", err)
}
if _, err := OLS([]float64{3, 3}, []float64{1, 2}); !errors.Is(err, ErrTooFewPoints) {
t.Errorf("OLS all-equal x: err = %v", err)
}
}
// 期望值由 SciPy 1.18.1 算出:
//
// stats.theilslopes(y, x, alpha=0.95)、stats.siegelslopes(y, x, method="separate")
func TestMatchesSciPy(t *testing.T) {
x := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
y := []float64{100.1, 99.7, 99.9, 99.2, 92.0, 99.0, 98.6, 98.9, 98.1, 97.9, 98.0, 90.5}
ts, err := TheilSen(x, y, 0.95)
if err != nil {
t.Fatal(err)
}
near(t, "theil slope", ts.Slope, -0.2354166666666651)
near(t, "theil intercept", ts.Intercept, 100.04479166666665)
near(t, "theil low", ts.Lo, -0.4)
near(t, "theil high", ts.Hi, -0.175)
rm, _ := RepeatedMedian(x, y)
near(t, "siegel slope", rm.Slope, -0.22916666666666458)
near(t, "siegel intercept", rm.Intercept, 100.05)
}
func TestSeasonalSenNeedsRepeatedSeason(t *testing.T) {
x := []float64{0, 1, 2}
if _, err := SeasonalSen(x, []int{0, 1, 2}, []float64{1, 2, 3}); !errors.Is(err, ErrTooFewPoints) {
t.Errorf("err = %v", err)
}
f, err := SeasonalSen([]float64{0, 0.5, 1, 1.5}, []int{0, 1, 0, 1}, []float64{10, 20, 9, 19})
if err != nil {
t.Fatal(err)
}
near(t, "seasonal slope", f.Slope, -1)
}
// withDeadline 让“卡死”变成一次快速失败,而不是等 go test 默认的 10 分钟超时。
func withDeadline(t *testing.T, f func()) {
t.Helper()
done := make(chan struct{})
go func() { defer close(done); f() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("did not return within 5s")
}
}
// 回归测试:缺失值(NaN)曾让 tieTerm 原地打转。现在所有入口都拒绝非有限值。
func TestRejectsNonFinite(t *testing.T) {
good := []float64{0, 1, 2, 3}
for _, bad := range []float64{math.NaN(), math.Inf(1), math.Inf(-1)} {
withX := []float64{0, 1, bad, 3}
withY := []float64{10, bad, 8, 7}
for name, fit := range map[string]func(x, y []float64) (Fit, error){
"OLS": OLS, "RepeatedMedian": RepeatedMedian,
"TheilSen": func(x, y []float64) (Fit, error) { return TheilSen(x, y, 0.95) },
"SeasonalSen": func(x, y []float64) (Fit, error) { return SeasonalSen(x, []int{0, 1, 0, 1}, y) },
} {
withDeadline(t, func() {
if _, err := fit(withX, good); !errors.Is(err, ErrNonFinite) {
t.Errorf("%s with %v in x: err = %v", name, bad, err)
}
if _, err := fit(good, withY); !errors.Is(err, ErrNonFinite) {
t.Errorf("%s with %v in y: err = %v", name, bad, err)
}
})
}
}
}
// tieTerm 自身也不能因为 NaN 停不下来(防御第二层)。
func TestTieTermTerminatesOnNaN(t *testing.T) {
withDeadline(t, func() {
// 两组并列 1,1 和 2,2,每组 t(t-1)(2t+5) = 2×1×9 = 18;NaN 自成一组,贡献 0
near(t, "tieTerm", tieTerm([]float64{2, math.NaN(), 1, 2, 1}), 36)
})
}
func TestBadConf(t *testing.T) {
x := []float64{0, 1, 2, 3}
y := []float64{3, 2, 1, 0}
for _, conf := range []float64{0, 1, -0.5, 1.5, 95, math.NaN(), math.Inf(1), math.Inf(-1)} {
if _, err := TheilSen(x, y, conf); !errors.Is(err, ErrBadConf) {
t.Errorf("conf %v: err = %v", conf, err)
}
}
if _, err := TheilSen(x, y, 0.9); err != nil {
t.Errorf("conf 0.9: err = %v", err)
}
}
cmd/experiments/main.go(A~F 六组实验;可以只跑其中几组,比如 go run ./cmd/experiments B C):
// experiments 用模拟数据比较几种斜率估计。所有随机数都用固定种子,结果可复现。
// 场景:每月一个“满电续航折算值”(基准为 100%),真实趋势每年下降 2 个百分点。
package main
import (
"fmt"
"math"
"math/rand/v2"
"os"
"runtime"
"slices"
"time"
"example.com/robustslope/trend"
)
const (
trueSlope = -2.0 // 每年下降 2 个百分点
noiseSD = 0.6
trials = 4000
)
type estimator struct {
name string
fit func(x, y []float64) (trend.Fit, error)
}
var estimators = []estimator{
{"OLS", trend.OLS},
{"Theil–Sen", func(x, y []float64) (trend.Fit, error) { return trend.TheilSen(x, y, 0.95) }},
{"重复中位数", trend.RepeatedMedian},
}
// months 返回 n 个按月等距的 x(单位:年)。
func months(n int) []float64 {
x := make([]float64, n)
for i := range x {
x[i] = float64(i) / 12
}
return x
}
func line(r *rand.Rand, x []float64) []float64 {
y := make([]float64, len(x))
for i, xi := range x {
y[i] = 100 + trueSlope*xi + r.NormFloat64()*noiseSD
}
return y
}
func must(f trend.Fit, err error) trend.Fit {
if err != nil {
panic(err)
}
return f
}
func medianAbsErr(errs []float64) float64 {
s := slices.Clone(errs)
slices.Sort(s)
return s[len(s)/2]
}
// A:一部分月份被拉低 8 个百分点(比如那几个月只在寒冷天气充满、或者估算本身出错)。
func outliers() {
fmt.Println("== A. 24 个月里有 m 个异常月份(低 8 个百分点),斜率误差的中位数(百分点/年)")
fmt.Println("位置 m 占比 OLS Theil–Sen 重复中位数")
n := 24
x := months(n)
for _, placement := range []string{"随机", "最近"} {
for _, m := range []int{0, 2, 4, 6, 7, 8, 10, 12} {
r := rand.New(rand.NewPCG(1, uint64(m)))
errs := make([][]float64, len(estimators))
for t := 0; t < trials; t++ {
y := line(r, x)
var idx []int
if placement == "随机" {
idx = r.Perm(n)[:m]
} else {
for k := n - m; k < n; k++ {
idx = append(idx, k)
}
}
for _, k := range idx {
y[k] -= 8
}
for e, est := range estimators {
errs[e] = append(errs[e], math.Abs(must(est.fit(x, y)).Slope-trueSlope))
}
}
fmt.Printf("%s %2d %3.0f%% %6.2f %9.2f %10.2f\n", placement, m, 100*float64(m)/float64(n),
medianAbsErr(errs[0]), medianAbsErr(errs[1]), medianAbsErr(errs[2]))
}
}
}
// B:季节起伏,不加噪声,只看偏差。三种形状(month 取 0~11,0 = 一月):
//
// 平滑:-1.5*cos(2π*month/12),一月最低、七月最高;
// 短促:只有十二月到二月低 3 个百分点,其余月份正常;
// 平滑+半年:-1.5*cos(2π*month/12) - 0.5*sin(2π*month/6),起伏不再左右对称。
func seasonal() {
shapes := []struct {
name string
dev func(month int) float64 // month: 0 = 一月
}{
{"平滑", func(m int) float64 { return -1.5 * math.Cos(2*math.Pi*float64(m)/12) }},
{"短促", func(m int) float64 {
if m == 11 || m == 0 || m == 1 {
return -3
}
return 0
}},
{"平滑+半年", func(m int) float64 {
return -1.5*math.Cos(2*math.Pi*float64(m)/12) - 0.5*math.Sin(2*math.Pi*float64(m)/6)
}},
}
fmt.Println("\n== B. 季节起伏(无噪声):12 个起点月份各算一次,估出的斜率范围(百分点/年)")
fmt.Println("形状 窗口(月) OLS Theil–Sen 季节 Sen")
for _, shape := range shapes {
for _, n := range []int{12, 18, 24, 36} {
lo := []float64{math.Inf(1), math.Inf(1), math.Inf(1)}
hi := []float64{math.Inf(-1), math.Inf(-1), math.Inf(-1)}
for start := 0; start < 12; start++ {
x := months(n)
y := make([]float64, n)
season := make([]int, n)
for i := range x {
month := (start + i) % 12
season[i] = month
y[i] = 100 + trueSlope*x[i] + shape.dev(month)
}
res := []float64{must(trend.OLS(x, y)).Slope, must(trend.TheilSen(x, y, 0.95)).Slope, math.NaN()}
if f, err := trend.SeasonalSen(x, season, y); err == nil {
res[2] = f.Slope
}
for k, v := range res {
lo[k] = math.Min(lo[k], v)
hi[k] = math.Max(hi[k], v)
}
}
cell := func(k int) string {
if math.IsNaN(lo[k]) || math.IsInf(lo[k], 0) {
return "不可用"
}
return fmt.Sprintf("%6.2f ~ %6.2f", lo[k], hi[k])
}
fmt.Printf("%s %4d %s %s %s\n", padCJK(shape.name, 10), n, cell(0), cell(1), cell(2))
}
}
}
// padCJK 按显示宽度补空格(中文字符算 2 格),让表格对齐。
func padCJK(s string, width int) string {
w := 0
for _, r := range s {
if r >= 0x2E80 {
w += 2
} else {
w++
}
}
for ; w < width; w++ {
s += " "
}
return s
}
// F:台阶。比如某次软件更新后估算方式变了,之后每个月都高 3 个百分点。
func step() {
fmt.Println("\n== F. 36 个月,第 k 个月起整体抬高 3 个百分点(无噪声),估出的斜率(百分点/年)")
fmt.Println("k OLS Theil–Sen 重复中位数")
n := 36
x := months(n)
for _, at := range []int{6, 18, 30} {
y := make([]float64, n)
for i := range x {
y[i] = 100 + trueSlope*x[i]
if i >= at {
y[i] += 3
}
}
fmt.Printf("%2d %6.2f %9.2f %10.2f\n", at, must(trend.OLS(x, y)).Slope,
must(trend.TheilSen(x, y, 0.95)).Slope, must(trend.RepeatedMedian(x, y)).Slope)
}
}
// trailingMedian3 模仿常见的“月度值先做 3 个月滚动中位数再算趋势”。
// 开头不足 3 个点时,就用已有的 1 个或 2 个点。
func trailingMedian3(y []float64) []float64 {
out := make([]float64, len(y))
for i := range y {
w := y[max(0, i-2) : i+1]
s := slices.Clone(w)
slices.Sort(s)
if len(s)%2 == 1 {
out[i] = s[len(s)/2]
} else {
out[i] = (s[0] + s[1]) / 2
}
}
return out
}
// C:95% 置信区间实际覆盖真值的比例。
func coverage() {
fmt.Println("\n== C. Sen 95% 置信区间的实际覆盖率(24 个月,4000 次)")
fmt.Println("数据 覆盖率 平均宽度 斜率误差中位数")
n := 24
x := months(n)
cases := []struct {
name string
gen func(r *rand.Rand) []float64
}{
{"独立噪声", func(r *rand.Rand) []float64 { return line(r, x) }},
{"独立噪声 + 3 月滚动中位数", func(r *rand.Rand) []float64 { return trailingMedian3(line(r, x)) }},
{"AR(1) 噪声 φ=0.6", func(r *rand.Rand) []float64 {
y := make([]float64, n)
e := r.NormFloat64() * noiseSD
for i := range y {
if i > 0 {
// 平稳方差保持和独立噪声一样
e = 0.6*e + r.NormFloat64()*noiseSD*math.Sqrt(1-0.36)
}
y[i] = 100 + trueSlope*x[i] + e
}
return y
}},
}
for ci, c := range cases {
r := rand.New(rand.NewPCG(3, uint64(ci)))
hit := 0
var width float64
var errs []float64
for t := 0; t < trials; t++ {
f := must(trend.TheilSen(x, c.gen(r), 0.95))
if f.Lo <= trueSlope && trueSlope <= f.Hi {
hit++
}
width += f.Hi - f.Lo
errs = append(errs, math.Abs(f.Slope-trueSlope))
}
fmt.Printf("%-26s %5.1f%% %8.2f %8.2f\n", c.name, 100*float64(hit)/trials, width/trials, medianAbsErr(errs))
}
}
// D:没有异常点、噪声是正态时,稳健要付出多少精度。
func efficiency() {
fmt.Println("\n== D. 纯正态噪声、无异常点时,斜率估计的标准差(百分点/年,4000 次)")
fmt.Println("月数 OLS Theil–Sen 重复中位数 OLS方差/TS方差 OLS方差/RM方差")
for _, n := range []int{12, 24, 60} {
x := months(n)
r := rand.New(rand.NewPCG(4, uint64(n)))
sums := make([]float64, len(estimators))
sq := make([]float64, len(estimators))
for t := 0; t < trials; t++ {
y := line(r, x)
for e, est := range estimators {
v := must(est.fit(x, y)).Slope
sums[e] += v
sq[e] += v * v
}
}
sd := make([]float64, len(estimators))
for e := range estimators {
mean := sums[e] / trials
sd[e] = math.Sqrt(sq[e]/trials - mean*mean)
}
fmt.Printf("%3d %.3f %9.3f %10.3f %14.2f %14.2f\n", n, sd[0], sd[1], sd[2],
sd[0]*sd[0]/(sd[1]*sd[1]), sd[0]*sd[0]/(sd[2]*sd[2]))
}
}
// E:点多了以后的耗时和内存。
func cost() {
fmt.Println("\n== E. 规模:点数、点对数、单次耗时、斜率切片占的内存")
fmt.Println("点数 点对数 Theil–Sen 重复中位数 斜率切片大小")
for _, n := range []int{120, 1000, 3000, 10000} {
r := rand.New(rand.NewPCG(5, uint64(n)))
x := make([]float64, n)
for i := range x {
x[i] = r.Float64() * 10
}
y := line(r, x)
runtime.GC()
t0 := time.Now()
f := must(trend.TheilSen(x, y, 0.95))
tsDur := time.Since(t0)
t0 = time.Now()
must(trend.RepeatedMedian(x, y))
rmDur := time.Since(t0)
fmt.Printf("%6d %12d %11s %11s %8.1f MB\n", n, f.Pairs, tsDur.Round(time.Microsecond),
rmDur.Round(time.Microsecond), float64(f.Pairs)*8/1e6)
}
}
func main() {
fmt.Println(runtime.Version(), runtime.GOOS+"/"+runtime.GOARCH)
sections := map[string]func(){"A": outliers, "B": seasonal, "C": coverage, "D": efficiency, "E": cost, "F": step}
if len(os.Args) > 1 {
for _, s := range os.Args[1:] {
sections[s]()
}
return
}
for _, s := range []string{"A", "B", "C", "D", "E", "F"} {
sections[s]()
}
}
cmd/dump/main.go:
// dump 生成一组带并列值和异常点的数据,把 Go 的计算结果写成 JSON,
// 交给 crosscheck.py 用 SciPy 复算比对。
package main
import (
"encoding/json"
"math/rand/v2"
"os"
"example.com/robustslope/trend"
)
type output struct {
X, Y []float64
Conf float64
TheilSen trend.Fit
Siegel struct{ Slope, Intercept float64 }
}
func main() {
r := rand.New(rand.NewPCG(2026, 11))
var x, y []float64
for i := 0; i < 40; i++ {
xi := float64(i / 2) // 每个 x 出现两次:x 有并列
yi := 100 - 0.15*xi + r.NormFloat64()*0.5
if i%9 == 0 {
yi -= 6 // 异常点
}
if i == 7 {
yi = y[len(y)-1] // y 也造一个并列
}
x = append(x, xi)
y = append(y, yi)
}
ts, err := trend.TheilSen(x, y, 0.95)
if err != nil {
panic(err)
}
rm, err := trend.RepeatedMedian(x, y)
if err != nil {
panic(err)
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(output{X: x, Y: y, Conf: 0.95, TheilSen: ts, Siegel: struct{ Slope, Intercept float64 }{rm.Slope, rm.Intercept}}); err != nil {
panic(err)
}
}
crosscheck.py:
"""用 SciPy 复算 dump 输出的那一组样例,六项要求完全相等(差为 0)。
只对这组输入做断言,不代表任意输入都逐位相同。用法:python3 crosscheck.py case.json
"""
import json
import sys
import scipy
from scipy import stats
case = json.load(open(sys.argv[1]))
x, y = case["X"], case["Y"]
ts = stats.theilslopes(y, x, alpha=case["Conf"])
sg = stats.siegelslopes(y, x, method="separate")
checks = [
("theil slope", ts.slope, case["TheilSen"]["Slope"]),
("theil intercept", ts.intercept, case["TheilSen"]["Intercept"]),
("theil low", ts.low_slope, case["TheilSen"]["Lo"]),
("theil high", ts.high_slope, case["TheilSen"]["Hi"]),
("siegel slope", sg.slope, case["Siegel"]["Slope"]),
("siegel intercept", sg.intercept, case["Siegel"]["Intercept"]),
]
print("scipy", scipy.__version__)
ok = True
for name, want, got in checks:
diff = abs(want - got)
ok &= want == got
print(f"{name:17s} scipy={want:.12f} go={got:.12f} diff={diff:.1e}")
sys.exit(0 if ok else 1)
从空目录跑起来
按上面的结构放好文件,在 robustslope/ 目录下:
go vet ./...
go test ./...
go run ./cmd/experiments
python3 -m venv .venv
.venv/bin/pip install scipy
go run ./cmd/dump > case.json
.venv/bin/python crosscheck.py case.json
A~D、F 的数字由固定种子决定,同一个 Go 版本上每次都一样;E 是计时,随机器不同。crosscheck.py 只核对 dump 生成的那一组样例,六项完全相等时退出码为 0。
参考
- Theil–Sen estimator(维基百科):崩溃点 29.3%(引 Rousseeuw & Leroy 2003)、季节变体(引 Hirsch, Slack & Smith 1982)、O(n log n) 算法汇总
- Repeated median regression(维基百科):崩溃点 50%
- H. Theil, “A rank-invariant method of linear and polynomial regression analysis”, Nederl. Akad. Wetensch. Proc. 53 (1950)
- P. K. Sen, “Estimates of the regression coefficient based on Kendall’s tau”, JASA 63(324): 1379–1389 (1968)
- A. F. Siegel, “Robust regression using repeated medians”, Biometrika 69(1): 242–244 (1982)
- R. M. Hirsch, J. R. Slack, R. A. Smith, “Techniques of trend analysis for monthly water quality data”, Water Resources Research 18(1): 107–121 (1982)
- SciPy 1.18.1:scipy.stats.theilslopes、scipy.stats.siegelslopes
讨论
点击后加载 giscus 讨论。登录与发表由你自行操作。