<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【機(jī)器學(xué)習(xí)基礎(chǔ)】數(shù)學(xué)推導(dǎo)+純Python實(shí)現(xiàn)機(jī)器學(xué)習(xí)算法10:線性不可分支持向量機(jī)

          共 8206字,需瀏覽 17分鐘

           ·

          2022-08-08 19:53

          點(diǎn)擊上方小白學(xué)視覺”,選擇加"星標(biāo)"或“置頂

          重磅干貨,第一時(shí)間送達(dá)

               本節(jié)筆者和大家討論支持向量機(jī)的最后一種情況——非線性支持向量機(jī)。前面兩節(jié)我們探討了數(shù)據(jù)樣例是完全線性可分情況和近似線性可分情況下的支持向量機(jī)模型。但線性可分情況并非總?cè)缛嗽?,大多?shù)時(shí)候我們遇到的都是非線性情況。


               

               所謂非線性可分問題,就是對于給定數(shù)據(jù)集,如果能用一個(gè)超曲面將正負(fù)實(shí)例正確分開,則這個(gè)問題為非線性可分問題。非線性問題的一個(gè)關(guān)鍵在于將原始數(shù)據(jù)空間轉(zhuǎn)換到一個(gè)新的數(shù)據(jù)空間,在原始空間中的非線性可分問題到新空間就是是線性可分問題。


               一般來說,用線性可分方法來解決非線性可分問題可分為兩步:首先用一個(gè)變換將原始空間的數(shù)據(jù)映射到新空間,再在新空間中用線性分類學(xué)習(xí)方法訓(xùn)練分類模型。這種將原始空間轉(zhuǎn)換到新空間的方法稱為核技巧(kernel trick)。



               假設(shè)存在一個(gè)從輸入空間到特征空間的映射,使得所有的x和z都有函數(shù)K(x,z)=&(x).&(z),則稱K(x,z)為核函數(shù)。在實(shí)際問題中,通常直接給定核函數(shù)的形式,然后進(jìn)行求解。核函數(shù)的選擇通常依賴于領(lǐng)域知識,最后由實(shí)驗(yàn)驗(yàn)證其有效性。常用的核函數(shù)包括多項(xiàng)式核函數(shù)、高斯核函數(shù)以及sigmoid核函數(shù)等,核函數(shù)更多細(xì)節(jié)問題可參考統(tǒng)計(jì)學(xué)習(xí)方法。


               基于核函數(shù)的非線性支持向量機(jī)對偶優(yōu)化問題如下:

               當(dāng)核函數(shù)為正定核的時(shí)候,上述優(yōu)化問題為凸優(yōu)化問題,是可以直接進(jìn)行求解的。可求得最優(yōu)解:

               計(jì)算w如下:

               最后可構(gòu)造分類決策函數(shù):

               雖然凸優(yōu)化問題可以直接求解,但當(dāng)數(shù)據(jù)量很大時(shí),直接求解將會非常低效,這時(shí)候可能需要一些高效的訓(xùn)練算法,比如說SMO(序列最小最優(yōu)化)算法。關(guān)于SMO算法的內(nèi)容這里不展開敘述,可參考統(tǒng)計(jì)學(xué)習(xí)方法了解更多內(nèi)容。


          下面來看基于cvxopt的非線性支持向量機(jī)快速實(shí)現(xiàn)方法。

          導(dǎo)入相關(guān)package:

          import numpy as npfrom numpy import linalgimport cvxoptimport cvxopt.solversimport pylab as pl

          定義多項(xiàng)式核函數(shù)如下:

          def polynomial_kernel(x, y, p=3):    return (1 + np.dot(x, y)) ** p

          生成示例數(shù)據(jù):

          def gen_non_lin_separable_data():    mean1 = [-1, 2]    mean2 = [1, -1]    mean3 = [4, -4]    mean4 = [-4, 4]    cov = [[1.0, 0.8], [0.8, 1.0]]    X1 = np.random.multivariate_normal(mean1, cov, 50)    X1 = np.vstack((X1, np.random.multivariate_normal(mean3, cov, 50)))    y1 = np.ones(len(X1))    X2 = np.random.multivariate_normal(mean2, cov, 50)    X2 = np.vstack((X2, np.random.multivariate_normal(mean4, cov, 50)))    y2 = np.ones(len(X2)) * -1    return X1, y1, X2, y2

          然后是構(gòu)建非線性支持向量機(jī)模型,完整版代碼如下:

          import numpy as npfrom numpy import linalgimport cvxoptimport cvxopt.solvers
          def polynomial_kernel(x, y, p=3): return (1 + np.dot(x, y)) ** p
          class nolinear_svm(object): def __init__(self, kernel=linear_kernel, C=None): self.kernel = kernel self.C = C if self.C is not None: self.C = float(self.C) def fit(self, X, y): n_samples, n_features = X.shape # Gram 矩陣 K = np.zeros((n_samples, n_samples)) for i in range(n_samples): for j in range(n_samples): K[i, j] = self.kernel(X[i], X[j]) P = cvxopt.matrix(np.outer(y, y) * K) q = cvxopt.matrix(np.ones(n_samples) * -1) A = cvxopt.matrix(y, (1, n_samples)) b = cvxopt.matrix(0.0) if self.C is None: G = cvxopt.matrix(np.diag(np.ones(n_samples) * -1)) h = cvxopt.matrix(np.zeros(n_samples)) else: tmp1 = np.diag(np.ones(n_samples) * -1) tmp2 = np.identity(n_samples) G = cvxopt.matrix(np.vstack((tmp1, tmp2))) tmp1 = np.zeros(n_samples) tmp2 = np.ones(n_samples) * self.C h = cvxopt.matrix(np.hstack((tmp1, tmp2))) # 求解二次規(guī)劃 solution = cvxopt.solvers.qp(P, q, G, h, A, b) # 獲得拉格朗日乘子 a = np.ravel(solution['x']) # 非零拉格朗日乘子的支持向量 sv = a > 1e-5 ind = np.arange(len(a))[sv] self.a = a[sv] self.sv = X[sv] self.sv_y = y[sv] print("%d support vectors out of %d points" % (len(self.a), n_samples)) # 截距項(xiàng) self.b = 0 for n in range(len(self.a)): self.b += self.sv_y[n] self.b -= np.sum(self.a * self.sv_y * K[ind[n], sv]) self.b /= len(self.a) # 權(quán)重參數(shù)向量 if self.kernel == linear_kernel: self.w = np.zeros(n_features) for n in range(len(self.a)): self.w += self.a[n] * self.sv_y[n] * self.sv[n] else: self.w = None # 預(yù)測函數(shù) def project(self, X): if self.w is not None: return np.dot(X, self.w) + self.b else: y_predict = np.zeros(len(X)) for i in range(len(X)): s = 0 for a, sv_y, sv in zip(self.a, self.sv_y, self.sv): s += a * sv_y * self.kernel(X[i], sv) y_predict[i] = s return y_predict + self.b def predict(self, X): return np.sign(self.project(X))

          if __name__ == "__main__": def gen_non_lin_separable_data(): mean1 = [-1, 2] mean2 = [1, -1] mean3 = [4, -4] mean4 = [-4, 4] cov = [[1.0, 0.8], [0.8, 1.0]] X1 = np.random.multivariate_normal(mean1, cov, 50) X1 = np.vstack((X1, np.random.multivariate_normal(mean3, cov, 50))) y1 = np.ones(len(X1)) X2 = np.random.multivariate_normal(mean2, cov, 50) X2 = np.vstack((X2, np.random.multivariate_normal(mean4, cov, 50))) y2 = np.ones(len(X2)) * -1 return X1, y1, X2, y2 def split_train(X1, y1, X2, y2): X1_train = X1[:90] y1_train = y1[:90] X2_train = X2[:90] y2_train = y2[:90] X_train = np.vstack((X1_train, X2_train)) y_train = np.hstack((y1_train, y2_train)) return X_train, y_train def split_test(X1, y1, X2, y2): X1_test = X1[90:] y1_test = y1[90:] X2_test = X2[90:] y2_test = y2[90:] X_test = np.vstack((X1_test, X2_test)) y_test = np.hstack((y1_test, y2_test)) return X_test, y_test def plot_margin(X1_train, X2_train, clf): def f(x, w, b, c=0): return (-w[0] * x - b + c) / w[1] pl.plot(X1_train[:, 0], X1_train[:, 1], "ro") pl.plot(X2_train[:, 0], X2_train[:, 1], "bo") pl.scatter(clf.sv[:, 0], clf.sv[:, 1], s=100, c="g") # w.x + b = 0 a0 = -4; a1 = f(a0, clf.w, clf.b) b0 = 4; b1 = f(b0, clf.w, clf.b) pl.plot([a0, b0], [a1, b1], "k") # w.x + b = 1 a0 = -4; a1 = f(a0, clf.w, clf.b, 1) b0 = 4; b1 = f(b0, clf.w, clf.b, 1) pl.plot([a0, b0], [a1, b1], "k--") # w.x + b = -1 a0 = -4; a1 = f(a0, clf.w, clf.b, -1) b0 = 4; b1 = f(b0, clf.w, clf.b, -1) pl.plot([a0, b0], [a1, b1], "k--") pl.axis("tight") pl.show() def plot_contour(X1_train, X2_train, clf): pl.plot(X1_train[:, 0], X1_train[:, 1], "ro") pl.plot(X2_train[:, 0], X2_train[:, 1], "bo") pl.scatter(clf.sv[:, 0], clf.sv[:, 1], s=100, c="g") X1, X2 = np.meshgrid(np.linspace(-6, 6, 50), np.linspace(-6, 6, 50)) X = np.array([[x1, x2] for x1, x2 in zip(np.ravel(X1), np.ravel(X2))]) Z = clf.project(X).reshape(X1.shape) pl.contour(X1, X2, Z, [0.0], colors='k', linewidths=1, origin='lower') pl.contour(X1, X2, Z + 1, [0.0], colors='grey', linewidths=1, origin='lower') pl.contour(X1, X2, Z - 1, [0.0], colors='grey', linewidths=1, origin='lower') pl.axis("tight") pl.show() def test_non_linear(): X1, y1, X2, y2 = gen_non_lin_separable_data() X_train, y_train = split_train(X1, y1, X2, y2) X_test, y_test = split_test(X1, y1, X2, y2) clf = nolinear_svm(polynomial_kernel) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) correct = np.sum(y_predict == y_test) print("%d out of %d predictions correct" % (correct, len(y_predict))) plot_contour(X_train[y_train == 1], X_train[y_train == -1], clf) test_non_linear()

          基于多項(xiàng)式核函數(shù)的非線性支持向量機(jī)分類效果如下:

               以上就是本節(jié)內(nèi)容,關(guān)于支持向量機(jī)的部分內(nèi)容,筆者就簡單寫到這里,下一講我們來看看樸素貝葉斯算法。完整代碼文件和數(shù)據(jù)可參考筆者GitHub地址:

          https://github.com/luwill/machine-learning-code-writing

          好消息!

          小白學(xué)視覺知識星球

          開始面向外開放啦??????




          下載1:OpenCV-Contrib擴(kuò)展模塊中文版教程
          在「小白學(xué)視覺」公眾號后臺回復(fù):擴(kuò)展模塊中文教程,即可下載全網(wǎng)第一份OpenCV擴(kuò)展模塊教程中文版,涵蓋擴(kuò)展模塊安裝、SFM算法、立體視覺、目標(biāo)跟蹤、生物視覺、超分辨率處理等二十多章內(nèi)容。

          下載2:Python視覺實(shí)戰(zhàn)項(xiàng)目52講
          小白學(xué)視覺公眾號后臺回復(fù):Python視覺實(shí)戰(zhàn)項(xiàng)目,即可下載包括圖像分割、口罩檢測、車道線檢測、車輛計(jì)數(shù)、添加眼線、車牌識別、字符識別、情緒檢測、文本內(nèi)容提取、面部識別等31個(gè)視覺實(shí)戰(zhàn)項(xiàng)目,助力快速學(xué)校計(jì)算機(jī)視覺。

          下載3:OpenCV實(shí)戰(zhàn)項(xiàng)目20講
          小白學(xué)視覺公眾號后臺回復(fù):OpenCV實(shí)戰(zhàn)項(xiàng)目20講,即可下載含有20個(gè)基于OpenCV實(shí)現(xiàn)20個(gè)實(shí)戰(zhàn)項(xiàng)目,實(shí)現(xiàn)OpenCV學(xué)習(xí)進(jìn)階。

          交流群


          歡迎加入公眾號讀者群一起和同行交流,目前有SLAM、三維視覺、傳感器、自動駕駛、計(jì)算攝影、檢測、分割、識別、醫(yī)學(xué)影像、GAN算法競賽等微信群(以后會逐漸細(xì)分),請掃描下面微信號加群,備注:”昵稱+學(xué)校/公司+研究方向“,例如:”張三 + 上海交大 + 視覺SLAM“。請按照格式備注,否則不予通過。添加成功后會根據(jù)研究方向邀請進(jìn)入相關(guān)微信群。請勿在群內(nèi)發(fā)送廣告,否則會請出群,謝謝理解~


          瀏覽 47
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产鸡巴视频 | 一区二区三区综合 | 91大神免费视频在线观看 | 国产精品观看 | 91成人在线免费电影 |