2014-09-17 3 views
0

coursera의 Ng 's machihne 학습 수업에서 this dataset에 대한 로지스틱 회귀를 시도하고 있습니다.로지스틱 회귀 : 객체가 정렬되지 않았습니다.

우리는 매개 변수 theta를 찾기 위해 최소화해야하는 비용 함수가 있다는 아이디어입니다.

import numpy as np 
from scipy.optimize import fmin_bfgs 

data = np.loadtxt('ex2data1.txt',delimiter=",") 
m,n = data.shape 
X = np.array(np.column_stack((np.ones(m),data[:,:-1]))) 
y = np.array(data[:,2].reshape(m,1)) 
theta = np.array(np.zeros(n).reshape(n,1)) 

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

def hypothesis(X,theta): 
    return sigmoid(X.dot(theta)) 

def cost(theta): 
    print theta.shape 
    h = hypothesis(X,theta) 
    cost = (-y.T.dot(np.log(h))-(1-y).T.dot(np.log(1-h)))/m 
    return cost 

def gradient(theta): 
    h = hypothesis(X,theta) 
    grad = ((h-y).T.dot(X)).T/m 
    return grad.flatten() 

def fmin(): 
    initial_theta=np.zeros(n).reshape(n,1) 
    theta=fmin_bfgs(cost,initial_theta,fprime=gradient) 
    return theta 

인쇄 FMIN()

내가 ValueError: Objects are not aligned 무엇입니까하지만 난 모든 개체의 모양을 확인하고 여전히 그것을 알아낼 수 없습니다. 여기에 역 추적입니다 :

---> 32  theta=fmin_bfgs(cost,initial_theta,fprime=gradient) 
    33 

/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.pyc in fmin_bfgs(f, x0, fprime, args, gtol, norm, epsilon, maxiter, full_output, disp, retall, callback) 
    775    'return_all': retall} 
    776 
--> 777  res = _minimize_bfgs(f, x0, args, fprime, callback=callback, **opts) 
    778 
    779  if full_output: 

/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.pyc in _minimize_bfgs(fun, x0, args, jac, callback, gtol, norm, eps, maxiter, disp, return_all, **unknown_options) 
    844  gnorm = vecnorm(gfk, ord=norm) 
    845  while (gnorm > gtol) and (k < maxiter): 
--> 846   pk = -numpy.dot(Hk, gfk) 
    847   try: 
    848    alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ 

ValueError: objects are not aligned 

답변

3

내가 코드를 수정, 그것은이 c=inf와 sklearn에 로지스틱 회귀와 같은 결과를 얻을 수 있습니다

import numpy as np 
from scipy.optimize import fmin_bfgs 
import io 
data = np.loadtxt('ex2data1.txt',delimiter=",") 
m,n = data.shape 
X = np.array(np.column_stack((np.ones(m),data[:,:-1]))) 
y = np.array(data[:,2].reshape(m,1)) 
theta = np.array(np.zeros(n).reshape(n,1)) 

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

def hypothesis(X,theta): 
    return sigmoid(X.dot(theta)) 

def cost(theta): 
    h = hypothesis(X,theta) 
    cost = (-y.T.dot(np.log(h))-(1-y).T.dot(np.log(1-h)))/m 
    r = cost[0] 
    if np.isnan(r): 
     return np.inf 
    return r 

def gradient(theta): 
    theta = theta.reshape(-1, 1) 
    h = hypothesis(X,theta) 
    grad = ((h-y).T.dot(X)).T/m 
    return grad.flatten() 

def fmin(): 
    initial_theta=np.zeros(n) 
    theta=fmin_bfgs(cost,initial_theta,fprime=gradient) 
    return theta 

theta = fmin() 
+0

감사합니다. 그 비용은 나노가 될 수 있습니다. 그러나 재구성 (-1,1)은 무엇을 의미합니까? 문서에서는 "하나의 도형 차원이 -1 일 수 있습니다.이 경우 값은 배열 길이와 나머지 차원에서 유추됩니다." 나는 그것을 얻지 않는다. – yayu