非線性邏輯迴歸的梯度下降算法python實現以及決策邊界的繪製

非線性邏輯迴歸的梯度下降算法python實現以及決策邊界的繪製

前言: 對於邏輯迴歸的決策邊界有很多並不是線性的而是非線性的,那麼這樣我就需要訓練非線性的邏輯迴歸,如何訓練非線性的邏輯迴歸呢?仍然利用sklearn的特徵轉換思路,將非線性問題轉爲線性問題進行解決,具體思路參考我這篇博文,關乎邏輯迴歸的理論知識 參考我這篇博文

一、非線性邏輯迴歸解決分類問題Demo

import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report
from sklearn import preprocessing
from sklearn.preprocessing import PolynomialFeatures

# 數據是否需要標準化
scale = False

# 讀取數據
data = np.genfromtxt('LR-testSet2.txt', delimiter=',')
x_data = data[:, 0:-1]
y_data = data[:, -1, np.newaxis]

# 繪製各類別的數據散點圖
def plotClass():
    x0 = []
    y0 = []
    x1 = []
    y1 = []
    for i in range(len(x_data)):
        if y_data[i] == 0:
            x0.append(x_data[i, 0])
            y0.append(x_data[i, 1])
        else:
            x1.append(x_data[i, 0])
            y1.append(x_data[i, 1])

    # 繪圖
    s1 = plt.scatter(x0, y0, c='b', marker='o')
    s2 = plt.scatter(x1, y1, c='r', marker='x')
    plt.legend(handles=[s1, s2], labels=['class0', 'class1'])


# 定義多項式迴歸,degree的值可以調節多項式的特徵
poly_reg = PolynomialFeatures(degree=3)  # 得到非線性方程y = theta0+theta1*x1+theta2*x1^2+theta3*x1*x2+theta4*x^2所需的樣本數據
# 特徵處理(獲取多項式相應特徵所對應的樣本數據)
x_poly = poly_reg.fit_transform(x_data)

# 定義邏輯迴歸的模型函數(S型函數)
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

# 計算代價值
def cost(xMat, yMat, ws):
    left = np.multiply(yMat, np.log(sigmoid(xMat * ws)))
    right = np.multiply(1 - yMat, np.log(1 - sigmoid(xMat * ws)))
    return np.sum(left + right) / -len(xMat)

# 梯度下降算法
def gradAscent(xArr, yArr):
    if scale:
        xArr = preprocessing.scale(xArr)
    xMat = np.mat(xArr)
    yMat = np.mat(yArr)

    # 學習率
    lr = 0.03
    # 梯度下降迭代次數
    ite = 50000
    # 記錄梯度下降過程中的代價值
    costList = []
    # 計算數據行列數
    m, n = np.shape(xMat)
    # 初始化線性函數權重
    ws = np.mat(np.ones((n, 1)))
    for i in range(ite + 1):
        h = sigmoid(xMat * ws)
        ws_grad = xMat.T * (h - yMat) / m
        ws = ws - lr * ws_grad
        if i % 50 == 0:
            costList.append(cost(xMat, yMat, ws))
    return ws, costList

# 訓練模型
ws, costList = gradAscent(x_poly, y_data)
# 獲取數據值所在的範圍
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1

# 生成網格矩陣
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
# 測試點的預測值
z = sigmoid(poly_reg.fit_transform(np.c_[xx.ravel(), yy.ravel()]).dot(np.array(ws)))
print(xx.shape)
print(len(z))
for i in range(len(z)):
    if z[i] > 0.5:
        z[i] = 1
    else:
        z[i] = 0

z = z.reshape(xx.shape)
# 繪製等高線圖
cs = plt.contourf(xx, yy, z)
plotClass()

# 根據訓練的模型進行預測類型
def predict(x_data, ws):
    if scale:
        x_data = preprocessing.scale(x_data)
    xMat = np.mat(x_data)
    ws = np.mat(ws)
    return [1 if x >= 0.5 else 0 for x in sigmoid(xMat * ws)]

predictions = predict(x_poly, ws)
# 計算準確率,召回率,F1值
print(classification_report(y_data, predictions))
plt.show()

二、執行結果

precision    recall  f1-score   support

         0.0       0.86      0.83      0.85        60
         1.0       0.83      0.86      0.85        58

   micro avg       0.85      0.85      0.85       118
   macro avg       0.85      0.85      0.85       118
weighted avg       0.85      0.85      0.85       118

在這裏插入圖片描述
三、數據下載
鏈接:https://pan.baidu.com/s/1Lvrzw7s0d4F5jB7SVlkJzg
提取碼:q3uv

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章