python離散建模之感知器學習算法
我們將研究一種判別式分類方法,其中直接學習評估 g(x)所需的 w 參數(shù)。我們將使用感知器學習算法。
感知器學習算法很容易實現(xiàn),但為了節(jié)省時間,我在下面為您提供了一個實現(xiàn)。該函數(shù)有幾個輸入:訓練數(shù)據(jù)、訓練標簽、對權(quán)重的初始猜測和學習率。注意,對于這兩個類,類標簽的值必須為+1和-1。
它將返回一個元組,其中包含:
- 1.學習w參數(shù)
- 2.執(zhí)行的迭代次數(shù)
- 3.錯誤分類的樣本數(shù)
花些時間檢查代碼。如果不清楚每一行是如何工作的,不要擔心,只要讓你自己知道每一行的目的是什么就可以了。代碼中有一些注釋可以幫助大家。
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ù)矩陣。每行代表一個單獨的樣本
y-與X-標簽行對應的整數(shù)類標簽的一維數(shù)組必須為+1或-1
w_init-初始權(quán)重向量
rho-標量學習率
最大迭代次數(shù)-最大迭代次數(shù)(默認為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)
- 感知器算法的高效實現(xiàn)
- 對于筆記本電腦數(shù)據(jù),此版本的工作速度將提高x100!
到此這篇關于python離散建模之感知器學習算法的文章就介紹到這了,更多相關python感知器學習算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python之標點符號string.punctuation的使用
Python的string模塊提供了一個方便的屬性string.punctuation,其中包含所有ASCII標點符號字符,這使得在處理和識別字符串中的標點符號時非常有用,可以通過簡單的in關鍵字來檢測字符是否為標點2024-09-09
python PaddleSpeech實現(xiàn)嬰兒啼哭識別
這篇文章主要為大家介紹了python PaddleSpeech實現(xiàn)嬰兒啼哭識別操作詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
python使用fcntl模塊實現(xiàn)程序加鎖功能示例
利用django創(chuàng)建一個簡易的博客網(wǎng)站的示例
python 實現(xiàn)自動遠程登陸scp文件實例代碼
利用python在Word文檔中創(chuàng)建和執(zhí)行條件郵件合并

