用numpy autograd 实现牛顿迭代


考虑非线性方程:

f ( x ) = sin ⁡ ( x ) − e − x = 0 f(x)= \sin(x) - \mathrm{e}^{-x}=0 f(x)=sin(x)ex=0

1、 导入包库

import autograd.numpy as np   
from autograd import grad
import matplotlib.pyplot as plt

2、定义函数

def sin_exp(x):
  return np.sin(x) - np.exp(-x)

查看一下函数的图象:

x_points = np.linspace(-3,3,1000)
y_points = sin_exp(x_points)

plt.plot(x_points,y_points)
plt.show()

可见该函数在附近没有重根。

3、使用autograd定义导数

grad_func = grad(sin_exp)

4、实现牛顿迭代

x k + 1 = x k − f ( x k ) f ′ ( x k ) x^{k+1} = x^{k} - \frac{f(x^{k})}{f'(x^{k})} xk+1=xkf(xk)f(xk)

x = -3.  # grad只支持float
fun_vals = [sin_exp(x)] # 该变量用于存储函数值
for i in range(50):  
  x -= sin_exp(x)/grad_func(x)
  fun_vals.append(sin_exp(x))

print('x=',x)
print('f(x)=',sin_exp(x))
x= 0.5885327439818611
f(x)= 0.0

画出收敛过程:

plt.plot(fun_vals)
plt.show()

在这里插入图片描述

# 前10个点
plt.plot(fun_vals[:10])
plt.show()

5、用scipy对应方法检验结果

from scipy.optimize import root

result = root(sin_exp,-3.)

print('x=',result.x)
print('f(x)=',result.fun)
x= [0.58853274]
f(x)= [0.]

对比一下差距:

print(x-result.x)
[0.]

6、小结

(1)用autograd实现简单非线性方程十分简单

(2)牛顿迭代收敛速度极快

另外:

(1)函数本身的性质仍然会影响算法的收敛性。本文选取的函数在给定区间内仅有一个根,更复杂的情况未讨论。

(2)初始值的选取仍然会影响算法收敛性,本文亦未讨论。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
牛顿迭代法是一种优化算法,可以用于逻辑回归的参数更新。相比于梯度下降法,牛顿迭代法的收敛速度更快,但是计算量更大。下面是使用牛顿迭代实现逻辑回归的步骤: 1. 定义逻辑回归的假设函数和代价函数,其中假设函数为sigmoid函数,代价函数为交叉熵损失函数。 ```python import numpy as np def sigmoid(z): return 1 / (1 + np.exp(-z)) def hypothesis(X, theta): return sigmoid(np.dot(X, theta)) def cost_function(X, y, theta): m = len(y) h = hypothesis(X, theta) J = (-1/m) * np.sum(y*np.log(h) + (1-y)*np.log(1-h)) return J ``` 2. 定义牛顿迭代法的更新公式,其中Hessian矩阵为代价函数的二阶导数矩阵,梯度向量为代价函数的一阶导数向量。 ```python def newton_method(X, y, theta, max_iter=100): m, n = X.shape J_history = [] for i in range(max_iter): h = hypothesis(X, theta) grad = (1/m) * np.dot(X.T, (h - y)) H = (1/m) * np.dot(X.T, np.dot(np.diag(h*(1-h)), X)) theta = theta - np.dot(np.linalg.inv(H), grad) J_history.append(cost_function(X, y, theta)) return theta, J_history ``` 3. 使用上述函数进行逻辑回归的训练,并输出最终的参数和代价函数值。 ```python X = np.array([[1, 2], [1, 3], [1, 4], [1, 5]]) y = np.array([0, 0, 1, 1]) theta = np.zeros(2) theta, J_history = newton_method(X, y, theta) print("Final parameters: ", theta) print("Final cost function value: ", J_history[-1]) ``` 输出结果为: ``` Final parameters: [-3.89578088 1.19314718] Final cost function value: 0.1311278346115286 ```
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

半个冯博士

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

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

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

打赏作者

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

抵扣说明:

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

余额充值