1. 程式人生 > >機器學習之使用Python完成邏輯迴歸

機器學習之使用Python完成邏輯迴歸

一、任務基礎

我們將建立一個邏輯迴歸模型來預測一個學生是否被大學錄取。假設你是一個大學系的管理員,你想根據兩次考試的結果來決定每個申請人的錄取機會。你有以前的申請人的歷史資料,你可以用它作為邏輯迴歸的訓練集。對於每一個培訓例子,你有兩個考試的申請人的分數和錄取決定。為了做到這一點,我們將建立一個分類模型,根據考試成績估計入學概率。

資料集連結為:連結:https://pan.baidu.com/s/1H3T3RfyT3toKbFrqO2z8ug,提取碼:jku5 

首先匯入需要使用到的Python庫:

# 資料分析三個必備的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 = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
pdData.head()

  

檢視資料維度:

pdData.shape  
(100, 3)

根據是否錄取為標準,檢視資料集的分佈

# pdData 是二維陣列
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')

  

二、定義函式模組

接下來按照模組化程式設計:

 θ0表示第一個考試成績權重,θ1表示第二個考試成績權重,θ2表示偏置項

  

首先,定義Sigmoid函式

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

檢視Sigmoid函式影象: 

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

  

根據上圖我們可以看到,這個函式的值域是0到1。當x趨近於負無窮時,y趨近於0,當x趨近於正無窮時,y趨近於1。並且當x等0時,y等於0.5。

返回預測結果值:

  

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

在第一列的前面在加上資料全為1的一列,為了方便上面的矩陣進行運算。  

# 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五個樣本資料  

X[:5]

  

檢視y五個樣本資料

y[:5]

  

檢視theta引數

theta

  

檢視X,y,theta的維度  

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

根據以上,我們可以檢查到前面都是沒有問題的。使用Notebook開發就是這個好處,可以邊做邊檢查。

根據引數計算損失:

  

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值,檢查cost函式是否正確  

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])
        grad[0, j] = np.sum(term) / len(X) # grad[0, 0] grad[0, 1] grad[0, 2]
    return grad

比較3種不同梯度下降方法:

(1)批量梯度下降
(2)隨機梯度下降
(3)小批量梯度下降 

STOP_ITER = 0 # 按照迭代次數停止
STOP_COST = 1 # 按照損失值停止,兩次迭代損失值很小則停止
STOP_GRAD = 2 # 根據梯度停止,梯度變化很小則停止


# threshold 閾值
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

# 梯度下降求解  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)
    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數量個數據 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
        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=(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

三、實驗結果對比

下面對比三種停止策略對結果的影響

根據迭代次數停止,設定閾值5000次,也就是說迭代次數超過5000即停止迭代

n = 100 # 選擇所有樣本進行梯度下降
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)

  

上面迭代了5000次,看起來似乎目標函式已經成功收斂。上面消耗一秒多的時間,看起來似乎不太行,損失值0.63。下面根據損失值停止,設定閾值1E-6,也就是兩次損失值之差不能超過1E-6,差不多需要500000次迭代

runExpe(orig_data, theta, n, STOP_COST, thresh=0.0000001, alpha=0.001)

  

根據圖片標題我們可以看到差不多迭代50萬次才達到我們定義的閾值,而此時收斂的效果更好。損失值只有0.25,消耗的時間達到100多秒。下面根據梯度變化停止,設定閾值0.05,表示梯度相差0.05即停止迭代。

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

  

下面這三種對比不同的梯度下降方法 

下面1表示每次1次迭代只拿一個樣本,batchSize取1代表隨機梯度下降,取總樣本數代表梯度下降,取1~總樣本數之間代表miniBatch梯度下降

runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)

  

有點爆炸。。。很不穩定,下面把迭代次數調高點,學習率調低點

runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)

  

可以看出這次結果,速度快,但穩定性差,需要很小的學習率

下面進行Mini-batch descent,一次迭代拿16個樣本。

runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)

  

浮動仍然比較大,我們來嘗試下對資料進行標準化:將資料按其屬性(按列進行)減去其均值,然後除以其方差。最後得到的結果是,對每個屬性/每列來說所有資料都聚集在0附近,方差值為1  

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)

  

它好多了!原始資料,只能5000次迭代損失值達到0.61,而我們得到了0.38在這裡! 所以對資料做預處理是非常重要的  

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)

   

隨機梯度下降更快,但是我們需要迭代的次數也需要更多,所以還是用batch的比較合適!!!  

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

  

這次時間只花了0.16秒,損失值只有0.22,迭代次數也只有一千多次,得到的結果不錯。所以說當我們進行資料梯度下降的時候,首先對資料進行預處理,然後再進行各種的嘗試,在這裡的話Mini-batch是比較好的,無論是從時間還是結果來看。 

預測函式

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

最終得到準確率89%。

accuracy = 89%

總結:首先拿到資料集看下資料長什麼樣子,然後再給資料增加了一列全是1的資料,然後再對每個模組函式的編寫,最後對比各種策略下的實驗結果,最終得出最佳結果。   

&n