1. 程式人生 > >Logistic Regression 邏輯迴歸演算法例子,python程式碼實現

Logistic Regression 邏輯迴歸演算法例子,python程式碼實現

轉載自原文

邏輯迴歸 Logistic Regression

雖然名字叫做邏輯迴歸 Logistic regression ,但它是一種分類演算法。對於文字處理方便,邏輯迴歸是一種非常強大的分類器。它主要通過在邏輯函式上執行迴歸來實現,正如其名字。

邏輯迴歸的一個小例子

如下圖,紅色表示分類1,藍色表示分類為0.但是對於特徵,橫座標上有一個區間既可以分到1也可以分到0。遇到這種情況,最好能用概率來表示分到某一類的可能性,而不是用離散的方式來表示0或1。 邏輯迴歸示例

在數學上,向來都是很難設定模型的邊界,像本例中的0和1。但是我們可以經過一些處理,使得分類的概率值落在0和1之間。

如果一個數據有0.9的可能性是屬於分類1的,我們可以認為其有9:1的可能性將該資料分類為1。如果另一個數據有0.5的可能性分類為1,則認為有1:1的可能性將資料的分類為1。這種odd的表達方式的範圍是0到無窮大。如果將odd加上log,取對數。則可以將odd的範圍對映到0和1 之間。這樣就實現了將離散的分類值轉換成連續的概率值的對映。

邏輯迴歸曲線

取對數之後的曲線:

邏輯迴歸對數曲線

邏輯迴歸python程式碼

使用 scipy.stats的norm.rvs產生隨機數,引數loc表示平均數,scale表示標準差,size是樣本量

np.hstack合併兩個陣列

import os
from data import CHART_DIR

import numpy as np
from scipy.stats import norm

from matplotlib import pyplot
np.random.seed(3)

num_per_class = 40
#生成樣本
X = np.hstack((norm.rvs(2, size=num_per_class, scale=2),
              norm.rvs(8, size=num_per_class, scale=3)))
y = np.hstack((np.zeros(num_per_class),
               np.ones(num_per_class)))


def lr_model(clf, X):
    return 1.0 / (1.0 + np.exp(-(clf.intercept_ + clf.coef_ * X)))

from sklearn.linear_model import LogisticRegression
logclf = LogisticRegression()
print(logclf)
logclf.fit(X.reshape(num_per_class * 2, 1), y)
print(np.exp(logclf.intercept_), np.exp(logclf.coef_.ravel()))
print("P(x=-1)=%.2f\tP(x=7)=%.2f" %
      (lr_model(logclf, -1), lr_model(logclf, 7)))
X_test = np.arange(-5, 20, 0.1)
pyplot.figure(figsize=(10, 4))
pyplot.xlim((-5, 20))
pyplot.scatter(X, y, c=y)
pyplot.xlabel("feature value")
pyplot.ylabel("class")
pyplot.grid(True, linestyle='-', color='0.75')
pyplot.savefig(
    os.path.join(CHART_DIR, "log_reg_example_data.png"), bbox_inches="tight")


def lin_model(clf, X):
    return clf.intercept_ + clf.coef_ * X

from sklearn.linear_model import LinearRegression
clf = LinearRegression()
print(clf)
clf.fit(X.reshape(num_per_class * 2, 1), y)
X_odds = np.arange(0, 1, 0.001)
pyplot.figure(figsize=(10, 4))
pyplot.subplot(1, 2, 1)
pyplot.scatter(X, y, c=y)
pyplot.plot(X_test, lin_model(clf, X_test))
pyplot.xlabel("feature value")
pyplot.ylabel("class")
pyplot.title("linear fit on original data")
pyplot.grid(True, linestyle='-', color='0.75')

X_ext = np.hstack((X, norm.rvs(20, size=100, scale=5)))
y_ext = np.hstack((y, np.ones(100)))
clf = LinearRegression()
clf.fit(X_ext.reshape(num_per_class * 2 + 100, 1), y_ext)
pyplot.subplot(1, 2, 2)
pyplot.scatter(X_ext, y_ext, c=y_ext)
pyplot.plot(X_ext, lin_model(clf, X_ext))
pyplot.xlabel("feature value")
pyplot.ylabel("class")
pyplot.title("linear fit on additional data")
pyplot.grid(True, linestyle='-', color='0.75')
pyplot.savefig(
    os.path.join(CHART_DIR, "log_reg_log_linear_fit.png"), bbox_inches="tight")

pyplot.figure(figsize=(10, 4))
pyplot.xlim((-5, 20))
pyplot.scatter(X, y, c=y)
pyplot.plot(X_test, lr_model(logclf, X_test).ravel())
pyplot.plot(X_test, np.ones(X_test.shape[0]) * 0.5, "--")
pyplot.xlabel("feature value")
pyplot.ylabel("class")
pyplot.grid(True, linestyle='-', color='0.75')
pyplot.savefig(
    os.path.join(CHART_DIR, "log_reg_example_fitted.png"), bbox_inches="tight")

X = np.arange(0, 1, 0.001)
pyplot.figure(figsize=(10, 4))
pyplot.subplot(1, 2, 1)
pyplot.xlim((0, 1))
pyplot.ylim((0, 10))
pyplot.plot(X, X / (1 - X))
pyplot.xlabel("P")
pyplot.ylabel("odds = P / (1-P)")
pyplot.grid(True, linestyle='-', color='0.75')

pyplot.subplot(1, 2, 2)
pyplot.xlim((0, 1))
pyplot.plot(X, np.log(X / (1 - X)))
pyplot.xlabel("P")
pyplot.ylabel("log(odds) = log(P / (1-P))")
pyplot.grid(True, linestyle='-', color='0.75')
pyplot.savefig(
    os.path.join(CHART_DIR, "log_reg_log_odds.png"), bbox_inches="tight")