Go语言实现最小二乘法算法

最小二乘法(Least Squares Method)是一种用于拟合数据的数学优化方法,广泛用于线性回归。它的目标是通过最小化预测值与实际数据之间的平方误差,找到最优的拟合曲线。下面是用Go语言实现线性回归最小二乘法算法的代码示例:

package main

import (
	"fmt"
	"math"
)

// 定义一对数据点
type Point struct {
	x, y float64
}

// 最小二乘法计算线性回归
func linearRegression(points []Point) (float64, float64) {
	var sumX, sumY, sumXY, sumX2 float64
	n := float64(len(points))

	for _, p := range points {
		sumX += p.x
		sumY += p.y
		sumXY += p.x * p.y
		sumX2 += p.x * p.x
	}

	// 计算斜率 (slope) 和截距 (intercept)
	slope := (n*sumXY - sumX*sumY) / (n*sumX2 - sumX*sumX)
	intercept := (sumY - slope*sumX) / n

	return slope, intercept
}

// 预测函数,给定x值返回y值
func predict(slope, intercept, x float64) float64 {
	return slope*x + intercept
}

func main() {
	// 定义一组数据点
	points := []Point{
		{1, 2},
		{2, 3},
		{3, 5},
		{4, 4},
		{5, 6},
	}

	// 调用线性回归函数
	slope, intercept := linearRegression(points)

	// 输出结果
	fmt.Printf("线性回归方程: y = %.2fx + %.2f\n", slope, intercept)

	// 预测给定 x = 6 时的 y 值
	x := 6.0
	y := predict(slope, intercept, x)
	fmt.Printf("预测 x = %.2f 时的 y 值为: %.2f\n", x, y)
}

代码说明:

  1. Point 结构体用于存储数据点的 xy 值。
  2. linearRegression 函数实现最小二乘法算法,用于计算线性回归的斜率和截距。
  3. predict 函数根据计算的斜率和截距,给定 x 值预测相应的 y 值。
  4. main 函数中通过定义一组数据点,调用线性回归函数,得到线性回归方程,并预测给定 x 值下的 y

最小二乘法是一种数学优化技术,它通过最小化误差的平方和来寻找数据的最佳函数匹配。在C++中实现最小二乘法算法通常涉及线性回归分析。线性回归的目标是找到一条直线(或更一般的情况下的曲线),使得这条直线与观测数据点之间的差异(垂直距离)的平方和最小。这种方法适用于数据拟合、建模和预测等问题。 下面是一个简单的线性最小二乘法的C++实现,该例子假设我们要拟合一条直线 y = ax + b: ```cpp #include <iostream> #include <vector> #include <utility> // For std::pair // 使用std::pair来存储点对(x, y) typedef std::pair<double, double> Point; // 计算线性回归的参数a和b void linearLeastSquares(const std::vector<Point>& points, double& a, double& b) { size_t n = points.size(); double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0; for (const auto& p : points) { sumX += p.first; sumY += p.second; sumXY += p.first * p.second; sumX2 += p.first * p.first; } // 根据最小二乘法公式计算a和b double xMean = sumX / n; double yMean = sumY / n; a = (sumXY - n * xMean * yMean) / (sumX2 - n * xMean * xMean); b = yMean - a * xMean; } int main() { // 示例数据点 std::vector<Point> points = {{1, 2}, {2, 3}, {4, 5}, {5, 7}, {6, 8}}; double a, b; // 计算最小二乘法线性回归参数 linearLeastSquares(points, a, b); std::cout << "Best fit line is y = " << a << "x + " << b << std::endl; return 0; } ``` 这个例子中,我们定义了一个`Point`类型来存储数据点对,然后使用一个函数`linearLeastSquares`来计算最佳拟合直线的斜率(`a`)和截距(`b`)。在`main`函数中,我们创建了一组示例数据点,调用了`linearLeastSquares`函数,并输出了拟合直线的方程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚丁号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值