[英]machine learning, logistic regression
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))的逻辑回归,我无法弄清楚主要是函数'graD'部分执行正则化梯度下降的问题是什么,结果是如下不正确:
lg(X,y,0.01,0.1,30)
Out[137]:
matrix([[1000.10539375],
[ 49.33333333]])
我输入的数据是:(对于X):1 2 3 4 5 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
您的代码中有一些错误。
在计算新的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
成本函数下降,因为它应该这样做:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.