import numpy as np
def sigmoid(x):
return 1.0/(1+np.asmatrix(np.exp(-x)))
def graD(X,y,alpha,s0,numda):
m=np.size(X,0)
n=np.size(X,1)
X0=X[:,0]
X1=X[:,1:]
theta=np.asmatrix(np.zeros(np.size(X,1))).T
s=100
lit=0
while abs(s)>s0 and lit<=10000:
theta0=theta[0]
theta1=theta[1:]
theta0-=(float(alpha)/m)*X0.T*(sigmoid(X*theta)-y)
theta1-=float(alpha)*((1.0/m)*X1.T*(sigmoid(X*theta)- y)+float(numda)/m*theta1)
theta=np.vstack((np.asmatrix(theta0),np.asmatrix(theta1)))
lit+=1
s=sum((float(1.0)/m)*X.T*(sigmoid(X*theta)-y))/float(n)
return theta
这是一个使用简单sigmoid函数1 /(1 + e ^( - t))的逻辑回归,我无法弄清楚主要是函数&#39; graD&#39;做正则梯度下降的部分,结果不正确,如下:
lg(X,y,0.01,0.1,30)
Out[137]:
matrix([[1000.10539375],
[ 49.33333333]])
我输入的数据是: (对于X): 1 2 3 4 五 6 7 8 9 10 11 12 13 14 15 (对于y): 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
答案 0 :(得分:1)
您的代码中存在一些错误。
计算新的theta值时,需要使用同步更新。在您更改theta0的情况下,您更改theta,然后在theta1计算中使用。这是错误的。您可能需要使用两个临时变量(或使用矢量化解决方案)。
成本函数也不正确。它应该由两部分组成:
y*log(h)
和(1-y)*log(1-h)
。
据我所知,成本函数不能为负数,因此您不需要计算它的绝对值。
正规化对我来说也是错误的。
这是我的代码,它对我有用。
import numpy as np
from numpy import *
import matplotlib.pyplot as plt
def sigmoid(x):
return 1.0/(1+np.asmatrix(np.exp(-x)))
def graD(X,y,alpha,s0,numda):
m=np.size(X,0)
X0=X[:,0]
X1=X[:,1:]
theta=np.asmatrix(np.zeros(np.size(X,1))).T
s=100
lit=0
s_history = []
while s>s0 and lit<=10000:
theta0=theta[0]
theta1=theta[1:]
sig = sigmoid(X*theta)
theta0_temp = theta0 - (float(alpha)/m)*X0.T*(sig-y)
theta1_temp = theta1 - (float(alpha)/m)*X1.T*(sig-y)
theta=np.vstack((np.asmatrix(theta0_temp),np.asmatrix(theta1_temp)))
lit+=1
# calculating the cost function
part1 = np.multiply(y, np.log(sig))
part2 = np.multiply((1 - y), np.log(1 - sig))
s = (-part1 - part2).sum()/m
s_history.append(s)
plt.plot(s_history)
plt.title("Cost function")
plt.grid()
plt.show()
print theta
print (-theta[0]/theta[1])
return theta
# Main module
_f = loadtxt('data/ex2data2_n_1.txt', delimiter=',')
_X, _y = _f[:,[0]], _f[:,[1]]
_m = np.shape(_X)[0]
# add a column of 1
_X = np.hstack((np.matrix(np.ones((_m, 1))),_X))
_y = np.matrix(_y)
_alpha = 0.01
_n= np.shape(_X)[1]
_w = np.matrix(np.zeros((_n, 1)))
graD(_X, _y, _alpha, 0.1, 0.1)
输出:
theta =
[[-5.51133636]
[ 0.77301063]]
-theta0/theta1 =
[[ 7.12970317]] #this number is the decision boundary for the 1-D case
成本函数应该下降: