fminunc 在 numpy 中交替

新手上路,请多包涵

是否有替代 fminunc python 中的函数(来自八度/matlab)?我有一个二元分类器的成本函数。现在我想运行梯度下降以获得 theta 的最小值。 octave/matlab 实现将如下所示。

 %  Set options for fminunc
options = optimset('GradObj', 'on', 'MaxIter', 400);

%  Run fminunc to obtain the optimal theta
%  This function will return theta and the cost
[theta, cost] = ...
    fminunc(@(t)(costFunction(t, X, y)), initial_theta, options);

我已经使用 numpy 库在 python 中转换了我的 costFunction,并在 numpy 中寻找 fminunc 或任何其他梯度下降算法实现。

原文由 Anurag Sharma 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 492
2 个回答

我还尝试按照 Coursera ML 课程中讨论的那样实施逻辑回归,但是是在 python 中。我发现 scipy 很有帮助。在最小化函数中尝试了不同的算法实现后,我发现牛顿共轭梯度最有帮助。另外查看它的返回值,好像和Octave中的fminunc是等价的。我在下面的 python 中包含了我的实现,以找到最佳的 theta。

 import numpy as np
import scipy.optimize as op

def Sigmoid(z):
    return 1/(1 + np.exp(-z));

def Gradient(theta,x,y):
    m , n = x.shape
    theta = theta.reshape((n,1));
    y = y.reshape((m,1))
    sigmoid_x_theta = Sigmoid(x.dot(theta));
    grad = ((x.T).dot(sigmoid_x_theta-y))/m;
    return grad.flatten();

def CostFunc(theta,x,y):
    m,n = x.shape;
    theta = theta.reshape((n,1));
    y = y.reshape((m,1));
    term1 = np.log(Sigmoid(x.dot(theta)));
    term2 = np.log(1-Sigmoid(x.dot(theta)));
    term1 = term1.reshape((m,1))
    term2 = term2.reshape((m,1))
    term = y * term1 + (1 - y) * term2;
    J = -((np.sum(term))/m);
    return J;

# intialize X and y
X = np.array([[1,2,3],[1,3,4]]);
y = np.array([[1],[0]]);

m , n = X.shape;
initial_theta = np.zeros(n);
Result = op.minimize(fun = CostFunc,
                                 x0 = initial_theta,
                                 args = (X, y),
                                 method = 'TNC',
                                 jac = Gradient);
optimal_theta = Result.x;

原文由 chammu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题