机器学习算法Python实现(github地址:https://github.com/lawlite19/MachineLearning_Python
由于公式使用的是LaTex,解析使用的google的Chart API,所以显示有问题,可以移步github)
二、逻辑回归
1、代价函数
- 可以综合起来为:
其中:
- 为什么不用线性回归的代价函数表示,因为线性回归的代价函数可能是非凸的,对于分类问题,使用梯度下降很难得到最小值,上面的代价函数是凸函数
- 的图像如下,即
y=1
时:
可以看出,当趋于1
,y=1
,与预测值一致,此时付出的代价cost
趋于0
,若趋于0
,y=1
,此时的代价cost
值非常大,我们最终的目的是最小化代价值
- 同理的图像如下(y=0
):
2、梯度
- 同样对代价函数求偏导:
可以看出与线性回归的偏导数一致
- 推到过程
3、正则化
- 目的是为了防止过拟合
- 在代价函数中加上一项,所以最终的代价函数为:
- 注意j是重1开始的,因为theta(0)为一个常数项,X中最前面一列会加上1列1,所以乘积还是theta(0),feature没有关系,没有必要正则化
- 正则化后的代价:
def costFunction(initial_theta,X,y,inital_lambda):
m = len(y)
J = 0
h = sigmoid(np.dot(X,initial_theta))
theta1 = initial_theta.copy()
theta1[0] = 0
temp = np.dot(np.transpose(theta1),theta1)
J = (-np.dot(np.transpose(y),np.log(h))-np.dot(np.transpose(1-y),np.log(1-h))+temp*inital_lambda/2)/m
return J
def gradient(initial_theta,X,y,inital_lambda):
m = len(y)
grad = np.zeros((initial_theta.shape[0]))
h = sigmoid(np.dot(X,initial_theta))
theta1 = initial_theta.copy()
theta1[0] = 0
grad = np.dot(np.transpose(X),h-y)/m+inital_lambda/m*theta1
return grad
4、S型函数(即)
def sigmoid(z):
h = np.zeros((len(z),1))
h = 1.0/(1.0+np.exp(-z))
return h
5、映射为多项式
- 因为数据的feture可能很少,导致偏差大,所以创造出一些feture结合
- eg:映射为2次方的形式:
- 实现代码:
def mapFeature(X1,X2):
degree = 3;
out = np.ones((X1.shape[0],1))
'''
这里以degree=2为例,映射为1,x1,x2,x1^2,x1,x2,x2^2
'''
for i in np.arange(1,degree+1):
for j in range(i+1):
temp = X1**(i-j)*(X2**j)
out = np.hstack((out, temp.reshape(-1,1)))
return out
6、使用scipy
的优化方法
- 梯度下降使用
scipy
中optimize
中的fmin_bfgs
函数
- 调用scipy中的优化算法fmin_bfgs(拟牛顿法Broyden-Fletcher-Goldfarb-Shanno
- costFunction是自己实现的一个求代价的函数,
- initial_theta表示初始化的值,
- fprime指定costFunction的梯度
- args是其余测参数,以元组的形式传入,最后会将最小化costFunction的theta返回
result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,y,initial_lambda))
7、运行结果
- data1决策边界和准确度
- data2决策边界和准确度
8、使用scikit-learn库中的逻辑回归模型实现
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import train_test_split
import numpy as np
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
# 归一化
scaler = StandardScaler()
scaler.fit(x_train)
x_train = scaler.fit_transform(x_train)
x_test = scaler.fit_transform(x_test)
#逻辑回归
model = LogisticRegression()
model.fit(x_train,y_train)
predict = model.predict(x_test)
right = sum(predict == y_test)
predict = np.hstack((predict.reshape(-1,1),y_test.reshape(-1,1)))
print predict
print ('测试集准确率:%f%%'%(right*100.0/predict.shape[0]))