5.logistic 回歸模型

大綱

1. idea --- 理解logistic 回歸原理

2. look --- 訓(xùn)練權(quán)值

3. code --- python


得先明確一下,這篇文章炒雞枯燥的說。非要看的話,得聽我解釋一下這篇文章的思路,要不會很凌亂的。

  • 首先是對logistic模型的核心公式解釋
  • 然后帶入以前的Perceptron計(jì)算模型中,來體現(xiàn)logistic模型的作用
  • 解釋模型中出現(xiàn)的概念和意義
  • 推導(dǎo)模型中公式
  • 訓(xùn)練算法的原理(極大似然法)
  • 用算法包實(shí)現(xiàn)一下看看
  • 都看到最后一條了開始看吧~

logistic 模型概述

輸出Y:{0,1}發(fā)生了事件->1,未發(fā)生事件->0
輸入X1,X2...Xm
P表示m個(gè)輸入作用下,事件發(fā)生(y=1)的概率
是一個(gè)由條件概率分布表示的2元分類模型

事件發(fā)生概率

logistic邏輯回歸模型就是,將輸入x和權(quán)值w的線性函數(shù)表示為輸出Y=1的概率(概念解釋和公式推導(dǎo)在后面)

Paste_Image.png

優(yōu)勢(odds)

事件發(fā)生的概率和不發(fā)生的概率比,即 P/(1-P)

優(yōu)勢比(odds ratio:OR)

衡量某個(gè)特征的兩個(gè)不同取值(C0,C1),對于結(jié)果的影響大小。OR>1事件發(fā)生概率大,是危險(xiǎn)因素,OR<1事件發(fā)生概率小,是保護(hù)因素,OR=1該因素與事件發(fā)生無關(guān)

OR:odds ratio

logit變換

事件發(fā)生于事件未發(fā)生之比的自然對數(shù),叫做P的logit變換,logit(P)

logit變換
logistic 函數(shù)

函數(shù)圖像為一個(gè)S形函數(shù):sigmoid function

S形函數(shù)

利用極大似然發(fā)擬合最佳參數(shù)

似然函數(shù)可以理解為條件概率的逆反
已知事件Y發(fā)生,來估計(jì)參數(shù)x·w的最合理的可能,即計(jì)算能預(yù)測事件Y的最佳x·w的值.

帶入logistic模型得以下公式

似然函數(shù)

為了簡單求得最大值,我們使用對數(shù)似然函數(shù)

對數(shù)似然函數(shù)

轉(zhuǎn)換成代價(jià)函數(shù)

我們用一個(gè)梯度上升的方法來使對數(shù)似然函數(shù)最大化,我們將對數(shù)似然函數(shù)重寫成代價(jià)函數(shù)的模式,然后利用梯度下降的方法求代價(jià)最小對應(yīng)的權(quán)值

代價(jià)函數(shù),對數(shù)似然函數(shù)重寫而來

整理成更易于閱讀和理解的形式

代價(jià)函數(shù)

在預(yù)測y=0和y=1的情況下,如下圖公式所示

Paste_Image.png

代價(jià)函數(shù)如圖,預(yù)測準(zhǔn)確的情況下誤差趨于0,預(yù)測錯(cuò)誤就會趨于無窮

代價(jià)函數(shù)圖形

Code Time

繪制S函數(shù)

# encoding:utf-8
__author__ = 'Matter'

import matplotlib.pyplot as plt
import numpy as np

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

z = np.arange(-5,5,0.05)
phi_z = sigmoid(z)

plt.plot(z,phi_z)
plt.axvline(0.0,color='k')
plt.ylim(-0.1,1.1)

plt.yticks([0.0,0.5,1.0])
ax = plt.gca()
ax.yaxis.grid(True)

plt.show()
S型函數(shù)

Logistic 邏輯回歸函數(shù)

# encoding:utf-8
__author__ = 'M'
# 讀取數(shù)據(jù)
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target

# 訓(xùn)練數(shù)據(jù)和測試數(shù)據(jù)分為7:3
from sklearn.cross_validation import train_test_split
x_train,x_test,y_train,y_test =train_test_split(X,y,test_size=0.3,random_state=0)

# 標(biāo)準(zhǔn)化數(shù)據(jù)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(x_train)
x_train_std = sc.transform(x_train)
x_test_std = sc.transform(x_test)

# 繪制決策邊界
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import warnings

def versiontuple(v):
    return tuple(map(int, (v.split("."))))

def plot_decision_regions(X,y,classifier,test_idx=None,resolution=0.02):
    # 設(shè)置標(biāo)記點(diǎn)和顏色
    markers = ('s','x','o','^','v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # 繪制決策面
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                         np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
                    alpha=0.8, c=cmap(idx),
                    marker=markers[idx], label=cl)

    # 高粱所有的數(shù)據(jù)點(diǎn)
    if test_idx:
        # 繪制所有數(shù)據(jù)點(diǎn)
        if not versiontuple(np.__version__) >= versiontuple('1.9.0'):
            X_test, y_test = X[list(test_idx), :], y[list(test_idx)]
            warnings.warn('Please update to NumPy 1.9.0 or newer')
        else:
            X_test, y_test = X[test_idx, :], y[test_idx]
        plt.scatter(X_test[:, 0], X_test[:, 1], c='',
                alpha=1.0, linewidth=1, marker='o',
                s=55, label='test set')

# 應(yīng)用Logistics回歸模型
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=1000.0,random_state=0)
lr.fit(x_train_std,y_train)

X_combined_std = np.vstack((x_train_std, x_test_std))
y_combined = np.hstack((y_train, y_test))
plot_decision_regions(X_combined_std, y_combined,
                      classifier=lr, test_idx=range(105,150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
Logistics 回歸函數(shù)分類結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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