感知器python代码
生活随笔
收集整理的這篇文章主要介紹了
感知器python代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
感知器屬于機器學習的入門算法了,具體的理論知識不細講了。只說下里面涉及到的核心知識:
權重更新公式:w=wi+▲wi ? ? ? ?? b=b+▲b其中▲wi=n(t-y)x ??b=n(t-y)
n是學習效率,t是label即真實的輸出,y是感知器的輸出值。我現階段認為機器學習最重要的是建立模型對模型進行訓練。我們建立模型。代碼如下:
def train(self, input_vecs, labels, iteration, rate):"""輸入訓練數據:一組向量、與每個向量對應的label;以及訓練輪數、學習率"""for i in range(iteration):self._one_iteration(input_vecs, labels, rate)def _one_iteration(self, input_vecs, labels, rate):"""一次迭代,把所有的訓練數據過一遍"""# 把輸入和輸出打包在一起,成為樣本的列表[(input_vec, label), ...]# 而每個訓練樣本是(input_vec, label)samples = zip(input_vecs, labels)# 對每個樣本,按照感知器規則更新權重for (input_vec, label) in samples:# 計算感知器在當前權重下的輸出output = self.predict(input_vec)# 更新權重self._update_weights(input_vec, output, label, rate)def _update_weights(self, input_vec, output, label, rate):"""按照感知器規則更新權重"""# 首先計算本次更新的delta# 然后把input_vec[x1,x2,x3,...]向量中的每個值乘上delta,得到每個權重更新# 最后再把權重更新按元素加到原先的weights[w1,w2,w3,...]上delta = label - outputself.weights = VectorOp.element_add(self.weights, VectorOp.scala_multiply(input_vec, rate * delta))# 更新biasself.bias += rate * delta模型建立好并訓練好之后就可以使用該模型對數據進行預測了。該段代碼實現的功能是真值表的與運算。整段代碼如下(python3):
#!/usr/bin/env python # -*- coding: UTF-8 -*-from __future__ import print_function from functools import reduceclass VectorOp(object):"""實現向量計算操作"""@staticmethoddef dot(x, y):"""計算兩個向量x和y的內積"""# 首先把x[x1,x2,x3...]和y[y1,y2,y3,...]按元素相乘# 變成[x1*y1, x2*y2, x3*y3]# 然后利用reduce求和return reduce(lambda a, b: a + b, VectorOp.element_multiply(x, y), 0.0)@staticmethoddef element_multiply(x, y):"""將兩個向量x和y按元素相乘"""# 首先把x[x1,x2,x3...]和y[y1,y2,y3,...]打包在一起# 變成[(x1,y1),(x2,y2),(x3,y3),...]# 然后利用map函數計算[x1*y1, x2*y2, x3*y3]return list(map(lambda x_y: x_y[0] * x_y[1], zip(x, y)))@staticmethoddef element_add(x, y):"""將兩個向量x和y按元素相加"""# 首先把x[x1,x2,x3...]和y[y1,y2,y3,...]打包在一起# 變成[(x1,y1),(x2,y2),(x3,y3),...]# 然后利用map函數計算[x1+y1, x2+y2, x3+y3]return list(map(lambda x_y: x_y[0] + x_y[1], zip(x, y)))@staticmethoddef scala_multiply(v, s):"""將向量v中的每個元素和標量s相乘"""return map(lambda e: e * s, v)class Perceptron(object):def __init__(self, input_num, activator):"""初始化感知器,設置輸入參數的個數,以及激活函數。激活函數的類型為double -> double"""self.activator = activator# 權重向量初始化為0self.weights = [0.0] * input_num# 偏置項初始化為0self.bias = 0.0def __str__(self):"""打印學習到的權重、偏置項"""return 'weights\t:%s\nbias\t:%f\n' % (self.weights, self.bias)def predict(self, input_vec):"""輸入向量,輸出感知器的計算結果"""# 計算向量input_vec[x1,x2,x3...]和weights[w1,w2,w3,...]的內積# 然后加上biasreturn self.activator(VectorOp.dot(input_vec, self.weights) + self.bias)def train(self, input_vecs, labels, iteration, rate):"""輸入訓練數據:一組向量、與每個向量對應的label;以及訓練輪數、學習率"""for i in range(iteration):self._one_iteration(input_vecs, labels, rate)def _one_iteration(self, input_vecs, labels, rate):"""一次迭代,把所有的訓練數據過一遍"""# 把輸入和輸出打包在一起,成為樣本的列表[(input_vec, label), ...]# 而每個訓練樣本是(input_vec, label)samples = zip(input_vecs, labels)# 對每個樣本,按照感知器規則更新權重for (input_vec, label) in samples:# 計算感知器在當前權重下的輸出output = self.predict(input_vec)# 更新權重self._update_weights(input_vec, output, label, rate)def _update_weights(self, input_vec, output, label, rate):"""按照感知器規則更新權重"""# 首先計算本次更新的delta# 然后把input_vec[x1,x2,x3,...]向量中的每個值乘上delta,得到每個權重更新# 最后再把權重更新按元素加到原先的weights[w1,w2,w3,...]上delta = label - outputself.weights = VectorOp.element_add(self.weights, VectorOp.scala_multiply(input_vec, rate * delta))# 更新biasself.bias += rate * deltadef f(x):"""定義激活函數f"""return 1 if x > 0 else 0def get_training_dataset():"""基于and真值表構建訓練數據"""# 構建訓練數據# 輸入向量列表input_vecs = [[1, 1], [0, 0], [1, 0], [0, 1]]# 期望的輸出列表,注意要與輸入一一對應# [1,1] -> 1, [0,0] -> 0, [1,0] -> 0, [0,1] -> 0labels = [1, 0, 0, 0]return input_vecs, labelsdef train_and_perceptron():"""使用and真值表訓練感知器"""# 創建感知器,輸入參數個數為2(因為and是二元函數),激活函數為fp = Perceptron(2, f)# 訓練,迭代10輪, 學習速率為0.1input_vecs, labels = get_training_dataset()p.train(input_vecs, labels, 10, 0.1)# 返回訓練好的感知器return pif __name__ == '__main__':# 訓練and感知器and_perception = train_and_perceptron()# 打印訓練獲得的權重print(and_perception)# 測試print('1 and 1 = %d' % and_perception.predict([1, 1]))print('0 and 0 = %d' % and_perception.predict([0, 0]))print('1 and 0 = %d' % and_perception.predict([1, 0]))print('0 and 1 = %d' % and_perception.predict([0, 1]))參考資料:https://www.zybuluo.com/hanbingtao/note/433855
總結
以上是生活随笔為你收集整理的感知器python代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2013年6月份安徽省计算机等级考试二级
- 下一篇: 根据工作年限预测工资python代码实现