Python实现迭代重加权最小二乘法(IRLS)

import numpy as np
import matplotlib.pyplot as plt

def irls(x, y, degree, iterations, epsilon):
    # 初始化参数
    theta = np.zeros(degree + 1)
    m = len(x)
    
    # 添加偏置项
    X = np.column_stack([np.power(x, i) for i in range(degree + 1)])
    
    # 迭代更新参数
    for _ in range(iterations):
        # 计算预测值
        y_pred = np.dot(X, theta)
        
        # 计算残差
        residuals = y - y_pred
        
        # 计算权重矩阵
        weights = np.diag(1 / (np.abs(residuals) + epsilon))
        
        # 更新参数
        theta = np.linalg.inv(X.T @ weights @ X) @ X.T @ weights @ y
    
    return theta

# 生成样本数据
x = np.linspace(0, 10, 100)
y = 2 * x + 1 + np.random.randn(100)

# 使用IRLS拟合曲线
degree = 1  # 多项式的次数
iterations = 10  # 迭代次数
epsilon = 0.01  # 避免除零错误的小值
theta = irls(x, y, degree, iterations, epsilon)

# 绘制拟合曲线
x_range = np.linspace(0, 10, 100)
y_pred = np.dot(np.column_stack([np.power(x_range, i) for i in range(degree + 1)]), theta)
plt.scatter(x, y, label='Data')
plt.plot(x_range, y_pred, color='red', label='Fitted curve')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

在上述代码中,我们定义了一个irls函数,该函数接受输入的x和y数据,以及多项式的次数、迭代次数和epsilon(用于避免除零错误的小值)作为参数。函数内部首先初始化参数theta为全零向量,并将x的幂次方作为特征矩阵X。然后,使用迭代的方式更新参数theta,直到达到指定的迭代次数。在每次迭代中,计算预测值y_pred、残差residuals和权重矩阵weights,并使用加权最小二乘法更新参数theta。最后,返回更新后的参数theta

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值