Logistic Regression
#三大件,%将那些用matplotlib绘制的图显示在页面里而不是弹出一个窗口
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline #由于 %matplotlib inline 的存在,当输入plt.plot(x,y_1)后,不必再输入 plt.show(),图像将自动显示出来
#os.sep 可以取代操作系统特定的路径分割符
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)) #固定搭配 fig, ax = plt.subplots(figsize=(12,8),ncols=2,nrows=1)#该方法会返回画图对象和坐标对象ax,figsize是设置子图长宽
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() #show
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
The logistic regression
目标:建立分类器(求解出三个参数 θ0θ1θ2θ0θ1θ2)
设定阈值,根据阈值判断录取结果
要完成的模块
sigmoid : 映射到概率的函数
model : 返回预测结果值
cost : 根据参数计算损失
gradient : 计算每个参数的梯度方向
descent : 进行参数更新
accuracy: 计算精度
sigmoid : 映射到概率的函数
def sigmoid(z):
return 1 / (1 + np.exp(-z))
nums = np.arange(-10, 10, step=1) #creates a vector containing 20 equally spaced values from -10 to 10
fig, ax = plt.subplots(figsize=(12,4))
ax.plot(nums, sigmoid(nums), 'r') #x,y,color
np.dot()返回的是两个数组的点积(dot product)
1.如果处理的是一维数组,则得到的是两数组的內积
In : d = np.arange(0,9) Out: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
In : e = d[::-1] Out: array([8, 7, 6, 5, 4, 3, 2, 1, 0]) In : np.dot(d,e) Out: 84
2.如果是二维数组(矩阵)之间的运算,则得到的是矩阵积(mastrix product)
In : a = np.arange(1,5).reshape(2,2)
Out:
array([[1, 2],
[3, 4]])
In : b = np.arange(5,9).reshape(2,2)
Out: array([[5, 6],
[7, 8]])
In : np.dot(a,b)
Out:
array([[19, 22],
[43, 50]])
3. a.dot(b) 与 np.dot(a,b)效果相同
#预测函数模块
def model(X, theta):
return sigmoid(np.dot(X, theta.T))
y = 0,1代表类别
pdData.insert(0, 'Ones', 1) #第一列插入全为1的一列
# set X (training data) and y (target variable)
orig_data = pdData.as_matrix() # 返回不是Numpy矩阵,而是Numpy数组。
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]
theta = np.zeros([1, 3]) #构造参数,进行占位
def cost(X, y, theta):
left = np.multiply(-y, np.log(model(X, theta))) #等式左边 这里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) #theta数 = 求导次数,即解的数
error = (model(X, theta)- y).ravel() #yi---真实值,hx----预测值
for j in range(len(theta.ravel())): #for each parmeter
term = np.multiply(error, X[:,j])
grad[0, j] = np.sum(term) / len(X) #这里X相当于样本个数
return grad
numpy.ravel() 与numpy.flatten()
二者都是将多维数组降位一维,
区别:
numpy.flatten()返回一份拷贝,对拷贝所做的修改不会影响(reflects)原始矩阵,
numpy.ravel()返回的是视图(view,也颇有几分C/C++引用reference的意味),会影响(reflects)原始矩阵。
Gradient descent
比较3种不同梯度下降方法
STOP_ITER = 0 #按次数
STOP_COST = 1 #损失
STOP_GRAD = 2 #梯度
def stopCriterion(type, value, threshold):
#设定三种不同的停止策略
if type == STOP_ITER: return value > threshold # threshold阈值
elif type == STOP_COST: return abs(value[-1]-value[-2]) < threshold
elif type == STOP_GRAD: return np.linalg.norm(value) < threshold
Python中fabs(x)
方法返回x的绝对值。虽然类似于abs()
函数,但是两个函数之间存在以下差异:
-
abs()
是一个内置函数,而fabs()
在math
模块中定义的。 -
fabs()
函数只适用于float和integer类型,而abs()
也适用于复数。
linalg=linear(线性)+algebra(代数),norm则表示范数。
函数参数
x_norm=np.linalg.norm(x, ord=None, axis=None, keepdims=False)
①x: 表示矩阵(也可以是一维)
②ord:范数类型
向量的范数:
计算机领域 用的比较多的就是迭代过程中收敛性质的判断,如果理解上述的意义,在计算机领域,一般迭代前后步骤的差值的范数表示其大小,常用的是二范数,差值越小表示越逼近实际值,可以认为达到要求的精度,收敛
import numpy.random
#洗牌 set X (trainning data) and y (target variable)
def shuffleData(data):
np.random.shuffle(data)
cols = data.shape[1]
X = data.iloc[:,0:cols-1] #x是所有行,去掉最后一列
y = data.iloc[:,cols-1:cols] #y是所有行,最后一列
return X, y
batch:批量----一次性拿多少个样本去做
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 #取batch数量个数据
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(); 断点调试
pdb 是 python 自带的一个包,为 python 程序提供了一种交互的源代码调试功能,主要特性包括设置断点、单步调试、进入函数调试、查看当前代码、查看栈片段、动态改变变量的值等。
使用的时候要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