python - 在正则化数据上使用 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
。
解决方案
当您尝试执行 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()
然后,您可以使用函数检查您的渐变是否正确。
推荐阅读
- file - 在目录中查找重复文件
- excel - 使用 VBA 查找和替换连续单元格中的值
- c - 在 FINTEK F81866A 芯片组上编程 GPIO 引脚
- hadoop - Hadoop权威指南的面向列的格式章节中的序列顺序?
- ruby - 自定义 Ruby on rails 验证错误
- kubernetes - Unabel 使用 openstack-helm 图表在 kubernetes 上部署 mariadb
- javascript - Marvel API 和 Insomnia(或 Postman):如何传递所需的哈希值?
- node.js - 你如何使用 distinct 和 mockingoose?
- python - 检查我的观点是否在我的屏幕的一部分
- c++ - 如何使用 break 停止循环?