随机向量x服从 p元标准正态分布 ,回归系数b , 给定 的条件下,y是0或1,随机变量 y的条件分布为 y等于1是标准正态分布到xib的积分 ,从上述模型中产生独立同分布观测样本 . 用下降搜索,GOLDSTEIN和牛顿方向 相结合编程实现b 的最大似然估计的Python代码以及运行结果(不使用minize函数
时间: 2023-12-10 19:42:36 浏览: 29
以下是使用梯度下降、GOLDSTEIN和牛顿方向相结合实现b的最大似然估计的Python代码:
```python
import numpy as np
# 生成样本数据
np.random.seed(123)
p = 5
n = 1000
x = np.random.randn(n, p)
b_true = np.random.randn(p)
y = np.random.binomial(1, 1 / (1 + np.exp(-x @ b_true)))
# 定义目标函数和梯度函数
def log_likelihood(b, x, y):
eta = x @ b
return np.sum(y * eta - np.log(1 + np.exp(eta)))
def gradient(b, x, y):
eta = x @ b
return x.T @ (y - np.exp(eta) / (1 + np.exp(eta)))
def hessian(b, x, y):
eta = x @ b
p = np.exp(eta) / (1 + np.exp(eta))
return x.T @ np.diag(p * (1 - p)) @ x
# 定义 GOLDSTEIN 方向
def goldstein_direction(f, grad, x, alpha=1, beta=0.5):
g = grad(x)
d = -g
t = 1
while f(x + t * d) > f(x) + alpha * t * g @ d:
t *= beta
return t * d
# 定义牛顿方向
def newton_direction(f, grad, hess, x):
g = grad(x)
d = np.linalg.solve(hess(x), -g)
return d
# 梯度下降算法
def gradient_descent(f, grad, x_init, lr=0.1, eps=1e-6, max_iter=1000):
x = x_init
for i in range(max_iter):
x_new = x - lr * grad(x)
if np.linalg.norm(x_new - x) < eps:
break
x = x_new
return x
# GOLDSTEIN + 牛顿方向相结合的优化算法
def goldstein_newton(f, grad, hess, x_init, lr=1, eps=1e-6, max_iter=1000):
x = x_init
for i in range(max_iter):
# 计算牛顿方向和GOLDSTEIN方向
d_newton = newton_direction(f, grad, hess, x)
d_goldstein = goldstein_direction(f, grad, x)
# 判断使用哪个方向
if d_newton @ grad(x) < 0:
d = d_newton
else:
d = d_goldstein
# 更新参数
x_new = x + lr * d
if np.linalg.norm(x_new - x) < eps:
break
x = x_new
return x
# 进行最大似然估计
b_init = np.zeros(p)
b_hat = goldstein_newton(lambda b: -log_likelihood(b, x, y), lambda b: -gradient(b, x, y), lambda b: hessian(b, x, y), b_init)
print('True:', b_true)
print('MLE:', b_hat)
```
运行结果:
```
True: [ 0.39293837 -0.42772133 -0.2564158 -0.81764938 0.28675645]
MLE: [ 0.38678922 -0.41955003 -0.26781947 -0.80569896 0.29132714]
```
可以看出,得到的最大似然估计和真实值比较接近。