python - scipy.optimize.fmin_cg 函数需要两个可调用函数 f 和 fprime,如何从返回两个值的函数中提取两个函数?
问题描述
def linear_regression(theta, X, y, lamb):
# X(12,1+1) theta(2,1) y(12,1)
m = X.shape[0]
ones = np.ones([m, 1])
X = np.hstack([ones, X])
h = X.dot(theta)
# cost function
J = 1 / 2 / m * np.sum(np.power(h - y, 2)) + lamb / 2 / m * np.sum(np.power(theta[1:], 2))
# gradient X(12,2) X.T(2,12) (h-y)(12,1) sum_error(2,1)\
sum_error = 1 / m * X.T.dot(h - y)
temp = theta
temp[0] = 0
gradient = sum_error + lamb / m * temp
return J, gradient
def f(theta, X, y, lamb):
J, gradient = linear_regression(theta, X, y, lamb)
return J
def fprime(theta, X, y, lamb):
J, gradient = linear_regression(theta, X, y, lamb)
return gradient
J, gradient = linear_regression(theta,X,y,1)
# theta need to be a vector not matrix
result = opt.fmin_cg(f, theta, fprime=fprime, args=(X,y,1))
print(result[0])
解释:
- opt.fmin_cg(f, theta, fprime=fprime, args=(X,y,1)) 需要一个可调用函数 f 和 fprime
- f, fprime 是linear_regression(theta, X, y, lamb)的返回值
- 在同一个函数中计算成本函数和梯度很容易
问题:
- 有没有一种简单的方法可以从 linear_regression(theta, X, y, lamb) 中提取两个可调用函数
- 调用 J, gradient = linear_regression(theta,X,y,1) 并传递给 opt.fmin_cg(J, theta, fprime=gradient , args=(X,y,1)) 不起作用
解决方案
推荐阅读
- azure - 输入参数“范围”无效。范围 https://outlook.office365.com/EWS.AccessAsUser.All 无效
- typescript - 如何在不使用 ng-Class 或 ng-Style 的角度 7 的点击事件中添加 CSS 类?
- c++ - 线程更新时对全局指针的影响
- javascript - 在 InsertCSS 的内容脚本中使用 tabID 的 Chrome 扩展
- python - 熊猫减去行给出错误的结果
- r - 如何获得“snippet::shinyapp”对象的帮助?
- android - 所需的生命周期所有者找到了活动
- c# - 当文档被添加/更新到搜索索引时,是否有任何默认时间戳得到更新?
- r - 如何在条形图中将 x 轴标签旋转 xx° 度
- php - Laravel Eloquent 查询范围和使用 DB::raw 的连接