感知機學習演算法的簡單實現(Python)

2021-07-17 04:57:45 字數 2927 閱讀 9893

演算法(原始形式,出自李航博士的統計學習方法)

輸入:t=(其中xi∈x=rn,yi∈y=,i=1,2…n,學習速率為η)

輸出:w, b;感知機模型f(x)=sign(w·x+b)

1. 初始化w0,b0

2. 在訓練資料集中選取(xi, yi)

3. 如果yi(w xi+b)≤0

w = w + ηyixi

b = b + ηyi

4. 轉至2

對於訓練資料集,其中正例點是x1=(3,3)t,x2=(4,3)t,負例點為x3=(1,1)t,用感知機學習演算法的原始形式求感知機模型f(x)=w·x+b。這裡w=(w(1),w(2))t,x=(x(1),x(2))t

簡單的python實現:

import numpy as np

training_set = [[3,3],[4,3],[1,1]]

y = [1,1,-1]

w = [0,0]

b = 0

n = 1

#check給出w,b,找到乙個此時的誤分點,如果沒有,說明演算法收斂

defcheck

(w,b):

c =

for e in training_set:

x1 = np.array(e).reshape((-1,1))

w1 = np.array(w)

c = np.dot(w1,x1)

y = y[training_set.index(e)]

if y*(c+b)<=0:

break

else:

continue

return c

defupdate

(c,w,b):

d =

y = y[training_set.index(c)]

x = np.array(c)

return d

while

true:

c = check(w, b)

if len(c)==0:

break

else:

w = update(c,w,b)[0]

b = update(c,w,b)[1]

print

'演算法已經收斂'

print

'y = sign(%d*x1 + %d*x2 + %d)'%(w[0],w[1],b)

輸出:

演算法已經收斂

y = sign(1

*x1 + 1

*x2 + -3)

import numpy as np

training_set = [[3,3],[4,3],[1,1]]

y = [1,1,-1]

a = [0,0,0]

b = 0

n = 1

n = 3

defcal

(training_set):

x11 = np.dot(np.array(training_set[0]),np.array(training_set[0]).reshape(-1,1))

x22 = np.dot(np.array(training_set[1]),np.array(training_set[1]).reshape(-1,1))

x33 = np.dot(np.array(training_set[2]),np.array(training_set[2]).reshape(-1,1))

x12 = x21 = np.dot(np.array(training_set[0]),np.array(training_set[1]).reshape(-1,1))

x13 = x31 = np.dot(np.array(training_set[0]),np.array(training_set[2]).reshape(-1,1))

x23 = x32 = np.dot(np.array(training_set[1]),np.array(training_set[2]).reshape(-1,1))

return [[x11,x12,x13],[x21,x22,x23],[x31,x32,x33]]

defcheck

(a,b):

c =

x = cal(training_set)

for i in range(n):

y = y[i]

l = 0

for j in range(n):

l = l + a[j]*y[j]*x[j][i]

if y*(l + b) <= 0:

c = training_set[i]

break

else:

continue

return c

defupdate

(c,a,b):

d =

y = y[training_set.index(c)]

a[training_set.index(c)] = a[(training_set.index(c)] + n

return d

while

true:

c = check(a, b)

if len(c)==0:

break

else:

a = update(c,a,b)[0]

b = update(c,a,b)[1]

print

u'演算法已收斂'

print a,b

輸出:

演算法已收斂

[6, 0, 16]

-5

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

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

簡單感知機的實現

感知機演算法初步實現 import numpy as np 階躍函式 deff y return 1if y 0else 0def and x np.array 0,0 0,1 1,0 1,1 資料集 w np.array 0.038 0.044 c 0.042 閾值 a 0.015 學習速率a b...

感知機學習演算法

from sklearn.linear model import perceptron import numpy as np 訓練資料集 x train np.array 3,3 4,3 1,1 y np.array 1 1,1 構建perceptron物件,訓練資料並輸出結果 perceptron...