機器學習 - 邏輯迴歸



邏輯迴歸是一種常用的用於二元分類問題的演算法,其中目標變數是具有兩個類別的分類變數。它對給定輸入特徵的目標變數的機率進行建模,並預測機率最高的類別。

邏輯迴歸是一種廣義線性模型,其中目標變數遵循伯努利分佈。該模型由輸入特徵的線性函式組成,該函式使用邏輯函式進行轉換以生成 0 到 1 之間的機率值。

線性函式基本上用作另一個函式(例如以下關係中的 g)的輸入:

$$h_{\theta }\left ( x \right )=g\left ( \theta ^{T}x \right )\, 其中\: 0\leq h_{\theta }\leq 1$$

這裡,g 是邏輯或 sigmoid 函式,可以表示如下:

$$g\left ( z \right )=\frac{1}{1+e^{-z}}\: 其中\: z=\theta ^{T}x$$

可以使用以下圖形表示 sigmoid 曲線。我們可以看到 y 軸的值介於 0 和 1 之間,並在 0.5 處穿過軸。

sigmoid curve

這些類別可以分為正類或負類。如果輸出介於 0 和 1 之間,則輸出屬於正類的機率。在我們的實現中,如果假設函式的輸出≥ 0.5,則將其解釋為正類,否則解釋為負類。

Python 實現

現在,我們將使用 Python 實現上述邏輯迴歸的概念。為此,我們使用名為“iris”的多元花卉資料集。iris 資料集是機器學習中一個眾所周知的資料集,包含三種不同鳶尾花物種的花萼長度、花萼寬度、花瓣長度和花瓣寬度的測量值。我們將使用邏輯迴歸來預測給定鳶尾花測量值的鳶尾花物種。

現在讓我們檢查使用 iris 資料集在 Python 中實現邏輯迴歸的步驟:

載入資料集

首先,我們需要將 iris 資料集載入到我們的 Python 環境中。我們可以使用 scikitlearn 庫載入資料集,如下所示:

from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data # input features
y = iris.target # target variable

繪製訓練資料

這是一個可選步驟,但為了更清楚地瞭解資料集,我們正在繪製訓練資料,如下所示:

import matplotlib.pyplot as plt

# plot the training data
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
plt.xlabel('Sepal length (cm)')
plt.ylabel('Sepal width (cm)')
plt.title('Iris Training Data')
plt.show()

分割資料集

接下來,我們需要將資料集分割成訓練集和測試集。我們將使用 70% 的資料進行訓練,30% 的資料進行測試。

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

建立邏輯迴歸模型

我們可以使用 scikit-learn 中的 LogisticRegression 類來建立一個邏輯迴歸模型。我們將使用 L2 正則化並將正則化強度設定為 1。

from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(penalty='l2', C=1.0, random_state=42)

訓練模型

我們可以使用 fit() 方法在訓練集上訓練模型。

clf.fit(X_train, y_train)

進行預測

訓練完模型後,我們可以使用 predict() 方法在測試集上使用它進行預測。

y_pred = clf.predict(X_test)

評估模型

最後,我們可以使用準確率、精確率、召回率和 F1 分數等指標來評估模型的效能。

from sklearn.metrics import accuracy_score, precision_score,
recall_score, f1_score
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Precision:', precision_score(y_test, y_pred, average='macro'))
print('Recall:', recall_score(y_test, y_pred, average='macro'))
print('F1-score:', f1_score(y_test, y_pred, average='macro'))

在這裡,我們使用平均引數並將值設定為“macro”來分別計算每個類別的指標,然後取平均值。

完整的實現示例

下面是使用 iris 資料集在 python 中實現邏輯迴歸的完整實現示例:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

# load the iris dataset
iris = load_iris()
X = iris.data # input features
y = iris.target # target variable

# plot the training data
plt.figure(figsize=(7.5, 3.5))
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)
plt.xlabel('Sepal length (cm)')
plt.ylabel('Sepal width (cm)')
plt.title('Iris Training Data')
plt.show()

# split the dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# create the logistic regression model
clf = LogisticRegression(penalty='l2', C=1.0, random_state=42)

# train the model on the training set
clf.fit(X_train, y_train)

# make predictions on the test set
y_pred = clf.predict(X_test)

# evaluate the performance of the model
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Precision:', precision_score(y_test, y_pred, average='macro'))
print('Recall:', recall_score(y_test, y_pred, average='macro'))
print('F1-score:', f1_score(y_test, y_pred, average='macro'))

輸出

執行此程式碼時,它將生成以下繪圖作為輸出:

Accuracy: 1.0
Precision: 1.0
Recall: 1.0
F1-score: 1.0
iris Traning data
廣告