python - 使用 Hessian 矩阵的梯度下降牛顿法

标签 python optimization machine-learning gradient-descent newtons-method

我正在使用牛顿法实现回归的梯度下降,如《机器学习概率视角》(Murphy)一书中的 8.3 部分所述。我在此实现中使用二维数据。我正在使用以下符号。
x = 输入数据点 m*2
y = 对应于输入数据的标记输出(m)
H = Hessian 矩阵定义为

梯度下降更新

其中损失函数定义为

就我而言 数组,H 为

这是我的 python 实现。然而,这不起作用,因为每次迭代的成本都在增加。

def loss(x,y,theta):
   m,n = np.shape(x)
   cost_list = []
   for i in xrange(0,n): 
     x_0 = x[:,i].reshape((m,1)) 
     predicted = np.dot(x_0, theta[i])    
     error = predicted - y
     cost = np.sum(error ** 2) /  m
     cost_list.append(cost)

   cost_list = np.array(cost_list).reshape((2,1))
   return cost_list


def NewtonMethod(x,y,theta,maxIterations):
   m,n = np.shape(x)
   xTrans  = x.transpose()
   H       = 2 * np.dot(xTrans,x) / m
   Hinv    = np.linalg.inv(H)
   thetaPrev = np.zeros_like(theta)
   best_iter = maxIterations
   for i in range(0,maxIterations):
     cost = loss(x,y,theta)
     theta  = theta - np.dot(Hinv,cost))
     if(np.allclose(theta,thetaPrev,rtol=0.001,atol=0.001)):
        break;
     else:
       thetaPrev = theta
       best_iter = i

   return theta

这是我使用的示例值

import numpy as np

x = np.array([[-1.7, -1.5],[-1.0 , -0.3],[ 1.7 ,  1.5],[-1.2, -0.7 ][  0.6,  0.1]])  
y = np.array([ 0.3 ,  0.07, -0.2,  0.07,  0.03 ])
theta = np.zeros(2)
NewtonMethod(x,y,theta,100)

需要帮助/建议来解决此问题。
谢谢

最佳答案

您有效地使用了步长 1。尝试减小步长,看看是否有帮助。也就是说,而不是

enter image description here

这样做:

enter image description here

值小于 1。

关于python - 使用 Hessian 矩阵的梯度下降牛顿法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36354215/

相关文章:

python - 在 Python 中查找丢失的封面艺术

haskell - GHC 优化

javascript - 优化jquery代码

r - R 中的多项式朴素贝叶斯分类器

matlab - 离散连续数据的分箱技术

machine-learning - 为什么要使用 CH 和 SIL 来查找 Elbow(或使用 L 方法)来选择簇数量?

Python Telethon get_messages 偏移量

python - 如何有效地循环此数据帧并使用内置的 numpy 或 pandas 执行函数?

python - 如何使用 pymongo 对 mongodb 进行排序

php - 运行 100 多个 MySQL 更新查询。优化提示请:)