[英]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.