小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

AI算法:邏輯回歸原理與實(shí)現(xiàn)

 禁忌石 2023-01-15 發(fā)布于浙江

1、算法思想

線性回歸可以對(duì)數(shù)據(jù)進(jìn)行線性擬合,擬合后的模型可以輸出連續(xù)的值。由于它沒有范圍,因此不適合與分類問題。邏輯回歸用于離散變量的分類問題,其輸出值為屬于某一類的概率,主要用于類的判別。

2、算法推導(dǎo)

2.1 邏輯回歸

對(duì)于線性回歸的預(yù)測(cè)函數(shù)為:

其中,

文章圖片1

圖1. sigmoid函數(shù)

文章圖片2

圖2. 邏輯回歸示意圖

由圖1所示:

當(dāng) 時(shí), ;

當(dāng) 時(shí), 。

因此,函數(shù)的輸出值在0-1之間。

對(duì)于邏輯回歸:

當(dāng) 時(shí) ,這時(shí)應(yīng)為類別1;

當(dāng) 時(shí) ,這時(shí)應(yīng)為類別0。

因此,預(yù)測(cè)輸出為在輸入與參數(shù)條件下預(yù)測(cè)類別為1的概率。

例如,對(duì)于給定的 所求得的概率為 ,則輸出類別1的概率為0.7,相應(yīng)的類別0的概率為0.3。

2.2 損失函數(shù)

對(duì)于線性回歸模型,我們定義的代價(jià)函數(shù)是所有模型誤差的平方和。理論上來說,我們也可以對(duì)邏輯回歸模型沿用這個(gè)定義,但是問題在于,當(dāng)我們將下述公式

帶入到線性回歸的損失函數(shù)中會(huì)得到圖3. 非凸函數(shù),梯度下降法會(huì)得到局部最小值。因此,需要重新設(shè)計(jì)損失函數(shù)。

文章圖片3

圖3. 非凸函數(shù)

采用BCE (Binary Cross Entropy)二分類交叉熵?fù)p失函數(shù)。

其中,

為樣本個(gè)數(shù)。

為類別1的真實(shí)值, 為類別0的預(yù)測(cè)值。

因此:

當(dāng)時(shí),

import numpy as npimport seabornimport matplotlib.pyplot as pltx = np.arange(0.1, 1, .01)y = -np.log(x)seaborn.lineplot(x=x, y=y)plt.show()
文章圖片4

圖4. 類別1損失函數(shù)

由圖4類別1的損失函數(shù),隨著預(yù)測(cè)值增加loss逐漸減小,預(yù)測(cè)值為1時(shí),loss=0。

當(dāng)y=0時(shí),

import numpy as npimport seabornimport matplotlib.pyplot as pltx = np.arange(0.1, 1, .01)y = -np.log(1-x)seaborn.lineplot(x=x, y=y)plt.show()
文章圖片5

圖5. 類別0損失函數(shù)

由圖5類別0的損失函數(shù),隨著預(yù)測(cè)值減小loss逐漸減小,預(yù)測(cè)值為時(shí),loss=0。

2.3 求解方法

文章圖片6
文章圖片7

?詳細(xì)推導(dǎo)如下:

文章圖片8

可以使用梯度下降法對(duì)參數(shù)進(jìn)行更新

3、算法實(shí)現(xiàn)

文章圖片9

?代碼如下:

(1)logistic_regression.py

# -*- coding: utf-8 -*-import numpy as npclass LogisticRegression(object): def __init__(self, learning_rate=0.1, max_iter=100, seed=None): self.seed = seed self.lr = learning_rate self.max_iter = max_iter def fit(self, x, y): np.random.seed(self.seed) self.w = np.random.normal(loc=0.0, scale=1.0, size=x.shape[1]) self.b = np.random.normal(loc=0.0, scale=1.0) self.x = x self.y = y for i in range(self.max_iter): self._update_step() # print('loss: \t{}'.format(self.loss())) # print('score: \t{}'.format(self.score())) # print('w: \t{}'.format(self.w)) # print('b: \t{}'.format(self.b)) def _sigmoid(self, z): return 1.0 / (1.0 + np.exp(-z)) def _f(self, x, w, b): z = x.dot(w) + b return self._sigmoid(z) def predict_proba(self, x=None): if x is None: x = self.x y_pred = self._f(x, self.w, self.b) return y_pred def predict(self, x=None): if x is None: x = self.x y_pred_proba = self._f(x, self.w, self.b) y_pred = np.array([0 if y_pred_proba[i] < 0.5 else 1 for i in range(len(y_pred_proba))]) return y_pred def score(self, y_true=None, y_pred=None): if y_true is None or y_pred is None: y_true = self.y y_pred = self.predict() acc = np.mean([1 if y_true[i] == y_pred[i] else 0 for i in range(len(y_true))]) return acc def loss(self, y_true=None, y_pred_proba=None): if y_true is None or y_pred_proba is None: y_true = self.y y_pred_proba = self.predict_proba() return np.mean(-1.0 * (y_true * np.log(y_pred_proba) + (1.0 - y_true) * np.log(1.0 - y_pred_proba))) def _calc_gradient(self): y_pred = self.predict() d_w = (y_pred - self.y).dot(self.x) / len(self.y) d_b = np.mean(y_pred - self.y) return d_w, d_b def _update_step(self): d_w, d_b = self._calc_gradient() self.w = self.w - self.lr * d_w self.b = self.b - self.lr * d_b return self.w, self.b

(2)train_test_lr.py

# -*- coding: utf-8 -*-import numpy as npimport matplotlib.pyplot as pltimport data_helperfrom logistic_regression import *# data generationx, y = data_helper.generate_data(seed=272)x_train, y_train, x_test, y_test = data_helper.train_test_split(x, y)# visualize data# plt.scatter(x_train[:,0], x_train[:,1], c=y_train, marker='.')# plt.show()# plt.scatter(x_test[:,0], x_test[:,1], c=y_test, marker='.')# plt.show()# data normalizationx_train = (x_train - np.min(x_train, axis=0)) / (np.max(x_train, axis=0) - np.min(x_train, axis=0))x_test = (x_test - np.min(x_test, axis=0)) / (np.max(x_test, axis=0) - np.min(x_test, axis=0))# Logistic regression classifierclf = LogisticRegression(learning_rate=0.1, max_iter=500, seed=272)clf.fit(x_train, y_train)# plot the resultsplit_boundary_func = lambda x: (-clf.b - clf.w[0] * x) / clf.w[1]xx = np.arange(0.1, 0.6, 0.1)plt.scatter(x_train[:,0], x_train[:,1], c=y_train, marker='.')plt.plot(xx, split_boundary_func(xx), c='red')plt.show()# loss on test sety_test_pred = clf.predict(x_test)y_test_pred_proba = clf.predict_proba(x_test)print(clf.score(y_test, y_test_pred))print(clf.loss(y_test, y_test_pred_proba))# print(y_test_pred_proba)

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多