二分类任务中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
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])
逻辑回归的目标
需要实现的模块
# 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))