大綱
1. idea --- 理解logistic 回歸原理
2. look --- 訓練權值
3. code --- python
得先明確一下,這篇文章炒雞枯燥的說。非要看的話,得聽我解釋一下這篇文章的思路,要不會很凌亂的。
- 首先是對logistic模型的核心公式解釋
- 然后帶入以前的Perceptron計算模型中,來體現logistic模型的作用
- 解釋模型中出現的概念和意義
- 推導模型中公式
- 訓練算法的原理(極大似然法)
- 用算法包實現一下看看
- 都看到最后一條了開始看吧~
logistic 模型概述
輸出Y:{0,1}發(fā)生了事件->1,未發(fā)生事件->0
輸入X1,X2...Xm
P表示m個輸入作用下,事件發(fā)生(y=1)的概率
是一個由條件概率分布表示的2元分類模型
事件發(fā)生概率
logistic邏輯回歸模型就是,將輸入x和權值w的線性函數表示為輸出Y=1的概率(概念解釋和公式推導在后面)
Paste_Image.png
優(yōu)勢(odds)
事件發(fā)生的概率和不發(fā)生的概率比,即 P/(1-P)
優(yōu)勢比(odds ratio:OR)
衡量某個特征的兩個不同取值(C0,C1),對于結果的影響大小。OR>1事件發(fā)生概率大,是危險因素,OR<1事件發(fā)生概率小,是保護因素,OR=1該因素與事件發(fā)生無關
OR:odds ratio
logit變換
事件發(fā)生于事件未發(fā)生之比的自然對數,叫做P的logit變換,logit(P)
logit變換
logistic 函數
函數圖像為一個S形函數:sigmoid function
S形函數
利用極大似然發(fā)擬合最佳參數
似然函數可以理解為條件概率的逆反
已知事件Y發(fā)生,來估計參數x·w的最合理的可能,即計算能預測事件Y的最佳x·w的值.
帶入logistic模型得以下公式
似然函數
為了簡單求得最大值,我們使用對數似然函數
對數似然函數
轉換成代價函數
我們用一個梯度上升的方法來使對數似然函數最大化,我們將對數似然函數重寫成代價函數的模式,然后利用梯度下降的方法求代價最小對應的權值
代價函數,對數似然函數重寫而來
整理成更易于閱讀和理解的形式
代價函數
在預測y=0和y=1的情況下,如下圖公式所示
Paste_Image.png
代價函數如圖,預測準確的情況下誤差趨于0,預測錯誤就會趨于無窮
代價函數圖形
Code Time
繪制S函數
# 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型函數
Logistic 邏輯回歸函數
# encoding:utf-8
__author__ = 'M'
# 讀取數據
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:,[2,3]]
y = iris.target
# 訓練數據和測試數據分為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)
# 標準化數據
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):
# 設置標記點和顏色
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)
# 高粱所有的數據點
if test_idx:
# 繪制所有數據點
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')
# 應用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 回歸函數分類結果