使用python进行逻辑回归

时间:2013-12-02 12:52:01

标签: python statistics machine-learning logistic-regression

我想在python中从头开始实现Logisitic回归。以下是其中的功能:

  1. 乙状结肠
  2. 费用
  3. fminunc
  4. 评估逻辑回归
  5. 我想知道,在python中从头开始是一个很好的开始。关于如何以及什么是好的指导。我知道这些功能的理论,但寻找更好的pythonic答案。

    我使用了八度音,但我没有把它弄好但是不知道如何在python中启动,因为OCtave已经将这些软件包设置为完成工作。

2 个答案:

答案 0 :(得分:2)

你可能想尝试将你的八度代码翻译成python并看看发生了什么。您也可以使用python包为您执行此操作。查看有关逻辑回归的scikit-learn。这个blog还有一个简单的例子。

答案 1 :(得分:1)

为了实现Logistic回归,您可以考虑以下两种方法:

  1. 考虑线性回归的工作原理。将Sigmoid函数应用于线性回归的假设并运行梯度下降直到收敛。或应用基于指数的Softmax函数以排除较低的发生可能性。

    def logistic_regression(x, y,alpha=0.05,lamda=0):
        '''
        Logistic regression for datasets
        '''
        m,n=np.shape(x)
        theta=np.ones(n)
        xTrans = x.transpose()
        oldcost=0.0
        value=True
        while(value):
            hypothesis = np.dot(x, theta)
            logistic=hypothesis/(np.exp(-hypothesis)+1)
            reg = (lamda/2*m)*np.sum(np.power(theta,2))
            loss = logistic - y
            cost = np.sum(loss ** 2)
            #print(cost)
            # avg cost per example (the 2 in 2*m doesn't really matter here.
            # But to be consistent with the gradient, I include it)
            # avg gradient per example
            gradient = np.dot(xTrans, loss)/m
            # update
            if(reg):
                cost=cost+reg
                theta = (theta - (alpha) * (gradient+reg))
            else:
                theta=theta -(alpha/m) * gradient
            if(oldcost==cost):
                value=False
            else:
                oldcost=cost
        print(accuracy(theta,m,y,x))
        return theta,accuracy(theta,m,y,x)