最小二乘拟合二维直线

目录

  • 1. 原理概述
  • 2. python实现
  • 3. matlab实现
  • 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(xi,yi)0i<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=1nkxi+byi(2)
  分别求 f ( x ) f(x) f(x)对于 k 、 b k、b kb的偏导数:
δ 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=1n2(kxi+byi)xi=2i=1nkxi2+bxixiyi=2(ki=1nxi2+bi=1nxii=1nxiyi)(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=1n2(kxi+byi)=2i=1nkxi+byi=2(ki=1nxi+bni=1nyi)(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} {ki=1nxi2+bi=1nxi=i=1nxiyiki=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=1nxi2,B=i=1nxi,C=i=1nxiyi,D=i=1nyi
于是有:

{ 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 kb
{ 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=nAB2nCBDb=nAB2DABC(7)

2. 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)

最小二乘拟合二维直线_第1张图片

3. matlab实现

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);

最小二乘拟合二维直线_第2张图片

4. C++实现

    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);

最小二乘拟合二维直线_第3张图片

你可能感兴趣的:(CloudCompare,开发语言,平面,线性代数,算法,计算机视觉)