一、任务基础

# 数据分析三个必备的python库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline


import os

path = "data" + os.sep + "LogiReg_data.txt"
# header=None 表示没有列标签 第三列表示考生是否被录取 Exam 1 Exam 2  表示两个特征


pdData.shape
(100, 3)

# pdData 是二维数组positive = pdData[pdData['Admitted'] == 1]

fig, ax = plt.subplots(figsize=(10, 5))# 绘制散点图
ax.scatter(positive['Exam 1'],
positive['Exam 2'],
s=30,
c='b',
marker='o',
ax.scatter(negative['Exam 1'],
negative['Exam 2'],
s=30,
c='r',
marker='x',
ax.legend()  # 添加图例
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')


二、定义函数模块

θ0表示第一个考试成绩权重，θ1表示第二个考试成绩权重，θ2表示偏置项

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


# sigmoid函数图像
nums = np.arange(-10, 10, step=1)
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(nums, sigmoid(nums), 'r')


def model(X, theta):
return sigmoid(np.dot(X, theta.T)) # 矩阵乘法


# pdData.drop('Ones', 1, inplace=True)  # 删除添加的Ones列
pdData.insert(0, 'Ones', 1)

orig_data = pdData.as_matrix()
# print(orig_data.shape)
cols = orig_data.shape[1]
X = orig_data[:, 0:cols - 1]
y = orig_data[:, cols - 1:cols]
# 三个θ参数，用零占位
theta = np.zeros([1, 3])


X[:5]


y[:5]


theta


X.shape, y.shape, theta.shape
((100, 3), (100, 1), (1, 3))

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)))
# print(left.shape)
# print("===========================")
# print(right.shape)
return np.sum(left - right) / len(X)


cost(X, y, theta)

0.6931471805599453

def gradient(X, y, theta):
grad = np.zeros(theta.shape) # 一共三个参数  所以计算三个参数的梯度
error = (model(X, theta) - y).ravel() # ravel展平数组
for j in range(len(theta.ravel())):
term = np.multiply(error, X[:, j])


（1）批量梯度下降
（2）随机梯度下降
（3）小批量梯度下降

STOP_ITER = 0 # 按照迭代次数停止
STOP_COST = 1 # 按照损失值停止，两次迭代损失值很小则停止

# threshold 阈值
def stopCriterion(type, value, threshold):
# 设定三种不同的停止策略
if type == STOP_ITER:
return value > threshold
elif type == STOP_COST:
return abs(value[-1] - value[-2]) < threshold
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

# 梯度下降求解  batchSize取1代表随机梯度下降，取总样本数代表梯度下降，取1~总样本数之间代表miniBatch梯度下降
def descent(data, theta, batchSize, stopType, thresh, alpha):
init_time = time.time() # 初始时间  thresh：阈值，alpha：学习率
i = 0 # 迭代次数
k = 0 # batch
X, y = shuffleData(data)
costs = [cost(X, y, theta)] #损失值

while True:
k += batchSize # 取batch数量个数据 n可能代表0
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
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:
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=(10, 5))
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.0000001, alpha=0.001)


runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)


下面这三种对比不同的梯度下降方法

runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, 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)


from sklearn import preprocessing as pp

scaled_data = orig_data.copy()
scaled_data[:, 1:3] = pp.scale(orig_data[:, 1:3])

runExpe(scaled_data, theta, n, STOP_ITER, thresh=5000, alpha=0.001)


runExpe(scaled_data, theta, n, STOP_GRAD, thresh=0.02, alpha=0.001)


更多的迭代次数会使得损失下降的更多！

theta = runExpe(scaled_data, theta, 1, STOP_GRAD, thresh=0.002/5, alpha=0.001)


runExpe(scaled_data, theta, 16, STOP_GRAD, thresh=0.002*2, alpha=0.001)


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))


accuracy = 89%

posted @ 2019-07-10 09:44  |旧市拾荒|  阅读(...)  评论(...编辑  收藏