py逻辑回归实例

建立一个逻辑回归模型来预测一个学生是否被大学录取。

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

#设置数据的路径,os.sep 根据你所处的平台,自动地采用相应的分割符号。

import os

path = 'data' + os.sep + 'LogiReg_data.txt' 

#读取csv文件,括号内,第一个是路径,第二个是header,指定行数用来作为列名,数据开始行数。如果文件中没有列名,则默认为0,否则设置为None。第三个名字是对数据1,2,3列进行命名。

pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])

pdData.head()

#读取数据的维度

pdData.shape

#下面是返回一个第三列中等于1的数据,和第三列中等于0的数据。等于分开了数据。分成两组。

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

#画图的画图域,大小先确定,长10,宽5

fig, ax = plt.subplots(figsize=(10,5))

#把上面确定的画出来,先画x的exam1,后画出来y的exam2,s是标量,默认可以是20,c是颜色 ,marker是形状,label是标签。

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

#设置x和y轴的名字

ax.set_xlabel('Exam 1 Score')

ax.set_ylabel('Exam 2 Score')

展示完数据,要完成分类,

目标:建立分类器(求解出三个参数 θ0θ1θ2

设定阈值,根据阈值判断录取结果,一般是 >0.5被录取,<0.5没被录取。

如下步骤

  • sigmoid : 映射到概率的函数

  • model : 返回预测结果值

  • cost : 根据参数计算损失

  • gradient : 计算每个参数的梯度方向

  • descent : 进行参数更新

  • accuracy: 计算精度

1、先定义def,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')

然后设置mode,就是x是样本的属性,theta是是参数。np.dot()是点乘。完成了预测模块。

def model(X, theta):
    

    return sigmoid(np.dot(X, theta.T))

得出来的是:


pdData.insert(0,'Ones',1) # 每行的第零个元素插入值为1的数,列名为Ones
orig_data = pdData.as_matrix() # convert the frame to its Numpy-array representation
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1] # 每行的最后一个数不取值
y = orig_data[:,cols-1:cols] # 获取每行的最后一个数
theta = np.zeros([1,3]) # [0,0,0], # 没有具体的值,只是起到占位的作用

X[:5]

查阅x的值:


y[:5]

查阅y的值:



下面定义损失函数:


第一式子的右面分了两个部分。

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

cost(X, y, theta)

out:

0.69314718055994529

计算梯度:


def gradient(X, y, theta):
    grad = np.zeros(theta.shape)
    error = (model(X, theta)- y).ravel()#numpy.flatten()返回一份拷贝,对拷贝所做的修改不会影响(reflects)原始矩阵,而numpy.ravel()返回的是视图,会影响原始矩阵。
    for j in range(len(theta.ravel())): #for each parmeter参数是
        term = np.multiply(error, X[:,j])#就是上面的式子,相乘第j列的所在行
        grad[0, j] = np.sum(term) / len(X)#在除以x长度
    

    return grad

三种方式决定迭代的结束的停止策略:

1、迭代次数,根据步长,大概 1000次。

2、根据梯度的变化 ,如果变化很小了就可以结束。

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
#data是数据,theta是x的系数,要迭代的。batchsize=1就是随机梯度下降,=总样本数就是梯度下降。在1和总数之间就是小批量。stoptype是停止策略。thresh是停止策略对应的阈值。alpha是梯度下降一步一步迭代的系数参数。
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();
    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

猜你喜欢

转载自blog.csdn.net/n_sapientia/article/details/80465534
今日推荐