面试例题5—感知器实现and函数
来源:互联网 发布:js 百度地图 标注位置 编辑:程序博客网 时间:2024/05/18 22:18
用感知器实现and函数
参考博客:https://www.zybuluo.com/hanbingtao/note/433855点击打开链接
and 运算时一个二元运算,它的真值表如下:
x1x2y000010100111
Python:
class Perceptron(object): def __init__(self, input_num, activator): self.activator = activator self.weights = [0 for i in range(input_num)] self.bias = 0.0 def __str__(self): return 'weights\t:%s\nbias\t:%f\n' % (self.weights,self.bias) def train(self, input_vecs, labels, iteration, rate): #train for i in range(iteration): self._one_iteration(input_vecs, labels, rate) def _one_iteration(self, input_vecs, labels, rate): # one iteration samples = zip(input_vecs, labels) for (input_vec, label) in samples: output = self.predict(input_vec) self._update_weights(input_vec, label, output, rate) def predict(self, input_vec): #predict output 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 _update_weights(self, input_vec, label, output, rate): # update weights and bias delta = label - output self.weights = map( lambda (x,w): w + rate * x * delta ,zip(input_vec, self.weights) ) self.bias += rate * deltadef f(x): # actavition function return 1 if x > 0 else 0def get_trianing_data(): #train data input_vects = [[1,1],[1,0],[0,1],[0,0]] labels = [1,0,0,0] return input_vects,labelsdef train_and_perceptron(): # train p = Perceptron(2,f) input_vecs, labels = get_trianing_data() p.train(input_vecs, labels, 10, 0.1) return pif __name__ == "__main__": and_perceptron = train_and_perceptron() 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])
阅读全文
0 0
- 面试例题5—感知器实现and函数
- AND 感知器练习
- [AHK]AutoHotkey也玩神经网络实现AND逻辑感知器
- 面试例题—sizeof(2)
- 感知器——python实现
- 感知器算法——C++实现
- Python实现感知器
- 面试例题
- 面试例题
- 面试例题4—main函数执行完毕后,是否会再执行一段代码
- 深度学习之感知器AND(与)实现C++代码
- 一道SQL面试例题 if...else 与聚集函数
- 模式识别:感知器的实现
- 模式识别:感知器的实现
- 感知器的scala实现
- 感知器的scala实现
- 模式识别:感知器的实现
- 感知器算法及其实现
- 【PMP认证考试之个人总结】第 4 章 项目范围管理
- 基本网络知识
- Android Studio中使用apt
- day6 linux操作基础命令 第三弹
- BZOJ 4027 [HEOI2015] 兔子与樱花
- 面试例题5—感知器实现and函数
- Java基础
- 从UIWebView到WKWebView
- Hadoop三剑客:hdfs、yarn、mapreduce
- 函数
- 第四讲 数据的处理
- 357. Count Numbers with Unique Digits 题解
- Sublime Text安装
- Spring 事务切面配置