从零手写感知器 python 篇
感知器是入门神经网络的基础
主要用到了两个公式
1、
2、
参考文章:点击前往
# -*- coding: utf-8 -*-
import numpy as np
class Perceptron(object):
def __init__(self, input_num):
self.activator = self.f
self.weights = [0.0] * input_num
self.bias = 0.0
def __str__(self):
"""
打印学习到的权重、偏置项
"""
return 'weights\t:%s\nbias\t:%f\n' % (self.weights, self.bias)
def predict(self, input_vec):
return np.dot(input_vec, self.weights) + self.bias
def train(self, input_vecs, labels, counts, rate):
# 训练的数据, 标签 ,轮数 , 下降率
for i in range(counts):
self.one_iteration(input_vecs, labels, rate)
def one_iteration(self, input_vecs, labels, rate):
samples = zip(input_vecs, labels)
for (input_vec, label) in samples:
out_put = self.predict(input_vec)
self.update_weight(input_vec,
out_put,
label,
rate
)
def update_weight(self, input_vec, out_put, label, rate):
# 训练等于 w = w + fw
# fw = rate * (label - out_put) * xi
delta = label - out_put
updateW = np.dot(delta * rate, input_vec)
self.weight = np.add(self.weights, updateW)
self.bias = rate * delta
def f(self, x):
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():
p = Perceptron(2)
input_vecs, labels = get_training_dataset()
p.train(input_vecs, labels, 10, 0.1)
return p
if __name__ == "__main__":
and_perceptron = train_and_perceptron()
print("my")
print(and_perceptron)
print('1 and 1 = %d' % and_perceptron.predict([1, 1]))
print('0 and 0 = %d' % and_perceptron.predict([0, 0]))
print('1 and 0 = %d' % and_perceptron.predict([1, 0]))
print('0 and 1 = %d' % and_perceptron.predict([0, 1]))