機器學習 - 算法 - 梯度降低求解邏輯迴歸

梯度降低求解邏輯迴歸 - 算法實現

相關模塊 - 三大件

#三大件
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline

數據集 - 大學錄取

咱們將創建一個邏輯迴歸模型來預測一個學生是否被大學錄取。html

假設你是一個大學系的管理員,你想根據兩次考試的結果來決定每一個申請人的錄取機會。python

你有之前的申請人的歷史數據,你能夠用它做爲邏輯迴歸的訓練集。算法

對於每個培訓例子,你有兩個考試的申請人的分數和錄取決定。數組

爲了作到這一點,咱們將創建一個分類模型,根據考試成績估計入學機率。app

import os path = 'data' + os.sep + 'LogiReg_data.txt' pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted']) pdData.head() pdData.shape #(100, 3) 數據維度 100 行, 3列

圖形展現 - 散點圖

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
 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') # x 標識
ax.set_ylabel('Exam 2 Score') # y 標識

 

邏輯迴歸 - 實現算法

▒ 目標

 ▨ 創建分類器 dom

 ▨ 求解三個參數  - 分別表示 成績一, 成績二以及偏置項的參數 函數

▒ 閾值

  ▨ 設定閾值來標識分類的結果, 此處設置爲 0.5 工具

  ▨ > 0.5  標識經過, < 0.5 標識未經過學習

▒ 所需模塊

  ▨ sigmoid : 映射到機率的函數測試

  ▨ model : 返回預測結果值

  ▨ cost : 根據參數計算損失

  ▨ gradient : 計算每一個參數的梯度方向

  ▨ descent : 進行參數更新

  ▨ accuracy: 計算精度

▒ sigmoid 函數實現

  ▨  公式    

  ▨  Python 實現     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')

 

  ▨ 值域 

    

▒  model 函數 - 預測函數實現 

  ▨ 數學公式     

  ▨ Python 實現 

def model(X, theta): return sigmoid(np.dot(X, theta.T))

▒  構造數據集

 ▨ 加一行 -  數據集要進行偏置項的處理 ( 加一列全1的數據 )

pdData.insert(0, 'Ones', 1) # 偏置項參數的處理


# set X (training data/訓練數據) and y (target variable/變量參數)
orig_data = pdData.as_matrix() # 轉換爲 數組形式
cols = orig_data.shape[1] X = orig_data[:,0:cols-1] y = orig_data[:,cols-1:cols] # convert to numpy arrays and initalize the parameter array theta #X = np.matrix(X.values) #y = np.matrix(data.iloc[:,3:4].values) #np.array(y.values)
theta = np.zeros([1, 3])  # 參數佔位, 先用 0 填充

 

▒  損失函數

  ▨ 數學公式 

  

  將對數似然函數去負號 -   

  求平均損失 -   

  這塊若是忘了怎麼回事能夠在這裏進行查閱 點擊這裏跳轉公式篇

   ▨  Python 實現 

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

  X, y  表示兩個特徵值, 傳入  theta  表示參數  

 np.multiply  乘法計算, 將式子分爲左右查分

   ▨  計算 cost 值

▒  計算梯度

   ▨  數學公式 - 進行求導計算後, 將最終結果轉換爲 python 實現

    

    ▨  Python 實現

def gradient(X, y, theta): grad = np.zeros(theta.shape) # 由於會有三個結果, 所以這裏進行預先的佔位
    error = (model(X, theta)- y).ravel() # h0(xi)-yi 象形... 這裏吧前面的m分之一的那個負號移到了這裏來去除負號
    for j in range(len(theta.ravel())): # 求三次
        term = np.multiply(error, X[:,j]) # : 表示全部的行, j 表示第 j 列
        grad[0, j] = np.sum(term) / len(X) return grad

     這裏有三個  , 那麼應該也是計算出來三個值, 所以這裏進行了三次的循環

  每次的循環針對要處理的那一列進行操做

▒  中止策略

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

    ▨  參數詳解

  •  data  -  數據
  •  theta  - 參數
  •  batchSize  這裏的指定及選擇降低方式
    • 若是指定爲 1 則表示隨機, 指定爲總樣本數則表示批量, 指定 1-總數 之間則表示小批量
  • stopType  - 中止策略
    • 迭代次數 - 達到指定次數中止
    • 損失 - 損失較小中止
    • 梯度 - 梯度較小中止
  • thresh  -  策略對應的閾值,
    • 好比選擇 迭代次數中止策略, 則此值表示迭代次數的上限, 
  • alpha  - 學習率 ( 就那個 0.01 ~ 0.0....1 的那個)

▒  輔助工具函數

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: " # 根據 中止方式進行選擇處理生成 name 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)

    ▨  參數詳解

  • 這裏 設置 100 爲樣本的總數據量, 所以這是個批量降低方式的計算
  • 中止策略是基於迭代次數進行判斷
  •  thresh  5000 表示迭代次數
  • 學習率的設置爲 0.00001 很是的小,  

    ▨  測試結果

  

    ▨  結果詳解

  1.34s 完成了所有的 5000次 迭代, 最終的結果的爲 0.63 左右

▒  批量降低 - 損失值中止策略

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

    ▨  參數詳解

  • 這裏 依舊設置 100 爲樣本的總數據量, 依舊爲批量降低方式的計算
  • 中止策略是基於損失值進行判斷
  •  thresh  設置爲若是損失小於 0.000001 的時候則中止
  • 學習率的設置爲 0.00001 很是的小

    ▨  測試結果

 

    ▨  結果詳解

  可見測試用了 32.02s才完成, 達到損失值這麼小的時候用了 100000次以上的迭代次數, 可是結果也達到了 0.4 如下

  比上一輪的結果要優秀不少

▒  批量降低 - 梯度值中止策略

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

    ▨  參數詳解

  • 這裏 依舊設置 100 爲樣本的總數據量, 依舊爲批量降低方式的計算
  • 中止策略是基於梯度值變化進行判斷
  •  thresh  設置 0.05 表示梯度變化 
  • 學習率的設置爲 0.00001 很是的小

    ▨  測試結果

 

    ▨  結果詳解

  可見測試用了12.18s 才完成, 達到損失值這麼小的時候用了40000 次以上的迭代次數, 可是結果也達到了 0.5 如下

  由迭代次數也能夠看出比不過 12w 次的結果, 所以最終的收斂在 0.50 左右沒法比過 0.4 的上輪結果

▒  總結

經過以上的三輪比較能夠看出. 迭代次數越多獲得的收斂結果越好, 並且某些方式還會存在誤判的

好比此圖中從2000開始後面就趨於平緩, 實際上並無可以徹底收斂到極限

梯度降低比較

▒  隨機降低 

  

   能夠看出隨機降低的5000此迭代的結果很是不穩定, 損失值忽上忽下, 基本上徹底沒辦法收斂的, 固然時間很快啊就只須要 0.50s 

   固然這麼理想的成績也是由於學習率的問題, 學習率進行調整後再試一次

    ▨  調整學習率

  

 在調整了學習率以及增大了迭代次數以後, 損失值確實進行了必定程度的收斂, 可是收斂到 0.63 左右不算很理想的成績

▒  小批量降低   

  

   小批量降低, 每次使用 16個樣本數據進行 15000次學習率爲 0.001 的迭代, 結果無收斂, 耗時 1.88s

   進一步優化的話能夠繼續調整學習率, 也能夠換另外一種方案 ---- 數據標準化

    ▨  數據標準化

   將數據按其屬性(按列進行)減去其均值,而後除以其方差

  最後獲得的結果是,對每一個屬性/每列來講全部數據都彙集在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)

  標準化處理後數據進行了收斂, 且收斂在 0.4如下是較爲優秀的結果了

    ▨ 對比

 

▒  總結

  在收斂效果不佳的時候, 先改數據再改模型是一個基本的套路

  對比三種降低方式, 綜合選擇小批量爲最優選擇

▒  精度計算

#設定閾值
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%
相關文章
相關標籤/搜索