您的位置:首页 > 其它

机器学习(3)-逻辑回归

2017-11-11 21:49 197 查看

Sigmoid函数

g(z)=11+e−z

x取值为任意实数,y取值为[0,1]

看成是把实数映射成一个概率值,可用作分类任务

数学推导

预测函数:hθ(x)=g(θTx)=11+e−θTx

θTx表示原假设函数的参数矩阵*特征

二分类任务中y的取值为1或者0,所以有:

P(y=1|x;0)=hθ(x)

P(y=0|x;0)=1−hθ(x)

整合后:P(y|x;θ)=(hθ(x))y(1−hθ(x))1−y

如果看不明白可以把y=1和y=0分别代入,即可得到原式子

似然函数

类似线性回归做似然函数的处理



求导过程



参数更新:θj:=θj−α1m∑mi=1(hθ(xi)−yi)xji

”:=”表示赋值

θj表示第j个参数

xi表示第i个样本

hθ(xi)表示将第i个样本输入预测函数得到的结果

yi表示第i个样本的label值

xji表示第i个样本的第j个特征

softmax多分类



代码实践

读取数据和数据处理

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
# os.sep是目录连接符lunux下是/ ;window下是\\,读取是相对路径 data\\LogiReg_data.txt
path = 'data'+os.sep+'LogiReg_data.txt'
path = 'data' + os.sep + 'LogiReg_data.txt'
#header表示第一行是不是列名
pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
# 查看头部
pdData.head()
# 查看矩阵的shape
pdData.shape

positive = pdData[pdData['Admitted'] == 1] # returns the subset of rows such Admitted = 1, i.e. the set of *positive* examples
negative = pdData[pdData['Admitted'] == 0] # returns the subset of rows such Admitted = 0, i.e. the set of *negative* examples
# 将数据再画布上查看,直观看下数据的分布
fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=30, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')




这里为数据加入列x0=1的特征

pdData.insert(0, 'Ones', 1)
# 获取特征矩阵和标签矩阵
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]
# 初始化参数矩阵
theta = np.zeros([1, 3])


逻辑回归的目标

建立分类器,求出三个参数θ0,θ1,θ2

因为只有两个特征,假设的函数是:y=θ0+θ1x1+θ2x2

为了计算,我们会引入x0=1,代码中的操作就是增加一列特征,值全部为1

所以有y=θ0x0+θ1x1+θ2x2=θTx

需要实现的模块

实现的目标函数:θj:=θj−α1m∑mi=1(hθ(xi)−yi)xji

sigmoid函数:hθ(x)=g(θTx)=11+e−θTx

model,矩阵乘法部分:θTx

cost,损失函数,对数似然函数的负值的平均值,用于评测算法,越小越好

gradient:计算梯度,即每个参数的梯度方向 ∂J∂θj=−1m∑i=1n(yi−hθ(xi))xij

descent:参数更新

计算精度

# sigmoid
def sigmoid(z):
return 1 / (1 + np.exp(-z))

# model
def model(X, theta):
return sigmoid(np.dot(X, theta.T))


损失函数

将对数似然函数去负号

D(hθ(x),y)=−ylog(hθ(x))−(1−y)log(1−hθ(x))

求平均损失

J(θ)=1n∑ni=1D(hθ(xi),yi)

def cost(X, y, theta):
left = np.multiply(-y, np.log(model(X, theta)))
right = np.multiply(1 - y, np.log(1 - model(X, theta)))
return np.sum(left - right) / (len(X))


计算梯度

∂J∂θj=−1m∑ni=1(yi−hθ(xi))xij

def gradient(X, y, theta):
grad = np.zeros(theta.shape)
error = (model(X, theta)- y).ravel()
for j in range(len(theta.ravel())): #for each parmeter
term = np.multiply(error, X[:,j])
grad[0, j] = np.sum(term) / len(X)

return grad


比较3中不同梯度下降方法

STOP_ITER = 0
STOP_COST = 1
STOP_GRAD = 2

def stopCriterion(type, value, threshold):
#设定三种不同的停止策略
if type == STOP_ITER:        return value > threshold
elif type == STOP_COST:      return abs(value[-1]-value[-2]) < threshold
elif type == STOP_GRAD:      return np.linalg.norm(value) < threshold

import numpy.random


#洗牌,每次梯度下降取样本前要把数据集的顺序打乱
def shuffleData(data):
# 随机排序函数shuffle
np.random.shuffle(data)
cols = data.shape[1]
X = data[:, 0:cols-1]
y = data[:, cols-1:]
return X, y


import time
# 参数迭代更新
def descent(data, theta, batchSize, stopType, thresh, alpha):
# 梯度下降求解

init_time = time.time()
i = 0 # 迭代次数
k = 0 # batch
X, y = shuffleData(data)
grad = np.zeros(theta.shape) # 计算的梯度
costs = [cost(X, y, theta)] # 损失值

while True:
grad = gradient(X[k:k+batchSize],y[k:k+batchSize], theta)
k += batchSize
if k >= n:
k = 0
X, y = shuffleData(data) #重新洗牌
theta = theta - alpha*grad
costs.append(cost(X, y, theta)) # 保存损失值
i += 1

if stopType == STOP_ITER:       value = i
elif stopType == STOP_COST:     value = costs
elif stopType == STOP_GRAD:     value = grad
if stopCriterion(stopType, value, thresh): break

return theta, i-1, costs, grad, time.time()-init_time


# 此处的代码是将迭代的过程以图表的形式展示
def runExpe(data, theta, batchSize, stopType, thresh, alpha):
#import pdb; pdb.set_trace();
theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled"
name += " data - learning rate: {} - ".format(alpha)
if batchSize==n: strDescType = "Gradient"
elif batchSize==1:  strDescType = "Stochastic"
else: strDescType = "Mini-batch ({})".format(batchSize)
name += strDescType + " descent - Stop: "
if stopType == STOP_ITER: strStop = "{} iterations".format(thresh)
elif stopType == STOP_COST: strStop = "costs change < {}".format(thresh)
else: strStop = "gradient norm < {}".format(thresh)
name += strStop
print ("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
name, theta, iter, costs[-1], dur))
fig, ax = plt.subplots(figsize=(12,4))
ax.plot(np.arange(len(costs)), costs, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title(name.upper() + ' - Error vs. Iteration')
return theta


不同迭代策略

每次迭代都遍历所有样本

#选择的梯度下降方法是基于所有样本的
n=100
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)




!这里的迭代次数过少,修改阈值为1E-6,迭代次数为110000次

会发现瞬时值会再次降低

runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)




这种策略虽然准确度较高,但是迭代次数多,计算量大

随机梯度下降:每次只选取一个样本进行计算

runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)


这种策略计算速度快,但是不稳定,需要很小的学习率

小批量梯度下降

runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)


实践中常用的策略,这种算法需要对数据进行预处理,数据标准化

精度预测

#设定阈值,设定0.5,预测概率大于等于0.5的值为1,小于0.5的值为0,来进行分类
def predict(X, theta):
return [1 if x >= 0.5 else 0 for x in model(X, theta)]

scaled_X = scaled_data[:, :3]
y = scaled_data[:, 3]
predictions = predict(scaled_X, theta)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]
accuracy = (sum(map(int, correct)) % len(correct))
print ('accuracy = {0}%'.format(accuracy))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息