线性分类器:Batch Perception+Ho_Kashyap+MSE原理及代码实现

本文介绍了批量感知算法、Ho-Kashyap算法及MSE算法的原理与Python实现。批量感知算法通过梯度下降最小化误分类样本,Ho-Kashyap算法则通过最小化误差平方和来优化权重向量,MSE算法则适用于多分类任务。

使用数据

在这里插入图片描述

Batch Perception算法

原理

设有一组样本 y 1 , y 2 , . . . , y n y_1,y_2,...,y_n y1,y2,...,yn,各样本均规范化表示,我们的目的是找一个解向量 a a a ,使 a T y i > 0 a^T y_i>0 aTyi>0。在线性可分的情况下,满足上式的 a a a是无穷的。所以要引出一个损失函数进行优化。这个准则的基本思想是错分样本最少:
J ( a ) = ∑ y ∈ Y ( − a T y ) J(a)=\sum_{y\in Y}(-a^{T}y) J(a)=yY(aTy)
Y Y Y为错分样本集合。我们采用梯度下降来优化目标函数:
∂ J ∂ a = ∑ y ∈ Y ( − y ) \frac{\partial J}{\partial a}=\sum_{y\in Y}(-y) aJ=yY(y)
则有:
a k + 1 = a k − η ∑ y ∈ Y ( − y ) a_{k+1}=a_{k}-η\sum_{y\in Y}(-y) ak+1=akηyY(y)

代码实现

# Define batch perception algorithm
# Input: w1, w2
#   w1: Samples in class 1
#   w2: Samples in class 2
# Output: a, n
#   a: the parameters
#   n: number of iterations
def batch_perception(w1, w2):
    # Generate the normalized augmented samples
    w = trans_sample(w1, w2)
    
    # Initiation
    a = np.zeros_like(w[1])
    eta = 1                             # Learning rate
    theta = np.zeros_like(w[1])+1e-6    # Termination conditions
    n = 0                               # Number of iterations

    # Implement the algorithm
    while True:
        y = np.zeros_like(w[1])
        for sample in w:
            if np.matmul(a.T, sample) <= 0:
                # the sample is misclassified 
                y += sample
        eta_y = eta * y

        if all(np.abs(eta_y)<=theta):
            # if the termination conditions are satisfied, terminate the iteration
            break

        a += eta_y
        n += 1
    
    print ("The dicision surface a is {}\nThe number of iterations is {}.".format(a, n))
    return a, n

Ho-Kashyap算法

原理

刚才的准则函数都是关注于错分样本,而对正确分类的样本则没有考虑在内。MSE准则函数把求解目标从不等式形式变成了等式形式:求取满足 a T y i = b i a^T y_i=b_i aTyi=bi的权向量。在这里, b i b_i bi是任取的正常数。

如果记矩阵 Y ∈ R n ∗ d Y\in R^{n*d} YRnd且其每行都是一个样本 y T y^T yT,向量 b = [ b 1 , b 2 , . . . , b n ] T b=[b_1,b_2,...,b_n]^T b=[b1,b2,...,bn]T,那么就可以表述为存在 Y a = b > 0 Ya=b>0 Ya=b>0。为了求解这个问题,使用MSE准则函数:
J = ∣ ∣ Y a − b ∣ ∣ 2 = ∑ i = 1 n ( a T y i − b i ) 2 J=||Ya-b||^2=\sum_{i=1}^{n}(a^T y_i-b_i)^2 J=Yab2=

代码 `end = start + batch_size if start + batch_size < len(input_features) else len(input_features)` 是一个三元条件表达式,用于确定每个批次数据的结束索引。其逻辑是:如果 `start + batch_size` 小于 `input_features` 的长度,说明当前批次可以完整地取出 `batch_size` 个数据,那么 `end` 就设为 `start + batch_size`;如果 `start + batch_size` 大于或等于 `input_features` 的长度,说明剩余的数据不足 `batch_size` 个,此时 `end` 就设为 `input_features` 的长度,以确保不会越界访问数据。 以下是结合上下文代码的示例,更直观地展示其用法: ```python import torch import numpy as np # 假设 input_features 是输入特征数据 input_features = np.random.rand(100, 5) labels = np.random.rand(100, 1) batch_size = 16 # 模拟神经网络模型 class MyNN(torch.nn.Module): def __init__(self): super(MyNN, self).__init__() self.linear = torch.nn.Linear(5, 1) def forward(self, x): return self.linear(x) my_nn = MyNN() cost = torch.nn.MSELoss() optimizer = torch.optim.Adam(my_nn.parameters(), lr=0.001) for start in range(0, len(input_features), batch_size): end = start + batch_size if start + batch_size < len(input_features) else len(input_features) xx = torch.tensor(input_features[start:end], dtype = torch.float, requires_grad = True) yy = torch.tensor(labels[start:end], dtype = torch.float, requires_grad = True) prediction = my_nn(xx) loss = cost(prediction, yy) optimizer.zero_grad() loss.backward(retain_graph=True) optimizer.step() ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值