【问题标题】:python scipy using fmin_bfgs for logistic regressionpython scipy 使用 fmin_bfgs 进行逻辑回归
【发布时间】:2012-08-20 13:05:27
【问题描述】:

我使用下面的公式作为我的假设:

下面的公式作为代价函数:

所以我尝试最小化的对象函数是:

渐变是:

csv 文件的格式如下: y0,x1,x2,x3,... y1,x1,x2,x3,... y2,x1,x2,x3,... y 为 1 或 0(用于分类) 训练代码如下:

import numpy as np
import scipy as sp
from scipy.optimize import fmin_bfgs
import pylab as pl



data = np.genfromtxt('../data/small_train.txt', delimiter=',')
y = data[:,0]
#add 1 as the first column of x, the constant term
x = np.append(np.ones((len(y), 1)), data[:,1:], axis = 1)

#sigmoid hypothesis
def h(theta, x):
    return 1.0/(1+np.exp(-np.dot(theta, x)))

#cost function
def cost(theta, x, y):
    tot = 0
    for i in range(len(y)):
        tot += y[i]*np.log(h(theta, x[i])) + (1-y[i])*(1-np.log(h(theta, x[i])))
    return -tot / len(y)

#gradient

def deviation(theta, x, y):
    def f(theta, x, y, j):
        tot = 0.0
        for i in range(len(y)):
            tot += (h(theta, x[i]) - y[i]) * x[i][j]
        return tot / len(y)
    ret = []
    for j in range(len(x[0])):
        ret.append(f(theta, x, y, j))
    return np.array(ret)
    

init_theta = np.zeros(len(x[0]))
ret = fmin_bfgs(cost, init_theta, fprime = deviation, args=(x,y))
print ret

我在一个小数据集上运行代码,但似乎我的实现不正确。有人可以帮助我吗? 还有一个问题:如您所知,fmin_bfgs 不一定需要 fprime 项,我们提供和不提供有什么区别?

【问题讨论】:

  • 据我所知,提供函数的导数只会提高速度。如果您不提供分析表格,则会即时生成数字表格。 scikits.learn 有一个逻辑回归函数,你可以试一试。

标签: python scipy regression logistics


【解决方案1】:

我想更正上面代码中的一些问题。

我认为代价函数应该如下(修正为粗体):

#cost function
def cost(theta, x, y):
    tot = 0
    for i in range(len(y)):
        tot += y[i]*np.log(h(theta, x[i])) + (1-y[i])*(**np.log(1-h(theta, x[i]**)))
    return -tot / len(y)

如果这样更好,请告诉我,非常感谢!

【讨论】:

    猜你喜欢
    • 2015-01-31
    • 2015-08-05
    • 1970-01-01
    • 2012-11-27
    • 2020-09-27
    • 2015-12-19
    • 2015-02-21
    • 2018-08-11
    • 2018-01-14
    相关资源
    最近更新 更多