import numpy as np def sigmoid(z): return 1 / (1 + np.exp(-z)) def cost_function(theta, X, y): m = len(y) h = sigmoid(X @ theta) J = -(1/m) * (y.T @ np.log(h) + (1-y).T @ np.log(1-h)) grad = (1/m) * X.T @ (h - y) return J, grad def trust_region_newton_method(X, y, max_iter=100, eta=0.05, delta=0.1): n = X.shape[1] theta = np.zeros((n,1)) J, grad = cost_function(theta, X, y) H = np.eye(n) for i in range(max_iter): # solve trust region subproblem p = np.linalg.solve(H, -grad) if np.linalg.norm(p) <= delta: d = p else: d = delta * p / np.linalg.norm(p) # compute actual reduction and predicted reduction J_new, grad_new = cost_function(theta+d, X, y) actual_reduction = J - J_new predicted_reduction = -grad.T @ d - 0.5 * d.T @ H @ d # update trust region radius rho = actual_reduction / predicted_reduction if rho < 0.25: delta *= 0.25 elif rho > 0.75 and np.abs(np.linalg.norm(d) - delta) < 1e-8: delta = min(2*delta, eta*np.linalg.norm(theta)) # update parameters if rho > 0: theta += d J, grad = J_new, grad_new H += (grad_new - grad) @ (grad_new - grad).T / ((grad_new - grad).T @ d) # check convergence if np.linalg.norm(grad) < 1e-5: break return theta ——修正算法,实现信赖域算法求解逻辑回归问题
时间: 2024-02-14 08:19:21 浏览: 92
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
这段代码实现了使用信赖域算法求解逻辑回归问题。具体来说,它定义了一个sigmoid函数和一个代价函数cost_function,这两个函数分别用于计算sigmoid函数和逻辑回归的代价函数以及其梯度。接着,它定义了一个trust_region_newton_method函数,用于实现信赖域牛顿法求解逻辑回归问题。在这个函数中,首先初始化参数theta和海森矩阵H,然后在每次迭代中,先通过求解信赖域子问题得到步长d,然后计算实际代价函数的减少量和预测代价函数的减少量,并根据这两个量的比值rho来更新信赖域半径delta。接着,根据rho的值来更新参数theta和海森矩阵H,并在满足终止条件时退出迭代。整个算法的目标是最小化逻辑回归的代价函数,以得到最优的参数theta。
阅读全文