在机器学习中,感知器是一种监督学习的二元分类器算法。
具体来说,感知器算法适用于解决是否,可以或不可以之类的二元分类问题。
从一个例子来说:
假设有 ~
, 5个向量(5个贷款申请人), 其中
中的第一个特征值为年龄,第二个特征值为年收入(万)。
d1~d5 是历史记录上这5个人贷款批准的情况记录,-1为不批准,+1为批准。
= (20, 10),
= -1
= (23, 12),
= -1
= (20, 8),
= -1
= (25, 14),
= +1
= (28, 15),
= +1
对应地,还有一个权值向量 = (3, 7) , 即代表着年龄在模型中占3,年收入占7。
根据感知器算法:
算法的目的是求得一个目标函数: 通过此函数就能判定给定
的
。
。
-
其中
~
是 s 个样本
-
是 n 维的输入向量
-
是感知器的输出值
-
指的是第 j 个向量由 i 个特征值构成
-
= 1
-
是在权重向量中的第 i 个值
-
是一个偏置值,一般情况下用 b 来代替
-
是权重 i 在第 t 轮的值
实际的计算过程:
- (1) 初始化权重及门槛值为 0。
- (2) 输入
, 求
。
- 计算实际地输出
- 更新权重
那么,设定初始值:
时:
(需要修正)
修正:
时:
(不需要修正)
继续
(需要修正)
修正:
- 时:
(不需要修正)
(不需要修正)
(不需要修正)
(不需要修正)
(不需要修正)
那么,到 时,所有样本都已经符合对应的
。
则:
如果希望在二维坐标系中表示此函数,则:
#coding=utf-8
import numpy as np
class Perceptron(object):
def __init__(self, orgi_weight = [], orgi_samples = []):
self.weight_t = 0
self.weight = np.array(orgi_weight)
self.orgi_samples = orgi_samples
def add_orgi_sample(self, new_sample=[]):
self.orgi_samples.append(new_sample)
def learning(self):
samples = []
results = []
for s in self.orgi_samples:
samples.append(np.array(s[0]))
results.append(np.array(s[1]))
# weight_t = 0
sample_t = 1
inx = 0
while inx < len(samples):
# print "turn: ", inx, ", w:", self.weight_t
out = (self.weight_t * sample_t) + np.dot(self.weight, samples[inx])
if np.sign(out) != results[inx]:
#print results[inx], out
self.weight_t = self.weight_t + (results[inx] - out) * sample_t
inx = 0
else:
inx += 1
def judge(self, new_sample=[]):
new_sample = np.array(new_sample)
out = np.dot(self.weight, new_sample) + self.weight_t
return np.sign(out)
if __name__ == '__main__':
orgi_samples = [
[[20, 10], -1],
[[23, 12], -1],
[[20, 8], -1],
[[25, 14], 1],
[[28, 15], 1]
]
orgi_weight = [3, 7]
perceptron = Perceptron(orgi_weight, orgi_samples)
perceptron.learning()
# 新建一个输入,查看此样本是否能被批准
print perceptron.judge([30, 10]) # 1
# 添加样本重新学习
perceptron.add_orgi_sample([[30, 10], -1])
perceptron.learning()
print perceptron.judge([30, 10]) # -1
print perceptron.judge([30, 11]) # 1
重要参考:
https://en.wikipedia.org/wiki/Perceptron