# 黑盒函数的探索

### 黑盒函数的研究对象

1. 最大值与最小值，i.e. $\max f(x)$$\min f(x).$
2. 根，i.e. $\{x:f(x) = 0\}.$
3. 函数的单调性与凹凸性等。

### 黑盒函数的根

$x = \frac{-b\pm\sqrt{b^{2}-4ac}}{2a}.$

#### 二分法

[介值定理] 如果连续函数 $f(x)$ 的定义域包含 $[a,b],$ 而且通过 $(a,f(a))$$(b,f(b))$ 两点，它也必定通过区间 $[a,b]$ 内的任意一点 $(c,f(c)),$ 其中 $a

1. 先找到一个区间 $[a,b],$ 使得 $f(a)f(b)<0;$
2. 求这个区间的中点 $m=(a+b)/2,$ 并求出 $f(m)$ 的取值；
3. 如果 $f(m)=0,$ 那么 $m$ 就是函数的根；如果 $f(m)f(a)>0,$ 就选择 $[m,b]$ 为新的区间，否则选择 $[a,m]$ 为新的区间；
4. 重复第 2 步和第 3 步直到达到最大迭代次数或者最理想的精度为止。

#### 牛顿法（Newton’s Method）

$x_{1} = x_{0} - f(x_{0})/f'(x_{0}).$

$x_{n+1}= x_{n}-f(x_{n})/f'(x_{n}).$

#### 割线法

$f'(x_{0}) = \lim_{x\rightarrow x_{0}}\frac{f(x)-f(x_{0})}{x-x_{0}}$

$f'(x_{0}) \approx \frac{f(x)-f(x_{0})}{x-x_{0}}.$

$x_{n+1} = x_{n} - \frac{x_{n}-x_{n-1}}{f(x_{n})-f(x_{n-1})}f(x_{n}).$

### 黑盒函数的最大值与最小值

#### Weierstrass 逼近定理

1. 闭区间上的连续函数可以用多项式级数一致逼近；
2. 闭区间上的周期为 $2\pi$ 的连续函数可以用三角函数级数一致逼近。

[Weierstrass 逼近定理] 假设 $f(x)$ 是闭区间 $[a,b]$ 连续的实函数。对于任意的 $\epsilon>0$，存在一个多项式 $p(x)$ 使得对于任意的 $x\in[a,b],$$|f(x)-p(x)|<\epsilon.$

#### Lagrange 插值公式

$p(x) = \sum_{i=0}^{n}\bigg(\prod_{0\leq j\leq n, j\neq i}\frac{x-x_{j}}{x_{i}-x_{j}}\bigg)y_{i}.$

#### 粒子群算法（Particle Swarm Optimization）

PSO 最初是为了模拟鸟群等动物的群体运动而形成的一种优化算法。PSO 算法是假设有一个粒子群，根据群体粒子和单个粒子的最优效果，来调整每一个粒子的下一步行动方向。假设粒子的个数是 $N_{p}$，每一个粒子 $\bold{x}_{i}\in \mathbb{R}^{n}$ 都是 $n$ 维欧几里德空间里面的点，同时需要假设粒子的速度 $\bold{v}_{i}\in\mathbb{R}^{n}$。在每一轮迭代中，需要更新两个最值，分别是每一个粒子在历史上的最优值和所有粒子在历史上的最优值，分别记为 $\bold{x}_{i}^{*}$$1\leq i \leq N_{p}$）和 $\bold{x}^{g}$。在第 $t+1$ 次迭代的时候，

$\bold{v}_{i}(t+1) = \bold{v}_{i}(t) + c r_{1}[\bold{x}_{i}^{*}(t) - \bold{x}_{i}(t)] + c r_{2}[\bold{x}^{g}(t) - \bold{x}_{i}(t)],$

$\bold{x}_{i}(t+1) = \bold{x}_{i}(t)+\bold{v}_{i}(t+1), \text{ } 1\leq i\leq N_{p}.$

#### 模拟退火（Simulated Annealing）

Repeat：

a. Repeat:

i. 进行一个随机扰动 $\bold{x} = \bold{x} + \Delta \bold{x}$

ii. 计算 $\Delta E(\bold{x}) = E(\bold{x}+\Delta\bold{x}) - E(\bold{x})$

b. 令 $T = T-\Delta T$

# 时间序列的自回归模型—从线性代数的角度来看

### Fibonacci 序列

$F_{n}=F_{n-1}+F_{n-2}$

0，1，1，2，3，5，8，13，21，34，55，89，144，…

### 求解 Fibonacci 序列的通项公式 －－－ 矩阵对角化

$\left( \begin{array}{c} F_{n+2} \\ F_{n+1} \\ \end{array}\right)= \left( \begin{array}{cc} 1 & 1 \\ 1 & 0 \\ \end{array}\right) \left( \begin{array}{c} F_{n+1} \\ F_{n} \\ \end{array}\right) = A \left( \begin{array}{c} F_{n+1} \\ F_{n} \\ \end{array}\right),$

$\left( \begin{array}{c} F_{n} \\ F_{n-1} \\ \end{array}\right)= A \left( \begin{array}{c} F_{n-1} \\ F_{n-2} \\ \end{array}\right) = \cdots = A^{n-1} \left( \begin{array}{c} F_{1} \\ F_{0} \\ \end{array}\right).$

$P^{-1}AP = diag(\lambda_{1},\cdots,\lambda_{m})$

$\implies AP = P diag(\lambda_{1},\cdots,\lambda_{m})$

$\implies A = P diag(\lambda_{1},\cdots,\lambda_{m})P^{-1}.$

$A^{k} = (PDP^{-1})\cdots(PDP^{-1}) = P D^{k} P^{-1}= P diag(\lambda_{1}^{k},\cdots,\lambda_{m}^{k})P^{-1}.$

$det(\lambda I - A) = 0,$

$A = \left( \begin{array}{cc} 1 & 1 \\ 1 & 0 \\ \end{array}\right)$,

$\vec{\alpha}_{1} = (\phi,1)^{T}, \vec{\alpha}_{2} = (-\phi^{-1},1)$.

$F_{k} = \frac{1}{\sqrt{5}}\bigg(\frac{1+\sqrt{5}}{2}\bigg)^{k} - \frac{1}{\sqrt{5}}\bigg(\frac{1-\sqrt{5}}{2}\bigg)^{k}=\frac{\phi^{k}-(-\phi)^{-k}}{\sqrt{5}}$.

### 时间序列的弱平稳性

1. $E(x_{t})$ 对于所有的 $t\geq 0$ 都是恒定的；
2. $Var(x_{t})$ 对于所有的 $t\geq 0$ 都是恒定的；
3. $x_{t}$$x_{t-h}$ 的协方差对于所有的 $t\geq 0$ 都是恒定的。

$ACF(x_{t},x_{t-h}) = \frac{Covariance(x_{t},x_{t-h})}{\sqrt{Var(x_{t})\cdot Var(x_{t-h})}}$.

$ACF(x_{t},x_{t-h}) = \frac{Covariance(x_{t},x_{t-h})}{Var(x_{t})}$.

### 时间序列的自回归模型（AutoRegression Model）

#### AR(1) 模型

AR(1) 模型指的是时间序列 $\{x_{t}\}_{t\geq 0}$ 在时间戳 $t$ 时刻的取值 $x_{t}$ 与时间戳 $t - 1$ 时刻的取值 $x_{t-1}$ 相关，其公式就是：

$x_{t}=\delta+\phi_{1}x_{t-1}+w_{t}$

1. $w_{t}\sim N(0,\sigma_{w}^{2})$，并且 $w_{t}$ 满足 iid 条件。其中 $N(0,\sigma_{w}^{2})$ 表示 Gauss 正态分布，它的均值是0，方差是 $\sigma_{w}^{2}$
2. $w_{t}$$x_{t}$ 是相互独立的（independent）。
3. $x_{0},x_{1},\cdots$弱平稳的，i.e. 必须满足 $|\phi_{1}|<1$

1. $E(x_{t}) = \delta/(1-\phi_{1})$.
2. $Var(x_{t}) = \sigma_{w}^{2}/(1-\phi_{1}^{2})$.
3. $Covariance(x_{t},x_{t-h}) = \phi_{1}^{h}$.

Proof of 1. 从 AR(1) 的模型出发，可以得到

$E(x_{t}) = E(\delta + \phi_{1}x_{t-1}+w_{t}) = \delta + \phi_{1}E(x_{t-1}) = \delta + \phi_{1}E(x_{t})$,

Proof of 2. 从 AR(1) 的模型出发，可以得到

$Var(x_{t}) = Var(\delta + \phi_{1}x_{t-1}+w_{t})$

$= \phi_{1}^{2}Var(x_{t-1}) +Var(w_{t}) = \phi_{1}^{2}Var(x_{t}) + \sigma_{w}^{2}$,

Proof of 3.$\mu = E(x_{t}), \forall t\geq 0$. 从 $x_{t}$ 的定义出发，可以得到：

$x_{t}-\mu = \phi_{1}(x_{t-1}-\mu)+w_{t}$

$= \phi_{1}^{h}(x_{t-h}-\mu) + \phi_{1}^{h-1}w_{t-h+1}+\cdots+\phi_{1}w_{t-1}+w_{t},$

$\rho_{h} = Covariance(x_{t},x_{t-h}) = \frac{E((x_{t}-\mu)\cdot(x_{t-h}-\mu))}{Var(x_{t})}=\phi_{1}^{h}$.

#### AR(1) 模型与一维动力系统

$f(x) = \phi_{1}x + \delta,$

Method 1.

$f^{n}(x) = \phi_{1}^{n}x+ \frac{1-\phi_{1}^{n}}{1-\phi_{1}}\delta$,

$n\rightarrow \infty$，可以得到 $f^{n}(x)\rightarrow \delta/(1-\phi_{1})$。这与 $E(x_{t}) = \delta/(1-\phi_{1})$ 其实是保持一致的。

Method 2.

$f(x)-\frac{\delta}{1-\phi_{1}} = \phi_{1}(x-\frac{\delta}{1-\phi_{1}})$

$\implies |f(x)-\frac{\delta}{1-\phi_{1}}| <\frac{1+|\phi_{1}|}{2}\cdot|x-\frac{\delta}{1-\phi_{1}}|$

$\implies |f^{n}(x)-\frac{\delta}{1-\phi_{1}}|<\bigg(\frac{1+|\phi_{1}|}{2}\bigg)^{n}\cdot|x-\frac{\delta}{1-\phi_{1}}|$.

$f(x)-\frac{\delta}{1-\phi_{1}} = \phi_{1}(x-\frac{\delta}{1-\phi_{1}})$

$\implies |f(x)-\frac{\delta}{1-\phi_{1}}| >\frac{1+|\phi_{1}|}{2}\cdot|x-\frac{\delta}{1-\phi_{1}}|$

$\implies |f^{n}(x)-\frac{\delta}{1-\phi_{1}}|>\bigg(\frac{1+|\phi_{1}|}{2}\bigg)^{n}\cdot|x-\frac{\delta}{1-\phi_{1}}|$.

#### AR(p) 模型

1. AR(1) 模型形如：

$x_{t}=\delta+\phi_{1}x_{t-1}+w_{t}.$

2. AR(2) 模型形如：

$x_{t} = \delta + \phi_{1}x_{t-1}+\phi_{2}x_{t-2}+w_{t}.$

3. AR(p) 模型形如：

$x_{t} = \delta + \phi_{1}x_{t-1}+\phi_{2}x_{t-2}+\cdots+\phi_{p}x_{t-p}+w_{t}.$

#### AR(p) 模型的稳定性 －－－ 基于线性代数

$x_{t}= \phi_{1}x_{t-1} + \phi_{2}x_{t-2}$.

$\left( \begin{array}{c} x_{t+2} \\ x_{t+1} \\ \end{array}\right)= \left( \begin{array}{cc} \phi_{1} & \phi_{2} \\ 1 & 0 \\ \end{array}\right) \left( \begin{array}{c} x_{t+1} \\ x_{t} \\ \end{array}\right) = A \left( \begin{array}{c} x_{t+1} \\ x_{t} \\ \end{array}\right).$

$x_{t} = \phi_{1}x_{t-1}+\phi_{2}x_{t-2}+\cdots+\phi_{p}x_{t-p}.$

$\left(\begin{array}{c} x_{t+p} \\ x_{t+p-1} \\ \vdots \\ x_{t+1}\\ \end{array}\right) = \left(\begin{array}{ccccc} \phi_{1} & \phi_{2} &\cdots & \phi_{p-1} & \phi_{p} \\ 1 & 0 & \cdots & 0 & 0 \\ \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & \cdots & 1 & 0 \\ \end{array}\right) \left(\begin{array}{c} x_{t+p-1} \\ x_{t+p-2} \\ \vdots \\ x_{t} \\ \end{array}\right) = A \left(\begin{array}{c} x_{t+p-1} \\ x_{t+p-2} \\ \vdots \\ x_{t} \\ \end{array}\right)$

$\lambda^{p}-\phi_{1}\lambda^{p-1}-\phi_{2}\lambda^{p-2}-\cdots-\phi_{p}=0.$

$x_{t} = \phi_{1}x_{t-1}+\phi_{2}x_{t-2}+\cdots+\phi_{p}x_{t-p}$

# 如何理解时间序列？— 从Riemann积分和Lebesgue积分谈起

Riemann 积分和 Lebesgue 积分是数学中两个非常重要的概念。本文将会从 Riemann 积分和 Lebesgue 积分的定义出发，介绍它们各自的性质和联系。

## 积分

### Riemann 积分

Riemann 积分虽然被称为 Riemann 积分，但是在 Riemann 之前就有学者对这类积分进行了详细的研究。早在阿基米德时代，阿基米德为了计算曲线 $x^{2}$ 在 [0,1] 区间上与 X 坐标轴所夹的图形面积，就使用了 Riemann 积分的思想。 他把 [0,1] 区间等长地切割成 n 段，每一段使用一个长方形去逼近 $x^{2}$ 这条曲线的分段面积，再把 n 取得很大，所以得到当 n 趋近于无穷的时候，就知道该面积其实是 1/3。

$\sum_{i=0}^{n-1}f(t_{i})(x_{i+1}-x_{i}).$

$|\sum_{i=0}^{n-1}f(t_{i})(x_{i+1}-x_{i}) - s|<\epsilon.$

### Lebesgue 积分

Riemann 积分是为了计算曲线与 X 轴所围成的面积，而 Lebesgue 积分也是做同样的事情，但是计算面积的方法略有不同。要想直观的解释两种积分的原理，可以参见下图：

Riemann 积分是把一条曲线的底部分成等长的区间，测量每一个区间上的曲线高度，所以总面积就是这些区间与高度所围成的面积和。

Lebesgue 积分是把曲线化成等高线图，每两根相邻等高线的差值是一样的。每根等高线之内含有它所圈着的长度，因此总面积就是这些等高线内的面积之和。

1. Riemann 积分：从一个角落开始一口一口吃，每口都包含所有的配料；
2. Lebesgue 积分：从最上层开始吃，按照“面包-配菜-肉-蛋-面包”的节奏，一层一层来吃。

$\int(\sum_{k}a_{k}1_{S_{k}})d\mu = \sum_{k}a_{k}\int 1_{S_{k}}d\mu = \sum_{k}a_{k}\mu(S_{k}).$

$\int_{E}f d\mu = \sup\{\int_{E}sd\mu: \bold{0}\leq s\leq f\}$,

$\int fd\mu = \int f^{+}d\mu - \int f^{-}d\mu.$.

### Riemann 积分与Lebesgue 积分的关系

$(R)\int_{a}^{b}f(x)dx = (L)\int_{[a,b]}f(x)dx$.

1. $x$ 是有理数时，$D(x) = 1$
2. $x$ 是无理数时，$D(x) = 0$.

Dirichlet 函数是定义在实数轴的函数，并且值域是 $\{0,1\}$，无法画出函数图像，它不是 Riemann 可积的，但是它 Lebesgue 可积。

## 时间序列

### 时间序列的表示 — 基于 Riemann 积分

1. 分段线性逼近（Piecewise Linear Approximation）
2. 分段聚合逼近（Piecewise Aggregate Approximation）
3. 分段常数逼近（Piecewise Constant Approximation）

#### 分段聚合逼近（Piecewise Aggregate Approximation）— 类似 Riemann 积分

$\overline{x}_{i} = \frac{w}{N} \cdot \sum_{j=\frac{N}{w}(i-1)+1}^{\frac{N}{w}i} x_{j}$.

#### 符号特征（Symbolic Approximation）— 类似用简单函数来计算 Lebesgue 积分

SAX 方法的流程如下：

1. 正规化（normalization）：把原始的时间序列映射到一个新的时间序列，新的时间序列满足均值为零，方差为一的条件。
2. 分段表示（PAA）：$\{x_{1},\cdots, x_{N}\} \Rightarrow \{\overline{x}_{1},\cdots,\overline{x}_{w}\}$
3. 符号表示（SAX）：如果 $\overline{x}_{i}，那么 $\hat{X}_{i}=l_{1}$；如果 $z_{(j-1)/\alpha}\leq \overline{x}_{i}，那么 $\hat{X}_{i} = l_{j}$，在这里 $2\leq j\leq \alpha$；如果 $\overline{x}_{i}\geq z_{(\alpha-1)/\alpha}$，那么 $\hat{X}_{i} = l_{\alpha}$

### 时间序列的表示 — 基于 Lebesgue 积分

#### 熵（Entropy）

$\text{entropy}(X) = -\sum_{i=1}^{\infty}P\{x=x_{i}\}\ln(P\{x=x_{i}\})$.

#### 分桶熵（Binned Entropy）

$\text{binned entropy}(X) = -\sum_{k=0}^{\min(maxbin, len(X))} p_{k}\ln(p_{k})\cdot 1_{(p_{k}>0)},$

# 时间序列的相似性

#### 度量空间

1. $d(x,y)\geq 0$，并且 $d(x,y)=0$ 当且仅当 $x=y$;
2. $d(x,y)=d(y,x)$，也就是满足对称性；
3. $d(x,z)\leq d(x,y)+d(y,z)$，也就是三角不等式。

Remark.

#### 内积空间

1. 对于任意的 $x,y\in V$，有 $ =\overline{}.$

2. 共轭双线性形式指的是：

$\forall a\in F, \forall x,y\in V, =a,$

$\forall x,y,z\in F, = + .$

$\forall b\in F, \forall x,y\in V, = \overline{b},$

$\forall x,y,z\in F, = +.$

3. 非负性：$\forall x\in V, \geq 0.$

4. 非退化：从 $V$ 到对偶空间 $V^{*}$ 的映射：$x\mapsto$ 是同构映射。

### 基于欧几里德距离的相似度计算

$d_{L^{1}}(X_{T},Y_{T}) = \sum_{t=1}^{T}|x_{t}-y_{t}|,$

$d_{L^{p}}(X_{T}, Y_{T}) = (\sum_{t=1}^{T}|x_{t}-y_{t}|^{p})^{1/p},$

$d_{L^{2}}(X_{T}, Y_{T}) = (\sum_{t=1}^{T}|x_{t}-y_{t}|^{2})^{1/2},$

$d_{L^{\infty}}(X_{T},Y_{T}) = \max_{1\leq t\leq T}|x_{t}-y_{t}|.$

### 基于相关性的相似度计算方法

#### Pearson 系数（Pearson Coefficient）

$\text{COR}(X_{T},Y_{T}) = \frac{\sum_{t=1}^{T}(x_{t}-\overline{X}_{T})\cdot(y_{t}-\overline{Y}_{T})}{\sqrt{\sum_{t=1}^{T}(x_{t}-\overline{X}_{T})^{2}}\cdot\sqrt{\sum_{t=1}^{T}(y_{t}-\overline{Y}_{T})^{2}}},$

$\overline{X}_{T} = \sum_{t=1}^{T}x_{t}/T$, $\overline{Y}_{T} = \sum_{t=1}^{T}y_{t}/T$

Pearson 系数的性质如下：

1. 如果两条时间序列 $X_{T} = Y_{T}$，则 $\text{COR}(X_{T},Y_{T}) =1$ 表是它们是完全一致的，如果两条时间序列 $X_{T} = -Y_{T}$，则 $\text{COR}(X_{T},Y_{T}) = -1$ 表示它们之间是负相关的。
2. $-1\leq \text{COR}(X_{T},Y_{T})\leq 1$.

$d_{COR,1}(X_{T},Y_{T}) = \sqrt{2\cdot(1-COR(X_{T},Y_{T}))},$

$d_{COR,2}(X_{T},Y_{T}) = \sqrt{\big(\frac{1-COR(X_{T},Y_{T})}{1+COR(X_{T},Y_{T})}\big)^{\beta}},$

#### The First Order Temporal Correlation Coefficient

$\text{CORT}(X_{T},Y_{T}) = \frac{\sum_{t=1}^{T-1}(x_{t+1}-x_{t})\cdot(y_{t+1}-y_{t})}{\sqrt{\sum_{t=1}^{T-1}(x_{t+1}-x_{t})^{2}}\cdot\sqrt{\sum_{t=1}^{T-1}(y_{t+1}-y_{t})^{2}}},$

$\text{CORT}(X_{T},Y_{T})$ 的性质：

1. $-1\leq \text{CORT}(X_{T},Y_{T}) \leq 1$
2. $\text{CORT}(X_{T},Y_{T}) =1$ 表示两条时间序列持有类似的趋势， 它们会同时上涨或者下跌，并且涨幅或者跌幅也是类似的。
3. $\text{CORT}(X_{T},Y_{T})=-1$ 表示两条时间序列的上涨和下跌趋势恰好相反。
4. $\text{CORT}(X_{T},Y_{T})=0$ 表示两条时间序列在单调性方面没有相关性。

$d_{CORT}(X_{T},Y_{T}) = \phi_{k}[CORT(X_{T},Y_{T})]\cdot d(X_{T},Y_{T}),$

$\phi_{k}(u) = 2/(1+\exp(ku)), k\geq 0$

#### 基于自相关系数的距离（Autocorrelation-based distance)

$\hat{\rho}_{k} = \frac{1}{(T-k)\sigma^{2}}\sum_{t=1}^{T-k}(x_{t}-\mu)\cdot(x_{t+k}-\mu)$,

$\hat{\rho}_{X_{T}} = (\hat{\rho}_{1,X_{T}},\cdots,\hat{\rho}_{L,X_{T}})^{T}\in \mathbb{R}^{L},$

$\hat{\rho}_{Y_{T}} = (\hat{\rho}_{1,Y_{T}},\cdots,\hat{\rho}_{L,Y_{T}})^{T}\in\mathbb{R}^{L}.$

$d_{ACF}(X_{T},Y_{T}) = \sqrt{(\hat{\rho}_{X_{T}}-\hat{\rho}_{Y_{T}})^{T}\Omega(\hat{\rho}_{X_{T}}-\hat{\rho}_{Y_{T}})}$.

（1）$\Omega = I_{L}$ 表示单位矩阵。用公式表示就是

$d_{ACFU}(X_{T},Y_{T}) =\sqrt{\sum_{i=1}^{L}(\hat{\rho}_{i,X_{T}}-\hat{\rho}_{i,Y_{T}})^{2}}$.

（2）$\Omega = diag\{p(1-p),p(1-p)^{2},\cdots,p(1-p)^{L}\}$ 表示一个 $L\times L$ 的对角矩阵，其中 $0。此时相当于一个带权重的求和公式。

$d_{ACFU}(X_{T},Y_{T}) =\sqrt{\sum_{i=1}^{L}p(1-p)^{i}(\hat{\rho}_{i,X_{T}}-\hat{\rho}_{i,Y_{T}})^{2}}$.

### 基于周期性的相似度计算方法

$I_{X_{T}}(\lambda_{k}) = T^{-1}|\sum_{t=1}^{T}x_{t}e^{-i\lambda_{k}t}|^{2}$,

$I_{Y_{T}}(\lambda_{k}) = T^{-1}|\sum_{t=1}^{T}y_{t}e^{-i\lambda_{k}t}|^{2}$.

（1）用原始的特征来表示距离：

$d_{P}(X_{T},Y_{T}) = \frac{1}{n}\sqrt{\sum_{k=1}^{n}(I_{X_{T}}(\lambda_{k})-I_{Y_{T}}(\lambda_{k}))^{2}}$.

（2）用正则化之后的特征来描述就是：

$d_{P}(X_{T},Y_{T}) = \frac{1}{n}\sqrt{\sum_{k=1}^{n}(NI_{X_{T}}(\lambda_{k})-NI_{Y_{T}}(\lambda_{k}))^{2}}$,

（3）用取对数之后的特征表示：

$d_{LNP}(X_{T},Y_{T}) = \frac{1}{n}\sqrt{\sum_{k=1}^{n}(\ln NI_{X_{T}}(\lambda_{k})-\ln NI_{Y_{T}}(\lambda_{k}))^{2}}$.

### 基于模型的相似度计算

#### Piccolo 距离

$ARMA(p,q)$ 模型有自己的 AR 表示，因此可以得到相应的一组参数 $(\pi_{1},\pi_{2},\cdots)$，所以，对于每一条时间序列，都可以用一组最优的参数去逼近。如果

$\hat{\prod}_{X_{T}}=(\hat{\pi}_{1,X_{T}},\cdots,\hat{\pi}_{k_{1},X_{T}})^{T},$

$\hat{\prod}_{X_{T}}=(\hat{\pi}_{1,X_{T}},\cdots,\hat{\pi}_{k_{1},X_{T}})^{T}$

$d_{PIC}(X_{T},Y_{T}) =\sqrt{\sum_{j=1}^{k}(\hat{\pi}_{j,X_{T}}'-\hat{\pi}_{j,Y_{T}}')^{2}}$,

#### Maharaj 距离

$d_{MAH}(X_{T},Y_{T}) =\sqrt{T}(\hat{\prod}'_{X_{T}}-\hat{\prod}'_{Y_{T}})^{T}\hat{V}^{-1}(\hat{\prod}'_{X_{T}}-\hat{\prod}'_{Y_{T}}).$

#### 基于 Cepstral 的距离

$\psi_{1}=\phi_{1}$

$\psi_{h}=\phi_{h}+\sum_{m=1}^{h-1}(\phi_{m}-\psi_{h-m})$$1

$\psi_{h}=\sum_{m=1}^{p}(1-\frac{m}{h})\phi_{m}\psi_{h-m}$$p

$d_{LPC, Cep}(X_{T},Y_{T}) =\sqrt{\sum_{i=1}^{T}(\psi_{i,X_{T}}-\psi_{i,Y_{T}})^{2}}$.

# 时序数据与事件的关联分析

### 关联关系的挖掘分成三个部分：

（1）是否存在关联性（Existence of Dependency）：在事件（E）与时间序列（S）之间是否存在关联关系。

（2）关联关系的因果关系（Temporal Order of Dependency）：是事件（E）导致了时间序列（S）的变化还是时间序列（S）导致了事件（E）的发生。

（3）关联关系的单调性影响（Monotonic Effect of Dependency）：用于判断时间序列（S）是发生了突增或者是突降。

### 基本概念：

$e_{i}$来表示某个事件，$\ell_{k}^{rear}(S,e_{i})$表示序列S在事件$e_{i}$之后的长度为k的子序列，$\ell_{k}^{front}(S,e_{i})$表示序列S在事件$e_{i}$之前的长度为k的子序列。如果事件E与时间序列S之间存在关联关系，那么

$\Gamma^{front}=\{\ell_{k}^{front}(S,e_{i}), i=1,\cdots,n\}$

$\Gamma^{rear}=\{\ell_{k}^{rear}(S,e_{i}),i=1,\cdots,n\}$应该是不一样的。

### 方法论：

$\Gamma^{front}$来做例子，$\Gamma^{front}=\{\ell_{k}^{front}(S,e_{i}), i=1,\cdots,n\}$$\Theta =\{\theta_{1},\cdots,\theta_{\tilde{n}}\}$ 是随机选择的，$Z=\Gamma \cup \Theta$，可以标记为$Z_{1},\cdots,Z_{p}$，其中$p=n$+$\tilde{n}$$Z_{i}=\ell_{k}^{front}(S,e_{i})$ when $1\leq i\leq n$$Z_{i}=\theta_{i-n}$ when $n$+$1\leq i\leq p$。可以使用记号$A=A_{1}\cup A_{2}$，其中$A_{1}=\Gamma^{front}$$A_{2}=\Theta=\{\theta_{1},\cdots,\theta_{\tilde{n}}\}$是随机选择的。

$I_{r}(x,A_{1},A_{2})=1$ when $x\in A_{i} \&\& NN_{r}(x,A)\in A_{i}$,

$I_{r}(x,A_{1},A_{2})=0$ when otherwise.

$T_{r,p}=\frac{1}{pr}\sum_{i=1}^{p}\sum_{j=1}^{r}I_{j}(x_{i},A_{1},A_{2})$,

$\lambda_{1}=n/p=n/(n$+$\tilde{n})$, $\lambda_{2}=\tilde{n}/(n$+$\tilde{n})$

$\alpha = 1.96$ for $P=0.025$

$\alpha = 2.58$ for $P=0.001$

$t_{score}=\frac{\mu_{\Gamma^{front}} - \mu_{\Gamma^{rear}}}{\sqrt{\frac{\sigma_{\Gamma^{front}}^{2}+\sigma_{\Gamma^{rear}}^{2}}{n}}}$.

$\alpha = 1.96$ for $P=0.025$

$\alpha = 2.58$ for $P=0.001$

### 算法综述：

7-13行是 $E\rightarrow S$ 的情形，因为$\Gamma^{rear}$ 异常，同时 $\Gamma^{front}$ 正常，说明事件导致了时间序列的变化。7-13行是为了计算 $t_{score}$ 的范围，判断是显著的提升还是下降。

14-20行是 $S\rightarrow E$ 的情形，因为$\Gamma^{front}$ 异常，就导致了事件的发生。14-20行是为了计算 $t_{score}$ 的范围，判断是显著的提升还是下降。

（1）Pearson Correlation

（2）J-Measure Correlation

# Opprentice: Towards Practical and Automatic Anomaly Detection Through Machine Learning

### 系统遇到的挑战：

Definition Challenges: it is difficult to precisely define anomalies in reality.（在现实环境下很难精确的给出异常的定义）

Detector Challenges: In order to provide a reasonable detection accuracy, selecting the most suitable detector requires both the algorithm expertise and the domain knowledge about the given service KPI (Key Performance Indicators). To address the definition challenge and the detector challenge, we advocate for using supervised machine learning techniques. （使用有监督学习的方法来解决这个问题）

### 该系统的优势：

(i) Opprentice is the first detection framework to apply machine learning to acquiring realistic anomaly definitions and automatically combining and tuning diverse detectors to satisfy operators’ accuracy preference.

(ii) Opprentice addresses a few challenges in applying machine learning to such a problem: labeling overhead, infrequent anomalies, class imbalance, and irrelevant and redundant features.

(iii) Opprentice can automatically satisfy or approximate a reasonable accuracy preference (recall>=0.66 & precision>=0.66). （准确率和覆盖率的效果）

### 2. 背景描述：

KPIs and KPI Anomalies:

KPIs: The KPI data are the time series data with the format of (time stamp, value). In this paper, Opprentice pays attention to three kinds of KPIs: the search page view (PV), which is the number of successfully served queries; The number of slow responses of search data centers (#SR); The 80th percentile of search response time (SRT).

Anomalies: KPI time series data can also present several unexpected patterns (e.g. jitters, slow ramp ups, sudden spikes and dips) in different severity levels, such as a sudden drop by 20% or 50%.

### 问题和目标：

1-FDR（false discovery rate）：# of false anomalous points detected / # of anomalous points detected = 1 – precision

The quantitative goal of opprentice is precision>=0.66 and recall>=0.66.

The qualitative goal of opprentice is automatic enough so that the operators would not be involved in selecting and combining suitable detectors, or tuning them.

### 3. Opprentice Overview: （Opprentice系统的概况）

(i) Opprentice approaches the above problem through supervised machine learning.

(ii) Features of the data are the results of the detectors.（Basic Detectors 来计算出特征）

(iii) The labels of the data are from operators’ experience.（人工打标签）

(iv) Addressing Challenges in Machine Learning: （机器学习遇到的挑战）

(1) Label Overhead: Opprentice has a dedicated labeling tool with a simple and convenient interaction interface. （标签的获取）

(2) Incomplete Anomaly Cases:（异常情况的不完全信息）

(3) Class Imbalance Problem: （正负样本比例不均衡）

(4) Irrelevant and Redundant Features:（无关和多余的特征）

### 4. Opprentice’s Design:

Architecture: Operators label the data and numerous detectors functions are feature extractors for the data.

Label Tool:

Detectors:

(i) Detectors As Feature Extractors: （Detector用来提取特征）

Here for each parameter detector, we sample their parameters so that we can obtain several fixed detectors, and a detector with specific sampled parameters a (detector) configuration. Thus a configuration acts as a feature extractor:

data point + configuration (detector + sample parameters) -> feature,

(ii) Choosing Detectors: (Detector的选择，目前有14种较为常见的）

Opprentice can find suitable ones from broadly selected detectors, and achieve a relatively high accuracy. Here, we implement 14 widely-used detectors in Opprentice.

Opprentice has 14 widely-used detectors:

Diff“: it simply measures anomaly severity using the differences between the current point and the point of last slot, the point of last day, and the point of last week.

MA of diff“: it measures severity using the moving average of the difference between current point and the point of last slot.

The other 12 detectors come from previous literature. Among these detectors, there are two variants of detectors using MAD (Median Absolute Deviation) around the median, instead of the standard deviation around the mean, to measure anomaly severity.

(iii) Sampling Parameters: （Detector的参数选择方法，一种是扫描参数空间，另外一种是选择最佳的参数）

Two methods to sample the parameters of detectors.

(1) The first one is to sweep the parameter space. For example, in EWMA, we can choose $\alpha \in \{0.1,0.3,0.5,0.7,0.9\}$ to obtain 5 typical features from EWMA; Holt-Winters has three [0,1] valued parameters $\alpha,\beta,\gamma$. To choose $\alpha,\beta,\gamma \in \{0.2,0.4,0.6,0.8\}$, we have $4^3$ features; In ARIMA, we can estimate their “best” parameters from the data, and generate only one set of parameters, or one configuration for each detector.

Supervised Machine Learning Models:

Decision Trees, logistic regression, linear support vector machines (SVMs), and naive Bayes. 下面是决策树（Decision Tree）的一个简单例子。

Random Forest is an ensemble classifier using many decision trees. It main principle is that a group of weak learners (e.g. individual decision trees) can together form a strong learner. To grow different trees, a random forest adds some elements or randomness. First, each tree is trained on subsets sampled from the original training set. Second, instead of evaluating all the features at each level, the trees only consider a random subset of the features each time. The random forest combines those trees by majority vote. The above properties of randomness and ensemble make random forest more robust to noises and perform better when faced with irrelevant and redundant features than decisions trees.

Configuring cThlds: （阈值的计算和预估）

(i) methods to select proper cThlds: offline part

We need to figure cThlds rather than using the default one (e.g. 0.5) for two reasons.

(1) First, when faced with imbalanced data (anomalous data points are much less frequent than normal ones in data sets), machine learning algorithems typically fail to identify the anomalies (low recall) if using the default cThlds (e.g. 0.5).

(2) Second, operators have their own preference regarding the precision and recall of anomaly detection.

The metric to evaluate the precision and recall are:

(1) F-Score: F-Score = 2*precision*recall/(precision+recall).

(2) SD(1,1): it selects the point with the shortest Euclidean distance to the upper right corner where the precision and the recall are both perfect.

(3) PC-Score: （本文中采用这种评估指标来选择合适的阈值）

If r>=R and p>=P, then PC-Score(r,p)=2*r*p/(r+p) + 1; else PC-Score(r,p)=2*r*p/(r+p). Here, R and P are from the operators’ preference “recall>=R and precision>=P”. Since the F-Score is no more than 1, then we can choose the cThld corresponding to the point with the largest PC-Score.

(ii) EWMA Based cThld Prediction: （基于EWMA方法的阈值预估算法）

In online detection, we need to predict cThlds for detecting future data.

Use EWMA to predict the cThld of the i-th week ( or the i-th test set) based on the historical best cThlds. Specially, EWMA works as follows:

If $i=1$, then $cThld_{i}^{p}=cThld_{1}^{p}=$ 5-fold prediction

Else $i>1$, then $cThld_{i}^{p}=\alpha\cdot cThld_{i-1}^{b}$+$(1-\alpha)\cdot cThld_{i-1}^{p}$, where $cThld_{i-1}^{b}$ is the best cThld of the (i-1)-th week. $cThld_{i}^{p}$ is the predicted cThld of the i-th week, and also the one used for detecting the i-th week data. $\alpha\in [0,1]$ is the smoothing constant.

For the first week, we use 5-fold cross-validation to initialize $cThld_{1}^{p}$. As $\alpha$ increases, EWMA gives the recent best cThlds more influences in the prediction. We use $\alpha=0.8$ in this paper.

### 5. Evaluation（系统评估）

Opprentice has 14 detectors with about 9500 lines of Python, R and C++ code. The machine learning block is based on the scikit-learn library.

Random Forest is better than decision trees, logistic regression, linear support vector machines (SVMs), and naive Bayes.