參考文章:
https://www.zybuluo.com/hanbingtao/note/433855,
reduce:https://www.cnblogs.com/XXCXY/p/5180245.html,
lambda:https://www.cnblogs.com/caizhao/p/7905094.html,
zip:https://blog.csdn.net/shijichao2/article/details/51295676
幾個函數介紹
[0.0 for _ in range(input_num)] 創建一個共有input_num個元素且每個元素都是0.0的列表
lambda表達式
g = lambda x:x+1
定義了一個匿名函數,等同于
def g(x):
return x+1
reduce函數
def f(x, y):
return x + y
reduce(f, [1, 3, 5, 7, 9])
reduce函數將做如下計算:
1.先計算頭兩個元素:f(1, 3),結果為4;
2.再把結果和第3個元素計算:f(4, 5),結果為9;
3.再把結果和第4個元素計算:f(9, 7),結果為16;
4.再把結果和第5個元素計算:f(16, 9),結果為25;
5.由于沒有更多的元素了,計算結束,返回結果25。
reduce()還可以接收第3個可選參數,作為計算的初始值。如果把初始值設為100,計算初始值和第一個元素:f(100, 1),結果為101。最終結果將變為125。
zip函數
a, b = [0, 1], [2, 3]
ab = zip(a, b)
print(list(ab))
# [(0, 2), (1, 3)]
將兩個列表壓縮成組成元組的列表
map函數
map()是 Python 內置的高階函數,它接收一個函數 f 和一個 list,并通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 并返回。
def f(x):
return x*x
print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
#[1, 4, 9, 10, 25, 36, 49, 64, 81]
實例
class Perceptron(object):
def __init__(self, input_num, activator):
'''
初始化感知器,設置輸入參數的個數,以及激活函數。
激活函數的類型為double -> double
'''
self.activator = activator
# 權重向量初始化為0
self.weights = [0.0 for _ in range(input_num)]
# 偏置項初始化為0
self.bias = 0.0
def __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,...]打包在一起
# 變成[(x1,w1),(x2,w2),(x3,w3),...]
# 然后利用map函數計算[x1*w1, x2*w2, x3*w3]
# 最后利用reduce求和
return self.activator(
reduce(lambda a, b: a + b,
map(lambda (x, w): x * w,
zip(input_vec, self.weights))
, 0.0) + 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):
'''
按照感知器規則更新權重
'''
# 把input_vec[x1,x2,x3,...]和weights[w1,w2,w3,...]打包在一起
# 變成[(x1,w1),(x2,w2),(x3,w3),...]
# 然后利用感知器規則更新權重
delta = label - output
self.weights = map(
lambda (x, w): w + rate * delta * x,
zip(input_vec, self.weights))
# 更新bias
self.bias += rate * delta
接下來,我們利用這個感知器類去實現and函數。
def f(x):
'''
定義激活函數f
'''
return 1 if x > 0 else 0
def 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] -> 0
labels = [1, 0, 0, 0]
return input_vecs, labels
def train_and_perceptron():
'''
使用and真值表訓練感知器
'''
# 創建感知器,輸入參數個數為2(因為and是二元函數),激活函數為f
p = Perceptron(2, f)
# 訓練,迭代10輪, 學習速率為0.1
input_vecs, labels = get_training_dataset()
p.train(input_vecs, labels, 10, 0.1)
#返回訓練好的感知器
return p
if __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])
python3的可執行代碼,注意和python2的區別:
from _functools import reduce
class Perceptron(object):
def __init__(self, input_num, activator):
'''
初始化感知器,設置輸入參數的個數,以及激活函數。
激活函數的類型為double -> double
'''
self.activator = activator
# 權重向量初始化為0
self.weights = [0.0 for _ in range(input_num)]
# 偏置項初始化為0
self.bias = 0.0
def __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,...]打包在一起
# 變成[(x1,w1),(x2,w2),(x3,w3),...]
# 然后利用map函數計算[x1*w1, x2*w2, x3*w3]
# 最后利用reduce求和
return self.activator(
reduce(lambda a, b: a + b,
map(lambda x, w: x * w
, input_vec, self.weights)
, 0.0) + 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):
'''
按照感知器規則更新權重
'''
# 把input_vec[x1,x2,x3,...]和weights[w1,w2,w3,...]打包在一起
# 變成[(x1,w1),(x2,w2),(x3,w3),...]
# 然后利用感知器規則更新權重
delta = label - output
self.weights = list(map(
lambda x, w: w + rate * delta * x,
input_vec, self.weights))
# 更新bias
self.bias += rate * delta
#print('weights\t:%s\nbias\t:%f\n'%(self.weights, self.bias))
def f(x):
'''
定義激活函數f
'''
return 1 if x > 0 else 0
def 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] -> 0
labels = [1, 0, 0, 0]
return input_vecs, labels
def train_and_perceptron():
'''
使用and真值表訓練感知器
'''
# 創建感知器,輸入參數個數為2(因為and是二元函數),激活函數為f
p = Perceptron(2, f)
# 訓練,迭代10輪, 學習速率為0.1
input_vecs, labels = get_training_dataset()
p.train(input_vecs, labels, 10, 0.1)
#返回訓練好的感知器
return p
if __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]))