首页 > 解决方案 > 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])

解释:

  1. opt.fmin_cg(f, theta, fprime=fprime, args=(X,y,1)) 需要一个可调用函数 f 和 fprime
  2. f, fprime 是linear_regression(theta, X, y, lamb)的返回值
  3. 在同一个函数中计算成本函数和梯度很容易

问题:

  1. 有没有一种简单的方法可以从 linear_regression(theta, X, y, lamb) 中提取两个可调用函数
  2. 调用 J, gradient = linear_regression(theta,X,y,1) 并传递给 opt.fmin_cg(J, theta, fprime=gradient , args=(X,y,1)) 不起作用

标签: pythonmachine-learning

解决方案


推荐阅读