northwolves[狼行天下] 的专栏

无知无惧,无欲无敌。

利用最小二乘法实现图片中多个点的一元线性回归

    在日常生活和科学实验中,人们会经常发现因变量y和自变量x之间存在一定线性关系设一组数据为:

   

yx的关系可以用线性方程表示:

   

 

    按最小二乘法可得:

   

 

   

 

        线性关系的程度可以用相关系数r表示

  

 

        所以,如果想在图象框中根据已知的多个存在线性关系的点描出相应的离所有的点最靠近的直线,应该利用以上一元线性回归的方法,代码如下:

 

Private Sub Command1_Click()
Picture1.Scale (0, 20)-(12, 0) '设置坐标范围
Dim p(4, 1) As Double, i As Integer
For i = 0 To 4
p(i, 0) = Choose(i + 1, 1.2, 3.7, 4.1, 5.1, 8.3)
p(i, 1) = Choose(i + 1, 2.2, 6.4, 7.8, 10.1, 15.8)
Next ' 定义五个点
drawline Picture1, p '画出过五个点的直线
End Sub
Sub drawline(ByVal pic As PictureBox, ByRef p() As Double)
Dim sigmax As Double, sigmay As Double, sigmaxx As Double, sigmaxy As Double, n As Integer
Dim i As Long
Dim a As Double, b As Double '截距斜率
Dim x0 As Double, y0 As Double, x1 As Double, y1 As Double '定义两端点
n = UBound(p) - LBound(p) + 1 '点的个数
For i = LBound(p) To UBound(p)
Picture1.Circle (p(i, 0), p(i, 1)), Picture1.ScaleWidth / 200, vbRed '描点
Picture1.CurrentX = p(i, 0)
Picture1.CurrentY = p(i, 1)
Picture1.ForeColor = vbBlue
Picture1.Print "(" & p(i, 0) & ","; p(i, 1) & ")" '数据标志
sigmax = sigmax + p(i, 0) 'Σx
sigmay = sigmay + p(i, 1) 'Σy
sigmaxx = sigmaxx + p(i, 0) ^ 2 'Σx^2
sigmaxy = sigmaxy + p(i, 0) * p(i, 1) 'Σx*y
Next

a = (sigmaxx * sigmay - sigmax * sigmaxy) / (n * sigmaxx - sigmax ^ 2) '截距
b = (n * sigmaxy - sigmax * sigmay) / (n * sigmaxx - sigmax ^ 2) '斜率
x0 = Picture1.ScaleLeft
y0 = a + b * x0 '左端点
x1 = Picture1.ScaleLeft + Picture1.ScaleWidth
y1 = a + b * x1 '右端点
Picture1.Line (x0, y0)-(x1, y1), vbGreen '回归直线
End Sub

 

结果如下图所示:

  

 

阅读更多
文章标签: integer command 生活
个人分类: 图形界面
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭