日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python離散建模之感知器學(xué)習(xí)算法_python

作者:努力奮斗的K崽 ? 更新時(shí)間: 2022-04-21 編程語言

我們將研究一種判別式分類方法,其中直接學(xué)習(xí)評(píng)估 g(x)所需的 w 參數(shù)。我們將使用感知器學(xué)習(xí)算法。
感知器學(xué)習(xí)算法很容易實(shí)現(xiàn),但為了節(jié)省時(shí)間,我在下面為您提供了一個(gè)實(shí)現(xiàn)。該函數(shù)有幾個(gè)輸入:訓(xùn)練數(shù)據(jù)、訓(xùn)練標(biāo)簽、對(duì)權(quán)重的初始猜測(cè)和學(xué)習(xí)率。注意,對(duì)于這兩個(gè)類,類標(biāo)簽的值必須為+1和-1。

它將返回一個(gè)元組,其中包含:

  • 1.學(xué)習(xí)w參數(shù)
  • 2.執(zhí)行的迭代次數(shù)
  • 3.錯(cuò)誤分類的樣本數(shù)

花些時(shí)間檢查代碼。如果不清楚每一行是如何工作的,不要擔(dān)心,只要讓你自己知道每一行的目的是什么就可以了。代碼中有一些注釋可以幫助大家。

def perce(X, y, w_init, rho, max_iter=1000):
? ??
? ? (N, nfeatures) = X.shape

? ? # Augment the feature vectors by adding a 1 to each one. (see lecture notes)
? ? X = np.hstack((X, np.ones((N, 1))))
? ? nfeatures += 1

? ? w = w_init ?# initialise weights
? ? iter = 0
? ? mis_class = N ?# start by assuming all samples are misclassified

? ? while mis_class > 0 and iter < max_iter:
? ? ? ? iter += 1
? ? ? ? mis_class = 0
? ? ? ? gradient = np.zeros(nfeatures) ?# initaliase the gradients to 0

? ? ? ? # loop over every training sample.
? ? ? ? for i in range(N):
? ? ? ? ? ? # each misclassified point will cause the gradient to change
? ? ? ? ? ? if np.inner(X[i, :], w) * y[i] <= 0:
? ? ? ? ? ? ? ? mis_class += 1
? ? ? ? ? ? ? ? gradient += -y[i] * X[i, :]
? ? ? ? # update the weight vector ready for the next iteration
? ? ? ? # Note, also that the learning rate decays over time (rho/iter)
? ? ? ? w -= rho / iter * gradient

? ? return w, iter, mis_class

解釋:

X-數(shù)據(jù)矩陣。每行代表一個(gè)單獨(dú)的樣本
y-與X-標(biāo)簽行對(duì)應(yīng)的整數(shù)類標(biāo)簽的一維數(shù)組必須為+1或-1
w_init-初始權(quán)重向量
rho-標(biāo)量學(xué)習(xí)率
最大迭代次數(shù)-最大迭代次數(shù)(默認(rèn)為1000)

def perce_fast(X, y, w_init, rho, max_iter=10000):
??
? ? (N, nfeatures) = X.shape
? ? X = np.hstack((X, np.ones((N, 1))))
? ? nfeatures += 1
? ? w = w_init
? ? iter = 0
? ? mis_class = N
? ? yy = np.tile(y, (nfeatures, 1)).T
? ? while mis_class > 0 and iter < max_iter:
? ? ? ? iter += 1
? ? ? ? # Compute set of misclassified points
? ? ? ? mc = (np.dot(X, w.transpose()) * y) <= 0
? ? ? ? mis_class = np.sum(mc)
? ? ? ? # Update weights. Note, the learning rate decays over time (rho/iter)
? ? ? ? w -= rho / iter * (np.sum(-yy[mc, :] * X[mc, :], axis=0))
? ? return w, iter, np.sum(mc)
  • 感知器算法的高效實(shí)現(xiàn)
  • 對(duì)于筆記本電腦數(shù)據(jù),此版本的工作速度將提高x100!

原文鏈接:https://blog.csdn.net/kirsten111111/article/details/121429528

欄目分類
最近更新