邏輯回歸

邏輯回歸

線性回歸 to 邏輯回歸

本質(zhì):邏輯回歸的本質(zhì)就是在線性回歸的基礎(chǔ)上做了一個非線性的映射(變換),使得算法具有非線性的屬性。
Q1:為什么要加這個非線性的變換呢?
答:因?yàn)閷τ诰€性回歸,預(yù)測的變量是連續(xù)型的變量,不適合于分類型的離散變量(eg y=0或者y=1)。原因在于線性回歸的定義可能讓y大于0或者小于1,現(xiàn)在我們需要讓0<=y<=1。就用sigmoid函數(shù)做映射函數(shù)。sigmod函數(shù)在負(fù)無窮大時,趨向于0;正無窮大時,趨向于1。

為什么不采用分段函數(shù)而要采用sigmoid函數(shù)呢?因?yàn)閟igmoid函數(shù)是連續(xù)的,階梯函數(shù)是不連續(xù)且不可微的

決策邊界

h_\theta(x) = \frac{1}{1+e^{-\theta^T x}}

  • 當(dāng)h_\theta(x)\geq0.5時,預(yù)測y=1
  • 當(dāng)h_\theta(x)<0.5時,預(yù)測y=0

等同于

  • 當(dāng)\theta^T\ge0時,預(yù)測y=1
  • 當(dāng)\theta^T<0時,預(yù)測y=0

假設(shè)對于2個特征變量的函數(shù),h_\theta(x) = \frac{1}{1+e^-{(\theta_0+\theta_1x_1+\theta_2x_2)}},最后求解為

\begin{cases} \ \theta_0=-3\\ \theta_1=1\\\theta_2=1\end{cases}

則當(dāng)\theta_0+\theta_1x_1+\theta_2x_2\ge0時,y=1;當(dāng)\theta_0+\theta_1x_1+\theta_2x_2<0時,y=0;那么決策邊界就是\theta_0+\theta_1x_1+\theta_2x_2=0這條線;

另外一種情況就是可能 -1+x_1^2+x_2^2=0也是決策邊界,代表一個圓;

損失函數(shù)

Q2: 為什么不用線性回歸的損失函數(shù)作為邏輯回歸的損失函數(shù)呢?

答:繼續(xù)使用線性回歸的損失函數(shù),會導(dǎo)致代價(jià)函數(shù)變成一個非凸函數(shù)。這就導(dǎo)致會有很多局部最小值,用梯度下降法很難保證其收斂到全局最小值。

Q3:損失函數(shù)特點(diǎn)?

  • 當(dāng)真實(shí)類別y=1時,異常概率越大,損失越小
  • 當(dāng)真實(shí)類別y=0時,異常概率越小,損失越大

J= \begin{cases} -log(p)& \text{y=1}\\ -log(1-p)& \text{y=0} \end{cases}

通過控制系數(shù)的方法,將兩個方程聯(lián)系起來,可以得到,單個樣本的損失函數(shù)為:

J = -log(p)-(1-p)log(1-p)

全部樣本的損失可以取平均值

J(\theta) = -\frac{1}{m}\sum_{i=1}^m y^ilog(p^i)+(1-y^i)log(1-p^i)

Q4:通過最大似然函數(shù)求解損失函數(shù)

代碼實(shí)現(xiàn)

我們在線性回歸的基礎(chǔ)上,修改得到邏輯回歸。主要內(nèi)容為:

  • 定義sigmoid方法,使用sigmoid方法生成邏輯回歸模型
  • 定義損失函數(shù),并使用梯度下降法得到參數(shù)
  • 將參數(shù)代入到邏輯回歸模型中,得到概率
  • 將概率轉(zhuǎn)化為分類
import numpy as np

# 因?yàn)檫壿嫽貧w是分類問題,因此需要對評價(jià)指標(biāo)進(jìn)行更改

from .metrics import accuracy_score

class LogisticRegression:
def __init__(self):
    """初始化Logistic Regression模型"""
    self.coef_ = None
    self.intercept_ = None
    self._theta = None

"""
定義sigmoid方法
參數(shù):線性模型t
輸出:sigmoid表達(dá)式
"""
def _sigmoid(self, t):
    return 1. / (1. + np.exp(-t))

"""
fit方法,內(nèi)部使用梯度下降法訓(xùn)練Logistic Regression模型
參數(shù):訓(xùn)練數(shù)據(jù)集X_train, y_train, 學(xué)習(xí)率, 迭代次數(shù)
輸出:訓(xùn)練好的模型
"""
def fit(self, X_train, y_train, eta=0.01, n_iters=1e4):
    
    assert X_train.shape[0] == y_train.shape[0], \
        "the size of X_train must be equal to the size of y_train"

    """
    定義邏輯回歸的損失函數(shù)
    參數(shù):參數(shù)theta、構(gòu)造好的矩陣X_b、標(biāo)簽y
    輸出:損失函數(shù)表達(dá)式
    """
    def J(theta, X_b, y):
        # 定義邏輯回歸的模型:y_hat
        y_hat = self._sigmoid(X_b.dot(theta))
        try:
            # 返回?fù)p失函數(shù)的表達(dá)式
            return - np.sum(y*np.log(y_hat) + (1-y)*np.log(1-y_hat)) / len(y)
        except:
            return float('inf')
    """
    損失函數(shù)的導(dǎo)數(shù)計(jì)算
    參數(shù):參數(shù)theta、構(gòu)造好的矩陣X_b、標(biāo)簽y
    輸出:計(jì)算的表達(dá)式
    """
    def dJ(theta, X_b, y):
        return X_b.T.dot(self._sigmoid(X_b.dot(theta)) - y) / len(y)

    """
    梯度下降的過程
    """
    def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):
        theta = initial_theta
        cur_iter = 0
        while cur_iter < n_iters:
            gradient = dJ(theta, X_b, y)
            last_theta = theta
            theta = theta - eta * gradient
            if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
                break
            cur_iter += 1
        return theta

    X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
    initial_theta = np.zeros(X_b.shape[1])
    # 梯度下降的結(jié)果求出參數(shù)heta
    self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)
    # 第一個參數(shù)為截距
    self.intercept_ = self._theta[0]
    # 其他參數(shù)為各特征的系數(shù)
    self.coef_ = self._theta[1:]
    return self

"""
邏輯回歸是根據(jù)概率進(jìn)行分類的,因此先預(yù)測概率
參數(shù):輸入空間X_predict
輸出:結(jié)果概率向量
"""
def predict_proba(self, X_predict):
    """給定待預(yù)測數(shù)據(jù)集X_predict,返回表示X_predict的結(jié)果概率向量"""
    assert self.intercept_ is not None and self.coef_ is not None, \
        "must fit before predict!"
    assert X_predict.shape[1] == len(self.coef_), \
        "the feature number of X_predict must be equal to X_train"

    X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
    # 將梯度下降得到的參數(shù)theta帶入邏輯回歸的表達(dá)式中
    return self._sigmoid(X_b.dot(self._theta))

"""
使用X_predict的結(jié)果概率向量,將其轉(zhuǎn)換為分類
參數(shù):輸入空間X_predict
輸出:分類結(jié)果
"""
def predict(self, X_predict):
    """給定待預(yù)測數(shù)據(jù)集X_predict,返回表示X_predict的結(jié)果向量"""
    assert self.intercept_ is not None and self.coef_ is not None, \
        "must fit before predict!"
    assert X_predict.shape[1] == len(self.coef_), \
        "the feature number of X_predict must be equal to X_train"
    # 得到概率
    proba = self.predict_proba(X_predict)
    # 判斷概率是否大于0.5,然后將布爾表達(dá)式得到的向量,強(qiáng)轉(zhuǎn)為int類型,即為0-1向量
    return np.array(proba >= 0.5, dtype='int')

def score(self, X_test, y_test):
    """根據(jù)測試數(shù)據(jù)集 X_test 和 y_test 確定當(dāng)前模型的準(zhǔn)確度"""

    y_predict = self.predict(X_test)
    return accuracy_score(y_test, y_predict)

def __repr__(self):
    return "LogisticRegression()"

下面我們使用Iris數(shù)據(jù)集,來調(diào)用上面實(shí)現(xiàn)的邏輯回歸。

數(shù)據(jù)展示

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y<2,:2]
y = y[y<2]
plt.scatter(X[y==0,0], X[y==0,1], color="red")
plt.scatter(X[y==1,0], X[y==1,1], color="blue")
plt.show()


from myAlgorithm.model_selection import train_test_split
from myAlgorithm.LogisticRegression import LogisticRegression

X_train, X_test, y_train, y_test = train_test_split(X, y, seed=666)
log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)

# 查看訓(xùn)練數(shù)據(jù)集分類準(zhǔn)確度

log_reg.score(X_test, y_test)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容