簡單感知機的實現

2021-10-04 17:19:02 字數 3025 閱讀 9707

感知機演算法初步實現

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 =0.006

#學習速率b

d=[0

,0,0

,1]#期望輸出

e=0#誤差

for i in

range(4

):s = np.

sum(w*x[i])-c

y = f(s)

e = d[i]

- y

w = w+a*e*x[i]

c = np.

sum(c+b*e)

print

(w, c)

if __name__ ==

'__main__'

: and(

)

感知機實現進一步改進

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 =0.006

#學習速率b

d=[0

,0,0

,1]#期望輸出

e=0#誤差

while

true

: num_errors=

0for i in

range(4

):s = np.

sum(w*x[i])-c

y = f(s)

e = d[i]

- y

w = w+a*e*x[i]

c = np.

sum(c+b*e)

# 判斷是否誤分類

if e !=0:

num_errors +=

1#print(e)

if num_errors ==0:

print

(w, c)

break

if __name__ ==

'__main__'

: and(

)

感知機實現加上畫圖

import numpy as np

import matplotlib.pyplot as plt

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 =0.006

# 學習速率b

d =[0

,0,0

,1]# 期望輸出

e =0# 誤差

while

true

: num_errors =

0for i in

range(4

):s = np.

sum(w * x[i]

)- c

y = f(s)

e = d[i]

- y w = w + a * e * x[i]

c = np.

sum(c + b * e)

# 判斷是否誤分類

if e !=0:

num_errors +=

1#print(e)

if num_errors ==0:

print

(w, c)

break

# x = np.random.ranf(20) # 0到1的均勻分布

x = np.random.uniform(

-0.1

,1.2

,100

)# 指定在0.0~1.2均勻分布

y =-(w[0]

* x-c)

/ w[1]

plt.plot(x, y,

'g')

# # # 畫出訓練集中的點

plt.scatter(0,

0, c=

'r')

plt.scatter(0,

1, c=

'r')

plt.scatter(1,

0, c=

'r')

plt.scatter(1,

1, c=

'b')

plt.show(

)if __name__ ==

'__main__'

: and(

)

感知機(Python實現,簡單)

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 tra...

簡單感知機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 用來正常...