首页 > 解决方案 > 在正则化数据上使用 SciPy fmin_bfgs() 发出警告

问题描述

我正在使用下一个正cost()gradient()化函数:

def cost(theta, x, y, lam):
    theta = theta.reshape(1, len(theta))
    predictions = sigmoid(np.dot(x, np.transpose(theta))).reshape(len(x), 1)

    regularization = (lam / (len(x) * 2)) * np.sum(np.square(np.delete(theta, 0, 1)))

    complete = -1 * np.dot(np.transpose(y), np.log(predictions)) \
           - np.dot(np.transpose(1 - y), np.log(1 - predictions))
    return np.sum(complete) / len(x) + regularization


def gradient(theta, x, y, lam):
    theta = theta.reshape(1, len(theta))
    predictions = sigmoid(np.dot(x, np.transpose(theta))).reshape(len(x), 1)

    theta_without_intercept = theta.copy()
    theta_without_intercept[0, 0] = 0
    assert(theta_without_intercept.shape == theta.shape)
    regularization = (lam / len(x)) * np.sum(theta_without_intercept)

    return np.sum(np.multiply((predictions - y), x), 0) / len(x) + regularization

有了这些功能,scipy.optimize.fmin_bfgs()我得到了下一个输出(这几乎是正确的):

Starting loss value: 0.69314718056 
Warning: Desired error not necessarily achieved due to precision loss.
         Current function value: 0.208444
         Iterations: 8
         Function evaluations: 51
         Gradient evaluations: 39
7.53668131651e-08
Trained loss value: 0.208443907192 

下面的正则化公式。如果我评论上面的正则化输入scipy.optimize.fmin_bfgs()效果很好,并正确返回局部最优值。

任何想法为什么?

在此处输入图像描述

更新:

在附加评论之后,我更新了成本和梯度正则化(在上面的代码中)。但是这个警告仍然出现(上面的新输出)。scipy check_grad函数返回下一个值:7.53668131651e-08。

更新 2:

我正在使用设置UCI 机器学习 Iris数据。并基于分类模型One-vs-All训练的第一个结果Iris-setosa

标签: pythonmachine-learningscipy

解决方案


当您尝试执行 L2 正则化时,您应该修改成本函数中的值

regularization = (lam / len(x) * 2) * np.sum(np.square(np.delete(theta, 0, 1)))

regularization = (lam / (len(x) * 2)) * np.sum(np.square(np.delete(theta, 0, 1)))

此外,正则化的梯度部分应该与参数向量具有相同的形状theta。因此,我宁愿认为正确的值是

theta_without_intercept = theta.copy()
theta_without_intercept[0] = 0 #  You are not penalizing the intercept in your cost function, i.e. theta_0
assert(theta_without_intercept.shape == theta.shape)
regularization = (lam / len(x)) * theta_without_intercept

否则,渐变将不正确。scipy.optimize.check_grad()然后,您可以使用函数检查您的渐变是否正确。


推荐阅读