神经元的实现

本文将使用python实现一个神经元(感知器).

本文来自https://www.zybuluo.com/hanbingtao/note/433855

理论请参考上文.下面是python2和3的实现

python2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from functools import reduce


class Perceptron(object):
def __init__(self, input_num, activator):
self.activator = activator
self.weights = [0.0 for _ in range(input_num)]
self.bias = 0.0

def train(self, input_vec, iteration, labels, rate):
for _ in range(iteration):
self._one_iteration(input_vec, labels, rate)

def _one_iteration(self, input_vec, labels, rate):
samples = zip(input_vec, labels)
for (vec, label) in samples:
output = self.predict(vec)
self._update_weights(vec, output, label, rate)

def predict(self, vec):
return self.activator(
reduce(
lambda a, b: a + b,
list(map(
lambda x, w: x * w,
vec, self.weights
)), 0.0
) + self.bias
)

def _update_weights(self, vec, output, label, rate):
delta = label - output
self.weights = list(map(
lambda x, w: w + rate * delta * x, # 在python2里是用的(x,w)形式
vec, self.weights
))
self.bias += rate * delta

def __str__(self):
return 'weights: %s\nbias: %s\n' % (self.weights, self.bias)


def activator(x):
return 1 if x > 0 else 0


def get_data_sets():
x = [[0, 1], [1, 0], [1, 1], [0, 0]]
labels = [0, 0, 1, 0]
return x, labels


def train():
p = Perceptron(2, activator)
x, labels = get_data_sets()
p.train(x, 20, labels, 0.05)
return p


if __name__ == '__main__':
p = train()
print(p)
# 测试
print('1 and 1 = %d' % p.predict([1, 1]))
print('0 and 0 = %d' % p.predict([0, 0]))
print('1 and 0 = %d' % p.predict([1, 0]))
print('0 and 1 = %d' % p.predict([0, 1]))

结果

1
2
3
4
5
6
7
weights: [0.1, 0.05]
bias: -0.1

1 and 1 = 1
0 and 0 = 0
1 and 0 = 0
0 and 1 = 0

其实上面就是梯度下降的过程.