目录
- [1. 原理概述](#1. 原理概述)
- [2. python实现](#2. python实现)
- [3. matlab实现](#3. matlab实现)
- [4. C++实现](#4. C++实现)
爬虫网站自重。
1. 原理概述
平面直线的表达式为:
y = k x + b (1) y=kx+b \tag{1} y=kx+b(1)
假设有 n n n个点 ( x i , y i ) ( 0 ≤ i < n ) (x_i, y_i)(0≤i<n) (xi,yi)(0≤i<n),于是目标函数为:
f ( x ) = ∑ i = 1 n k x i + b − y i (2) f(x)=\sum_{i=1}^n kx_i+b-y_i\tag{2} f(x)=i=1∑nkxi+b−yi(2)
分别求 f ( x ) f(x) f(x)对于 k 、 b k、b k、b的偏导数:
δ f δ k = ∑ i = 1 n 2 ( k x i + b − y i ) x i = 2 ∑ i = 1 n k x i 2 + b x i − x i y i = 2 ( k ∑ i = 1 n x i 2 + b ∑ i = 1 n x i − ∑ i = 1 n x i y i ) (3) \frac{\delta f}{\delta k}=\sum_{i=1}^n 2(kx_i+b-y_i)x_i=2\sum_{i=1}^n kx_i^2+bx_i-x_iy_i \\=2(k \sum_{i=1}^n x_i^2+b\sum_{i=1}^n x_i- \sum_{i=1}^n x_iy_i)\tag{3} δkδf=i=1∑n2(kxi+b−yi)xi=2i=1∑nkxi2+bxi−xiyi=2(ki=1∑nxi2+bi=1∑nxi−i=1∑nxiyi)(3)
δ f δ b = ∑ i = 1 n 2 ( k x i + b − y i ) = 2 ∑ i = 1 n k x i + b − y i = 2 ( k ∑ i = 1 n x i + b n − ∑ i = 1 n y i ) (4) \frac{\delta f}{\delta b}=\sum_{i=1}^n 2(kx_i+b-y_i)=2\sum_{i=1}^n kx_i+b-y_i \\=2(k \sum_{i=1}^n x_i+bn- \sum_{i=1}^n y_i)\tag{4} δbδf=i=1∑n2(kxi+b−yi)=2i=1∑nkxi+b−yi=2(ki=1∑nxi+bn−i=1∑nyi)(4)
令(3)式和(4)式偏导数为0,得到一个二元一次方程组:
{ k ∑ i = 1 n x i 2 + b ∑ i = 1 n x i = ∑ i = 1 n x i y i k ∑ i = 1 n x i + b n = ∑ i = 1 n y i (5) \begin{cases} k \sum_{i=1}^n x_i^2+b\sum_{i=1}^n x_i= \sum_{i=1}^n x_iy_i\\ k \sum_{i=1}^n x_i+bn= \sum_{i=1}^n y_i \end{cases} \tag{5} {k∑i=1nxi2+b∑i=1nxi=∑i=1nxiyik∑i=1nxi+bn=∑i=1nyi(5)
记
A = ∑ i = 1 n x i 2 , B = ∑ i = 1 n x i , C = ∑ i = 1 n x i y i , D = ∑ i = 1 n y i A=\sum_{i=1}^n x_i^2,B=\sum_{i=1}^n x_i,C=\sum_{i=1}^n x_iy_i,D=\sum_{i=1}^n y_i A=i=1∑nxi2,B=i=1∑nxi,C=i=1∑nxiyi,D=i=1∑nyi
于是有:
{ A k + B b = C B k + b n = D (6) \begin{cases} Ak+Bb=C\\ Bk+bn=D \end{cases} \tag{6} {Ak+Bb=CBk+bn=D(6)
解以上方程组得到 k 、 b k、b k、b
{ k = n C − B D n A − B 2 b = D A − B C n A − B 2 (7) \begin{cases} k=\frac{nC-BD}{nA-B^2}\\ b=\frac{DA-BC}{nA-B^2} \end{cases} \tag{7} {k=nA−B2nC−BDb=nA−B2DA−BC(7)
2. python实现
python
# -----------------------------------拟合直线y=kx+b--------------------------------
n = points.shape[0]
A = sum(x * x)
B = sum(x)
C = sum(x * y)
D = sum(y)
k = (n * C - B * D) / (n * A - B * B)
b = (D * A - B * C) / (n * A - B * B)
3. matlab实现
cpp
n = pc.Count;
A = sum(x.^2);
B = sum(x);
C = sum(x.*y);
D = sum(y);
k = (n * C - B * D) / (n * A - B * B);
b = (D * A - B * C) / (n * A - B * B);
4. C++实现
cpp
int n = cloud->points.size();
double A = 0.0, B = 0.0, C = 0.0, D = 0.0;
for (int i = 0; i < n; i++)
{
A += pow(cloud->points[i].x, 2);
B += cloud->points[i].x;
C += cloud->points[i].x * cloud->points[i].y;
D += cloud->points[i].y;
}
double k = (n * C - B * D) / (n * A - B * B);
double b = (D * A - B * C) / (n * A - B * B);