fminunc候补在numpy

2024-04-27 20:56:51 发布

您现在位置:Python中文网/ 问答频道 /正文

python中的fminunc函数(来自octave/matlab)是否有替代方法?我有一个二元分类器的代价函数。现在我想通过梯度下降得到θ的最小值。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或任何其他梯度下降算法实现。


Tags: the方法函数numpy分类器options梯度set
3条回答

我还试图实现logistic回归,正如Coursera ML课程中所讨论的,但在python中。我发现希比很有帮助。在尝试了最小化函数的不同算法实现之后,我发现牛顿共轭梯度是最有用的。在检查了它的返回值之后,它似乎与八度音阶中的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;

这里有更多关于感兴趣函数的信息:http://docs.scipy.org/doc/scipy-0.10.0/reference/tutorial/optimize.html

而且,看起来您正在学习Coursera机器学习课程,但使用的是Python。你可以去看看http://aimotion.blogspot.com/2011/11/machine-learning-with-python-logistic.html;这家伙也在做同样的事情。

看来你得换成scipy

在那里你可以找到所有基本的优化算法。

http://docs.scipy.org/doc/scipy/reference/optimize.html

相关问题 更多 >