前言
最近准备开始学习机器学习,后续将对学习内容进行记录,该文主要针对逻辑回归代码实现进行记录!同时也准备建一个群,大家可以进行交流,微信:ffengjixuchui
一、逻辑回归是什么?
逻辑回归概念篇可看博主之前的文章,传送门
二、代码实现
1.数据说明
你想根据两次考试的结果来决定每个申请人的录取机会。你有以前的申请人的历史数据,你可以用它作为逻辑回归的训练集。对于每一个培训例子,你有两个考试的申请人的分数和录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。 数据源下载:数据下载 提取码: 5mf2 打开数据后可以看到,只有数字没有列名,于是在利用pandas创建DataFrame结构时需要手动指定header 数据导入
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
pdData.head()
输出为: 将数据用散点图绘制出来
positive = pdData[pdData['Admitted'] == 1]
negative = pdData[pdData['Admitted'] == 0]
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')
输出为
2.逻辑回归代码
目标:建立分类器(求解出三个参数
θ
0
θ
1
θ
2
\theta_0\theta_1\theta_2
θ0?θ1?θ2?)设定阈值,根据阈值判断录取结果(一般设置为0.5) 待完成模块: ·sigmoid : 映射到概率的函数 ·model : 返回预测结果值 ·cost : 根据参数计算损失 ·gradient : 计算每个参数的梯度方向 ·descent : 进行参数更新 ·accuracy: 计算精度 具体代码说明: ①sigmoid函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
②model函数
def model(X, theta):
return sigmoid(np.dot(X, theta.T))
③增加一列取值为1的特征
if 'Ones' not in pdData.columns:
pdData.insert(0, 'Ones', 1)
④将pandas转换为ndarray,获取数据总列数
orig_data = pdData.values
cols = orig_data.shape[1]
⑤提取特征数据X,结果数据y,定义
θ
\theta
θ
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]
theta = np.zeros([1, 3])
⑥损失函数
J
(
θ
)
=
1
n
∑
i
=
1
n
[
(
?
y
l
o
g
(
h
θ
(
x
)
)
)
?
(
1
?
y
)
l
o
g
(
1
?
h
θ
(
x
)
)
]
J(\theta)=\frac{1}{n}\sum_{i=1}^n[(-ylog(h_\theta(x)))-(1-y)log(1-h_\theta(x))]
J(θ)=n1?∑i=1n?[(?ylog(hθ?(x)))?(1?y)log(1?hθ?(x))]
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))
⑦计算梯度方向
def gradient(X, y, theta):
grad = np.zeros(theta.shape)
error = (model(X, theta)-y ).ravel()
for j in range(len(theta.ravel())):
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):
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
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):
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)
runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
|