感知器(Perceptron)详解
感知器是一种简单的线性二分类算法,它是神经网络和深度学习的基础之一。
感知器的核心概念
感知器模型基于将输入特征加权求和,然后应用激活函数来决定输出类别。
1. 输入和权重
- 输入: x 1 , x 2 , . . . , x n x_1, x_2, ..., x_n x1,x2,...,xn 是特征向量。
- 权重: w 1 , w 2 , . . . , w n w_1, w_2, ..., w_n w1,w2,...,wn 是每个特征的权重。
2. 加权求和
感知器通过计算输入特征的加权和来做出决策:
z = w 1 x 1 + w 2 x 2 + . . . + w n x n + b z = w_1x_1 + w_2x_2 + ... + w_nx_n + b z=w1x1+w2x2+...+wnxn+b
其中 b b b 是偏置项。
3. 激活函数
激活函数用于将加权和转换为输出类别。在经典的感知器模型中,通常使用符号函数(sign function):
y = sign ( z ) y = \text{sign}(z) y=sign(z)
其中 sign ( z ) \text{sign}(z) sign(z) 是一个符号函数,当 z ≥ 0 z \geq 0 z≥0 时输出 +1,否则输出 -1。
感知器的学习规则
感知器通过迭代地调整权重来学习分类边界:
初始化:权重和偏置初始化为0或小的随机数。
对于每个样本:
计算输出 y y y。
更新权重和偏置:
w i = w i + η ( y true − y ) x i w_i = w_i + \eta (y_{\text{true}} - y) x_i wi=wi+η(ytrue−y)xi
b = b + η ( y true − y ) b = b + \eta (y_{\text{true}} - y) b=b+η(ytrue−y)
其中 η \eta η 是学习率, y true y_{\text{true}} ytrue 是真实类别。
代码
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
y_ = np.array([1 if i > 0 else -1 for i in y])
for _ in range(self.n_iterations):
for idx, x_i in enumerate(X):
linear_output = np.dot(x_i, self.weights) + self.bias
y_predicted = np.sign(linear_output)
update = self.learning_rate * (y_[idx] - y_predicted)
self.weights += update * x_i
self.bias += update
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias
return np.sign(linear_output)
# 示例使用
if __name__ == "__main__":
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
data = load_iris()
X = data.data[data.target != 2]
y = data.target[data.target != 2]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)
p = Perceptron(learning_rate=0.01, n_iterations=1000)
p.fit(X_train, y_train)
predictions = p.predict(X_test)
print(f"Perceptron classification accuracy: {accuracy_score(y_test, predictions)}")
这段代码实现了一个基本的感知器模型,包括权重的初始化、训练过程中的权重更新以及预测功能。在示例使用中,它被应用于鸢尾花数据集的一个子集上,用于分类任务。
结论
- 感知器是一种简单有效的线性分类器,尽管它只能处理线性可分的数据。
- 它为更复杂的神经网络模型奠定了基础。