and感知機通過訓練後,可以進行邏輯"與"的運算。例如:當輸入 1,1時,輸出為1;輸入1,0時,輸出為0。
通過上圖,我們可以發現(0,0)(0,1)(1,0)這三個點數表示輸出為0,而點(1,1)表示輸出為1,所以我們可以近似找到一條直線將輸出為0的點與輸出為1的點分隔開。我們可以通過不斷訓練係數(即權值與閾值)找到這條直線。假設輸入為x0,x1,權值分別為w0,w1,輸出為y,那麼感知機的模型為y = w0 * x0 + w1 * x1 - θ,其中θ為閾值,也叫偏置。模型 中的權值與閾值初始可以是任意值。
其實and感知機是乙個二分類的過程,其結果不是0就為1,所以我們需要啟用函式
這個函式可以將得到的任意實數y對映成0或1, 這樣便於得到正確的結果。
根據下列規則,可調整權值與閾值的大小,輸出正確的結果。
其中ε為誤差 ε = y - y' ,y為預期值,y'為實際值。
當輸入x0 = 1, x1 = 1,權值w0 = 1,w1 = 1,閾值θ = 3(權值與閾值初始可以為任意值),則 y = 1 * 1 + 1 * 1 - 3 = -1,將y帶入sgn(x)函式中得到0,結果與預期結果1不符(1 and 1 = 1),那麼就要根據上述跪著調整權值與閾值,
誤差為ε = 1 - 0 = 1,根據上面公式w
**如下:
執行結果:#and感知機
class perception(object):
def __init__(self, input_para_num, acti_func):
self.activator = acti_func
#權重向量初始化為0
self.weights = [0.0 for _ in range(input_para_num)] #這裡只是將所有的權值初始化成0(初始化成其他值是不會影響到結果的)
def __str__(self):
return 'final weights\n\tw0 = \n\tw1 = \n\tw2 = '\
.format(self.weights[0], self.weights[1], self.weights[2])
def predict(self,row_vec):
act_values = 0.0
for i in range(len(self.weights)):
act_values += self.weights[i] * row_vec[i]
return self.activator(act_values)
#對感知機進行訓練
def train(self, dataset, iteration, rate):
for i in range(iteration):
for input_vec_label in dataset:
#計算機感知機在當前權重下輸出
prediction = self.predict(input_vec_label)
#更新權重
self._update_weights(input_vec_label, prediction, rate)
#更新權重
def _update_weights(self, input_vec_label, prediction, rate):
delta = input_vec_label[-1] - prediction
for i in range(len(self.weights)):
self.weights[i] += rate * delta * input_vec_label[i]
#啟用函式
def func_activator(input_value):
return 1.0 if input_value >= 0.0 else 0.0
def get_training_dataset():
#構建訓練資料
dataset = [[-1, 1, 1, 1], [-1, 0, 0, 0],[-1, 1, 0, 0],[-1, 0, 1, 0]]
#期望的輸出列表,注意要與輸入一一對應
#[-1, 1, 1] -> 1, [-1, 0, 0] -> 0,[-1, 1, 0] -> 0,[-1, 0, 1] -> 0
return dataset
def train_and_perception():
p = perception(3, func_activator)
#獲取訓練資料
dataset = get_training_dataset()
#指定迭代次數:10輪,學習效率設定為0.1
p.train(dataset, 10, 0.1)
#返回訓練好的感知機
return p
if __name__ == '__main__':
#訓練and感知機
and_perception = train_and_perception()
#列印訓獲得的權重
print(and_perception)
#測試print('1 and 1 = %d' % and_perception.predict([-1, 1, 1])) #第乙個值-1是x0,其係數w0為閾值
print('0 and 0 = %d' % and_perception.predict([-1, 0, 0]))
print('1 and 0 = %d' % and_perception.predict([-1, 1, 0]))
print('0 and 1 = %d' % and_perception.predict([-1, 0, 1]))
發現and感知機訓練成功
參考:《深度學習之美:ai時代的資料處理與最佳實踐_張玉巨集》
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 定義訓練函式,包...
感知機python實現
有用請點贊,沒用請差評。感知機原理參考部落格 演算法引用李航博士 統計學習方法 p29.感知機 import numpy as np import matplotlib.pyplot as plt class perceptron object def init self,eta 1,iter 50...
感知機(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...