关于python:机器学习,逻辑回归

machine learning, logistic regression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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'部分执行正则化梯度下降的问题是什么,结果是 如下不正确:

1
2
3
4
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个


您的代码中有一些错误。

在计算新的θ值时,您需要使用同时更新。 在您更改theta0的情况下,您更改theta,然后将其用于theta1计算。 这是错误的。 您可能需要使用两个临时变量(或使用向量化解决方案)。

成本函数也不正确。 它应该包括两个部分:

y*log(h)(1-y)*log(1-h)

据我所知,成本函数不能为负,因此您无需计算其绝对值。

正则化对我来说也错了。

这是我的代码,对我有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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)

输出:

1
2
3
4
5
6
theta =
[[-5.51133636]
 [ 0.77301063]]

-theta0/theta1 =
[[ 7.12970317]]    #this number is the decision boundary for the 1-D case

成本函数下降,因为它应该这样做:

cost function of the logistic regression