Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用Scipy实现逻辑回归:为什么Scipy优化返回全零?_Python_Optimization_Machine Learning_Scipy_Numerical Methods - Fatal编程技术网

Python 使用Scipy实现逻辑回归:为什么Scipy优化返回全零?

Python 使用Scipy实现逻辑回归:为什么Scipy优化返回全零?,python,optimization,machine-learning,scipy,numerical-methods,Python,Optimization,Machine Learning,Scipy,Numerical Methods,我正在尝试实现一对多逻辑回归,正如Andrew Ng的一样,他在实现中使用了一个名为fmincg的倍频程函数。我曾尝试在中使用多个函数,但无论输入什么,我都会在分类器输出中得到所有的零 在过去的几个小时里,我结帐了大量的资源,但最有用的是,和 是否有任何明显或不太明显的地方使我的实现误入歧途 import scipy.optimize as op def sigmoid(z): """takes matrix and returns result of passing through

我正在尝试实现一对多逻辑回归,正如Andrew Ng的一样,他在实现中使用了一个名为
fmincg
的倍频程函数。我曾尝试在中使用多个函数,但无论输入什么,我都会在分类器输出中得到所有的零

在过去的几个小时里,我结帐了大量的资源,但最有用的是,和

是否有任何明显或不太明显的地方使我的实现误入歧途

import scipy.optimize as op

def sigmoid(z):
    """takes matrix and returns result of passing through sigmoid function"""
    return 1.0 / (1.0 + np.exp(-z))

def lrCostFunction(theta, X, y, lam=0):
    """
    evaluates logistic regression cost function:

    theta: coefficients. (n x 1 array)
    X: data matrix (m x n array)
    y: ground truth matrix (m x 1 array)
    lam: regularization constant
    """
    m = len(y)
    theta = theta.reshape((-1,1))
    theta = np.nan_to_num(theta)

    hypothesis = sigmoid(np.dot(X, theta))
    term1 = np.dot(-y.T,np.log(hypothesis))
    term2 = np.dot(1-y.T,np.log(1-hypothesis))
    J = (1/m) * term1 - term2
    J = J + (lam/(2*m))*np.sum(theta[1:]**2)
    return J

def Gradient(theta, X, y, lam=0):
    m = len(y)
    theta = theta.reshape((-1,1))
    hypothesis = sigmoid(np.dot(X, theta))
    residuals = hypothesis - y 
    reg = theta  
    reg[0,:] = 0
    reg[1:,:] = (lam/m)*theta[1:]
    grad = (1.0/m)*np.dot(X.T,residuals)
    grad = grad + reg
    return grad.flatten()

def trainOneVersusAll(X, y, labels, lam=0):
    """
    trains one vs all logistic regression.

    inputs:
        - X and Y should ndarrays with a row for each item in the training set
        - labels is a list of labels to generate probabilities for.
        - lam is a regularization constant

    outputs:
        - "all_theta", shape = (len(labels), n + 1) 
    """
    y = y.reshape((len(y), 1))
    m, n = np.shape(X)
    X = np.hstack((np.ones((m, 1)), X))
    all_theta = np.zeros((len(labels), n + 1))
    for i,c in enumerate(labels):
        initial_theta = np.zeros(n+1)
        result, _, _ = op.fmin_tnc(func=lrCostFunction, 
                            fprime=Gradient,
                            x0=initial_theta, 
                            args=(X, y==c, lam))
        print result
        all_theta[i,:] = result
    return all_theta


def predictOneVsAll(all_theta, X):
    pass

a = np.array([[ 5.,  5.,  6.],[ 6.,  0.,  8.],[ 1.,  1.,  1.], [ 6.,  1.,  9.]])
k = np.array([1,1,0,0])
# a = np.array([[1,0,1],[0,1,0]])
# k = np.array([0,1])
solution = np.linalg.lstsq(a,k)
print 'x', solution[0]
print 'resid', solution[1]
thetas = trainOneVersusAll(a, k, np.unique(k))

问题在于你的
梯度
函数。在
numpy
中,赋值为不复制对象,因此您的行

reg = theta
reg
作为对
theta
的引用,因此每次计算梯度时,实际上都会修改当前的解决方案。应该是

reg = theta.copy()
我还建议从随机权重开始

initial_theta = np.random.randn(n+1)

现在的解决方案不再是零(虽然我并没有检查每个公式,所以仍然可能有数学错误)。还值得注意的是,对于线性可分问题,没有正则化的逻辑回归是不适定的(其目标是无界的),因此我建议使用
lam>0

进行测试。您是否尝试从随机向量而不是np.0开始优化?不,我没有尝试过……好的。我试过了。运气不好…您的代码显示您正在使用
fmin\u tnc
。它有三个返回值,但忽略其中两个。如果您要调试这个问题,您当然应该检查所有的返回值,尤其是第三个,即返回代码。请参阅docstring以了解其解释:第三个变量返回2s