python實現(xiàn)神經(jīng)網(wǎng)絡(luò)感知器算法
現(xiàn)在我們用python代碼實現(xiàn)感知器算法。
# -*- coding: utf-8 -*- import numpy as np class Perceptron(object): """ eta:學(xué)習(xí)率 n_iter:權(quán)重向量的訓(xùn)練次數(shù) w_:神經(jīng)分叉權(quán)重向量 errors_:用于記錄神經(jīng)元判斷出錯次數(shù) """ def __init__(self, eta=0.01, n_iter=2): self.eta = eta self.n_iter = n_iter pass def fit(self, X, y): """ 輸入訓(xùn)練數(shù)據(jù)培訓(xùn)神經(jīng)元 X:神經(jīng)元輸入樣本向量 y: 對應(yīng)樣本分類 X:shape[n_samples,n_features] x:[[1,2,3],[4,5,6]] n_samples = 2 元素個數(shù) n_features = 3 子向量元素個數(shù) y:[1,-1] 初始化權(quán)重向量為0 加一是因為前面算法提到的w0,也就是步調(diào)函數(shù)閾值 """ self.w_ = np.zeros(1 + X.shape[1]) self.errors_ = [] for _ in range(self.n_iter): errors = 0 """ zip(X,y) = [[1,2,3,1],[4,5,6,-1]] xi是前面的[1,2,3] target是后面的1 """ for xi, target in zip(X, y): """ predict(xi)是計算出來的分類 """ update = self.eta * (target - self.predict(xi)) self.w_[1:] += update * xi self.w_[0] += update print update print xi print self.w_ errors += int(update != 0.0) self.errors_.append(errors) pass def net_input(self, X): """ z = w0*1+w1*x1+....Wn*Xn """ return np.dot(X, self.w_[1:]) + self.w_[0] def predict(self, X): return np.where(self.net_input(X) >= 0, 1, -1) if __name__ == '__main__': datafile = '../data/iris.data.csv' import pandas as pd df = pd.read_csv(datafile, header=None) import matplotlib.pyplot as plt import numpy as np y = df.loc[0:100, 4].values y = np.where(y == "Iris-setosa", 1, -1) X = df.iloc[0:100, [0, 2]].values # plt.scatter(X[:50, 0], X[:50, 1], color="red", marker='o', label='setosa') # plt.scatter(X[50:100, 0], X[50:100, 1], color="blue", marker='x', label='versicolor') # plt.xlabel("hblength") # plt.ylabel("hjlength") # plt.legend(loc='upper left') # plt.show() pr = Perceptron() pr.fit(X, y)
其中數(shù)據(jù)為
控制臺輸出為
你們跑代碼的時候把n_iter設(shè)置大點,我這邊是為了看每次執(zhí)行for循環(huán)時方便查看數(shù)據(jù)變化。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python數(shù)據(jù)類型強制轉(zhuǎn)換實例詳解
這篇文章主要介紹了python數(shù)據(jù)類型強制轉(zhuǎn)換實例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06Pandas DataFrame數(shù)據(jù)的更改、插入新增的列和行的方法
這篇文章主要介紹了Pandas DataFrame數(shù)據(jù)的更改、插入新增的列和行的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06對Python的zip函數(shù)妙用,旋轉(zhuǎn)矩陣詳解
今天小編就為大家分享一篇對Python的zip函數(shù)妙用,旋轉(zhuǎn)矩陣詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Blender?Python編程實現(xiàn)批量導(dǎo)入網(wǎng)格并保存渲染圖像
這篇文章主要為大家介紹了Blender?Python?編程實現(xiàn)批量導(dǎo)入網(wǎng)格并保存渲染圖像示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08Tensorflow使用Anaconda、pycharm安裝記錄
這篇文章主要介紹了Tensorflow使用Anaconda、pycharm安裝記錄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Python學(xué)習(xí)筆記之For循環(huán)用法詳解
這篇文章主要介紹了Python學(xué)習(xí)筆記之For循環(huán)用法,結(jié)合實例形式詳細(xì)分析了Python for循環(huán)的功能、原理、用法及相關(guān)操作注意事項,需要的朋友可以參考下2019-08-08