爱吧机器人网 » 技术 > 机器学习 > 正文

Machine Learning-感知器分类算法详解

作者:阿Sam 【翻译整理】
个人公众号:SAMshare
选自 python-machine-learning-book on GitHub
作者:Sebastian Raschka
翻译&整理 by Sam


最近在GitHub上面发现了一个炒鸡赞的项目,果然直接拿过来消化一波,这个项目的内容是关于机器学习的指导,我会挑一些内容来完成下面的一系列文章。


今天我们来讲解的内容是感知器分类算法,本文的结构如下:

什么是感知器分类算法
在Python中实现感知器学习算法
在iris(鸢尾花)数据集上训练一个感知器模型
自适应线性神经元和融合学习
使用梯度下降方法来最小化损失函数
在Python中实现一个自适应的线性神经元


什么是感知器分类算法


设想我们改变逻辑回归算法,“迫使”它只能输出-1或1抑或其他定值。在这种情况下,之前的逻辑函数‍‍g就会变成阈值函数sign:




如果我们令假设为hθ(x)=g(θTx)hθ(x)=g(θTx),将其带入之前的迭代法中:

至此我们就得出了感知器学习算法。简单地来说,感知器学习算法是神经网络中的一个概念,单层感知器是最简单的神经网络,输入层和输出层直接相连。

每一个输入端和其上的权值相乘,然后将这些乘积相加得到乘积和,这个结果与阈值相比较(一般为0),若大于阈值输出端就取1,反之,输出端取-1。

初始权重向量W=[0,0,0],更新公式W(i)=W(i)+ΔW(i);ΔW(i)=η*(y-y’)*X(i); 
η:学习率,介于[0,1]之间 
y:输入样本的正确分类 
y’:感知器计算出来的分类 
通过上面公式不断更新权值,直到达到分类要求。
图:单层感知器模型

初始化权重向量W,与输入向量做点乘,将结果与阈值作比较,得到分类结果1或-1。


在Python中实现感知器学习算法


下面直接贴上实现代码:(也可在公众号后台输入“感知器”进行获取ipynb文件)

 1import numpy as np
 2class  Perceptron(object):
 3"""Perceptron classifier.
 4Parameters
 5------------
 6eta : float
 7  Learning rate (between 0.0 and 1.0)
 8n_iter : int
 9  Passes over the training dataset.
10Attributes
11-----------
12w_ : 1d-array
13  Weights after fitting.
14errors_ : list
15  Number of misclassifications (updates) in each epoch.
16"""
17def __init__(self, eta=0.01, n_iter=10):
18  self.eta = eta
19  self.n_iter = n_iter
20def fit(self, X, y):
21  """Fit training data.
22  Parameters
23  ----------
24  X : {array-like}, shape = [n_samples, n_features]
25  Training vectors, where n_samples is the number of samples and
26  n_features is the number of features.
27  y : array-like, shape = [n_samples]
28  Target values.
29  Returns
30  -------
31  self : object
32  """
33  self.w_ = np.zeros(1 + X.shape[1])
34  self.errors_ = []
35  for _ in range(self.n_iter):
36  errors = 0
37  for xi, target in zip(X, y):
38  update = self.eta * (target - self.predict(xi))
39  self.w_[1:] += update * xi
40  self.w_[0] += update
41  errors += int(update != 0.0)
42  self.errors_.append(errors)
43  return self
44def net_input(self, X):
45  """Calculate net input"""
46  return np.dot(X, self.w_[1:]) + self.w_[0]
47def predict(self, X):
48  """Return class label after unit step"""
49  return np.where(self.net_input(X) >= 0.0, 1, -1)

特别说明:


学习速率η(eta)只有在权重(一般取值0或者很小的数)为非零值的时候,才会对分类结果产生作用。如果所有的权重都初始化为0,学习速率参数eta只影响权重向量的大小,而不影响其方向,为了使学习速率影响分类结果,权重需要初始化为非零值。需要更改的代码中的相应行在下面突出显示:

1def __init__(self, eta=0.01, n_iter=50, random_seed=1): # add random_seed=1
2  ...
3  self.random_seed = random_seed # add this line
4def fit(self, X, y):
5  ...
6  # self.w_ = np.zeros(1 + X.shape[1]) ## remove this line
7  rgen = np.random.RandomState(self.random_seed) # add this line
8  self.w_ = rgen.normal(loc=0.0, scale=0.01, size=1 + X.shape[1]) # add this line

在iris(鸢尾)数据集上训练一个感知器模型

读取iris数据集
1import pandas as pd
2import collections
3df = pd.read_csv('https://archive.ics.uci.edu/ml/'
4  'machine-learning-databases/iris/iris.data', header=None)
5print (df.head())
6print ("\n")
7print (df.describe())
8print ("\n")
9print (collections.Counter(df[4]))

output:



可视化iris数据

 1%matplotlib inline
 2import matplotlib.pyplot as plt
 3import numpy as np
 4# 为了显示中文(这里是Mac的解决方法,其他的大家可以去百度一下)
 5from matplotlib.font_manager import FontProperties
 6font = FontProperties(fname='/System/Library/Fonts/STHeiti Light.ttc')
 7# 选择 setosa and versicolor类型的花
 8y = df.iloc[0:100, 4].values
 9y = np.where(y == 'Iris-setosa', -1, 1)
10# 提取它们的特征 (sepal length and petal length)
11X = df.iloc[0:100, [0, 2]].values
12# 可视化数据,因为数据有经过处理,总共150行数据,1-50行是setosa花,51-100是versicolor花,101-150是virginica花
13plt.scatter(X[:50, 0], X[:50, 1],
14  color='red', marker='o', label='setosa')
15plt.scatter(X[50:100, 0], X[50:100, 1],
16  color='blue', marker='x', label='versicolor')
17plt.xlabel('sepal 长度 [cm]',FontProperties=font,fontsize=14)
18plt.ylabel('petal 长度 [cm]',FontProperties=font,fontsize=14)
19plt.legend(loc='upper left')
20plt.tight_layout()
21plt.show()

output:


训练感知器模型

1# Perceptron是我们前面定义的感知器算法函数,这里就直接调用就好
2ppn = Perceptron(eta=0.1, n_iter=10)
3ppn.fit(X, y)
4plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
5plt.xlabel('迭代次数',FontProperties=font,fontsize=14)
6plt.ylabel('权重更新次数(错误次数)',FontProperties=font,fontsize=14)
7plt.tight_layout()
8plt.show()


output:


绘制函数决策区域

 1from matplotlib.colors import ListedColormap
 2def plot_decision_regions(X, y, classifier, resolution=0.02):
 3  # setup marker generator and color map
 4  markers = ('s', 'x', 'o', '^', 'v')
 5  colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
 6  cmap = ListedColormap(colors[:len(np.unique(y))])
 7  # plot the decision surface
 8  x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
 9  x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
10  xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
11 np.arange(x2_min, x2_max, resolution))
12  Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
13  Z = Z.reshape(xx1.shape)
14  plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
15  plt.xlim(xx1.min(), xx1.max())
16  plt.ylim(xx2.min(), xx2.max())
17  # plot class samples
18  for idx, cl in enumerate(np.unique(y)):
19  plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
20  alpha=0.8, c=cmap(idx),
21  edgecolor='black',
22  marker=markers[idx], 
23  label=cl)


1plot_decision_regions(X, y, classifier=ppn)
2plt.xlabel('sepal 长度 [cm]',FontProperties=font,fontsize=14)
3plt.ylabel('petal 长度 [cm]',FontProperties=font,fontsize=14)
4plt.legend(loc='upper left')
5plt.tight_layout()
6plt.show()


output:



自适应线性神经元和融合学习


使用梯度下降方法来最小化损失函数

梯度下降的方法十分常见,具体的了解可以参考附录的文章[2],如今,梯度下降主要用于在神经网络模型中进行权重更新,即在一个方向上更新和调整模型的参数,来最小化损失函数。

图:梯度下降原理过程演示

在Python中实现一个自适应的线性神经元

先贴上定义的python函数,(也可在公众号后台输入“感知器”进行获取ipynb文件)

 1# 定义神经元函数
 2class AdalineGD(object):
 3  """ADAptive LInear NEuron classifier.
 4  Parameters
 5  ------------
 6  eta : float
 7  Learning rate (between 0.0 and 1.0)
 8  n_iter : int
 9  Passes over the training dataset.
10  Attributes
11  -----------
12  w_ : 1d-array
13  Weights after fitting.
14  cost_ : list
15  Sum-of-squares cost function value in each epoch.
16  """
17  def __init__(self, eta=0.01, n_iter=50):
18  self.eta = eta
19  self.n_iter = n_iter
20  def fit(self, X, y):
21  """ Fit training data.
22  Parameters
23  ----------
24  X : {array-like}, shape = [n_samples, n_features]
25  Training vectors, where n_samples is the number of samples and
26  n_features is the number of features.
27  y : array-like, shape = [n_samples]
28  Target values.
29  Returns
30  -------
31  self : object
32  """
33  self.w_ = np.zeros(1 + X.shape[1])
34  self.cost_ = []
35  for i in range(self.n_iter):
36  net_input = self.net_input(X)
37  # Please note that the "activation" method has no effect
38  # in the code since it is simply an identity function. We
39  # could write `output = self.net_input(X)` directly instead.
40  # The purpose of the activation is more conceptual, i.e.,  
41  # in the case of logistic regression, we could change it to
42  # a sigmoid function to implement a logistic regression classifier.
43  output = self.activation(X)
44  errors = (y - output)
45  self.w_[1:] += self.eta * X.T.dot(errors)
46  self.w_[0] += self.eta * errors.sum()
47  cost = (errors**2).sum() / 2.0
48  self.cost_.append(cost)
49  return self
50  def net_input(self, X):
51  """Calculate net input"""
52  return np.dot(X, self.w_[1:]) + self.w_[0]
53  def activation(self, X):
54  """Compute linear activation"""
55  return self.net_input(X)
56  def predict(self, X):
57  """Return class label after unit step"""
58  return np.where(self.activation(X) >= 0.0, 1, -1)

查看不同学习率下的错误率随迭代次数的变化情况:

\
\
\
\




上一篇:贝叶斯网络之父:如何真正教会机器理解
下一篇:深度学习的可解释性研究(一):让模型「说人话」
精选推荐
什么是机器人学?机器人学简介
什么是机器人学?机器人学简介

[2017-12-14]  机器人学是工程学与科学的交叉学科,包括机械工程,电气工程,计算机科学等。机器人技术涉及机器人的设计、制造、操作和应用,以及用于控制、感官反馈和信息处理的计算机系统。...

[2017-03-21]  虽然有很多关于机器人取代工人的担心,但哈佛经济学家James Bessen的论文指出,在过去的67年里机器人仅仅淘汰掉人类工作中的一个。在1950 ...

[2018-01-26]  纽约时报的报道,德国的研究人员已经开发出一种长约七分之一英寸的机器人,首先看起来不过是一小块橡皮条。然后它开始移动。机器人走路,跳跃,爬行,滚动和游泳。它甚至爬出......

九台“猎豹”机器人组队踢球,麻省理工高材生们的高级趣味
九台“猎豹”机器人组队踢球,麻省理工高材生们的高级趣味

[2019-11-09]  本周,在麻省理工学院10号楼外草坪上展开了一场别开生面的足球比赛。在绿草如茵的基利安球场上,一群由人工智能驱动的机器人就是这场比赛的 ...

MIT最新“人机”互连系统 让双腿机器人复制人体技能
MIT最新“人机”互连系统 让双腿机器人复制人体技能

[2019-11-01]  MIT的小爱马仕想借用你的大脑 ,图片来自: João Ramos爱吧机器人网消息,麻省理工学院(MIT)的研究人员展示了一种新型遥操作系 ...

美国人工智能公司Skymind进入福建全面开展业务
美国人工智能公司Skymind进入福建全面开展业务

[2017-12-11]  人工智能在当今这个时代对大家来说想必是非常熟悉的,这也是我国近十几年来一直追求的目标,未来的时间里这也将是全人类追求的目标。就目前来看,近年来,人工智能或在我国迎......

通过对抗性图像黑入大脑
通过对抗性图像黑入大脑

[2018-03-02]  在上面的图片中,左边是一张猫的照片。在右边,你能分辨出它是同一只猫的图片,还是一张看起来相似的狗的图片?这两张图片之间的区别在于, ...

谷歌大脑发布ROBEL基准 鼓励用低成本机器人训练AI系统
谷歌大脑发布ROBEL基准 鼓励用低成本机器人训练AI系统

[2019-10-11]  训练AI系统的机器人D& 39;Claw和D& 39;Kitty用于控制机器人的人工智能系统,测量其性能所使用的基准通常仅限于为工业环境设计的昂贵硬件, ...

本周栏目热点

深度学习反向传播算法(BP)原理推导及代码实现

[2017-12-19]  分析了手写字数据集分类的原理,利用神经网络模型,编写了SGD算法的代码,分多个epochs,每个 epoch 又对 mini_batch 样本做多次迭代计算。这其中,非常重要的一个步骤,......

如何在机器学习项目中使用统计方法的示例

[2018-07-23]  事实上,机器学习预测建模项目必须通过统计学方法才能有效的进行。在本文中,我们将通过实例介绍一些在预测建模问题中起关键作用的统计学方法。...

[2017-08-28]  模拟退火(Simulated Annealing,简称SA)是一种通用概率算法,用来在一个大的搜寻空间内找寻命题的最优解。1、固体退火原理:将固体加温 ...

Machine Learning-感知器分类算法详解

[2018-05-31]  今天我们来讲解的内容是感知器分类算法,本文的结构如下:什么是感知器分类算法,在Python中实现感知器学习算法,在iris(鸢尾花)数据集上训练一个感知器模型,自适应线性神......

机器人是怎么深度学习的?

[2016-03-29]      一个人独处时,感觉有点孤单,怎么办?微软亚洲研究院推出的微软小冰,或许 ...