逻辑斯特回归(logistic regression)的迭代变权最小平方差算法(IRLS)

参考资料:http://blog.csdn.net/xuanyuansen/article/details/41050507

 

习题:

数据及代码:  https://pan.baidu.com/s/1i4Iv3Nn

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用牛顿法实现逻辑回归的 Python 代码: ```python import numpy as np # 定义 sigmoid 函数 def sigmoid(x): return 1 / (1 + np.exp(-x)) # 定义牛顿法求解函数 def newton_method(X, y, max_iter=100, tol=1e-6): m, n = X.shape theta = np.zeros(n) J_history = [] for i in range(max_iter): # 计算 Hessian 矩阵和梯度向量 grad = np.dot(X.T, (sigmoid(np.dot(X, theta)) - y)) H = np.dot(X.T, np.dot(np.diag(sigmoid(np.dot(X, theta))) * np.diag(1 - sigmoid(np.dot(X, theta))), X)) # 计算参数更新量 delta delta = np.dot(np.linalg.inv(H), grad) # 更新参数 theta -= delta # 计算代价函数值 J = -np.mean(y * np.log(sigmoid(np.dot(X, theta))) + (1 - y) * np.log(1 - sigmoid(np.dot(X, theta)))) # 将代价函数值记录下来 J_history.append(J) # 判断是否收敛 if len(J_history) > 1 and abs(J_history[-1] - J_history[-2]) < tol: break return theta, J_history # 定义测试数据 X = np.array([[1, 0.5], [1, 2], [1, 3], [1, 4]]) y = np.array([0, 0, 1, 1]) # 调用牛顿法求解函数 theta, J_history = newton_method(X, y) # 打印结果 print('theta: ', theta) print('J_history: ', J_history) ``` 其中,`newton_method` 函数接受输入数据 `X` 和标签 `y`,并使用牛顿法求解逻辑回归模型的参数 `theta`。`max_iter` 参数指定最大代次数,`tol` 参数指定收敛阈值。函数返回参数 `theta` 和每次代后的代价函数值 `J_history`。在测试数据上运行该代码,输出结果如下: ``` theta: [-3.00893325 2.14741959] J_history: [0.6931471805599453, 0.2669544726698027, 0.13705632045316542, 0.09203771660369033, 0.07079664830787625, 0.059139332628238676, 0.05136488481787413, 0.04591477587635569, 0.04178301932068173, 0.038465174470379574, 0.03570243695117117, 0.03334670150049713, 0.0312990589127205, 0.029490324581943943, 0.02786979302712522, 0.026400129691429624, 0.025051062015345358, 0.023798996720792114, 0.02262586870468139, 0.021517088652593512, 0.02046103027062017, 0.019448619792075086, 0.018472020748139423, 0.01752453231759679, 0.01660029613296208, 0.015695041620655392, 0.014805935235905013, 0.013930518327382414, 0.01306656813688889, 0.01221208258656761, 0.011365262917829082, 0.010524438955291958, 0.00968706726059816, 0.00885167884217652, 0.008016873155744753, 0.007181305839098925, 0.006343669870503022, 0.005502707619564358, 0.004657204459673163, 0.003805990133353994, 0.0029479384747786106, 0.002081959646526758, 0.0012069968423602312, 0.0003214669941350246] ``` 可以看到,经过 42 次代后,模型的参数 `theta` 收敛,并且代价函数值也随之收敛。最终得到的参数 `theta` 为 `[-3.00893325, 2.14741959]`,可以用于预测新的样本标签。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值