感知機(Python實現,簡單)

2021-08-14 19:54:00 字數 1784 閱讀 6976

#!/usr/bin/python

#-*-coding:utf-8 -*-

importrandom

fromnumpyimport*

importnumpyasnp

deftraining():

train_data1 = [[3, 3, 1], [4, 3, 1]] # 正樣本

train_data2 = [[1, 1, -1]] # 負樣本

train_datas = train_data1 + train_data2 # 樣本集

leng=len(train_datas[0])

#選取初值

w=[0,0] #權值

b=0

#偏置step=1

while(judgeerrorpoint(w,b,train_datas)):

#選取資料(xi,yi)

ranint=random.randint(0,2)

data=train_datas[ranint]

xi,yi=selectxiyi(leng,data)

# print(str(xi)+"----"+str(yi))

ifyi[0]*((calculate(w,xi)+b))<=0:

w=mat(w)+mat(step*yi[0]*xi)

b=b+step*yi[0]

print(w)

print(b)

returnw,b

#矩陣計算

defcalculate(w,xi):

a1=w

a1=mat(a1)

a2=mat(xi).t #矩陣轉置

a3=a1*a2

val=a3[0,0] #把矩陣變為乙個數值

# print (str(val)+"-----val")

returnval

#判斷是否有誤分類點

defjudgeerrorpoint(w,b,train_datas):

leng=len(train_datas[0])

judge=false

fordataintrain_datas:

xi,yi=selectxiyi(leng,data)

ifyi[0]*((calculate(w,xi)+b))<=0:

judge=true

returnjudge

returnjudge

#把資料來源中的xi,yi分開

defselectxiyi(leng,data):

ranint=random.randint(0,2)

# print(ranint)

xi=data[:leng-1]

yi=data[-1:leng]

returnxi,yi

training()

簡單感知機Python實現

import numpy as np import matplotlib.pyplot as plt plt.rcparams font.sans serif simhei 用來正常顯示中文標籤 plt.rcparams axes.unicode minus false 用來正常顯示負號 plt.r...

Python 實現簡單的感知機演算法

隨機生成一些點和一條原始直線,然後用感知機演算法來生成一條直線進行分類,比較差別 import numpy as np import matplotlib.pyplot as plt matplotlib inline plt.rcparams font.sans serif simhei 用來正常...

python實現感知機

import numpy as np 定義啟用函式 def acti fun x return 1 if x 0 else 0 建立感知器類 class perception object 初始化權重 def init self self.weights 0 self.bias 1 定義訓練函式,包...