机器学习--感知器分类算法

本文介绍了一个简单的感知器分类器实现,通过Python代码演示了如何进行训练及错误次数的记录,并展示了分类结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说,直接上代码.原理很
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

    #! /usr/bin/env python  
#coding=utf-8  
import numpy as np  
import unittest
import matplotlib.pylab as plt
#感知器分类的学习  
class Perceptron:  
    ''''' 
    eta:学习率 
    n_iter:权重向量的训练次数 
    w_:权重向量 
    errors_:记录神经元判断出错的次数 
     
    '''  
    def __init__(self, alpha=0.01, n_iter=20):
        self.alpha = alpha
        self.n_iter = n_iter

    def fit(self, X, Y):
        m, n = shape(X)#返回训练数据集的行数与列数  这里的n代表有多少个
        self.intercept = 0
        self.W = mat(ones((n, 1)))

        for i in range(self.n_iter):
            for x, y in zip(X, Y):
                y_ = float(x * self.W) + self.intercept 
                if y * y_ < 0:  #由于是感知器,所以这里我们使用阶跃函数
                    self.W += x.T * self.alpha * y #修改其权值
                    self.intercept += self.alpha * y #修改其偏置值
            if self.loss(X, Y) == 0: #如果所是函数的值符合要求,那么我们就返回
                return i

    def loss(self, X, Y):
        sum_loss = 0.0
        for x, y in zip(X, Y):
            y_ = float(x * self.W) + self.intercept
            if y * y_ < 0:
                sum_loss += - y * y_
        return sum_loss
class PerceptronTest(unittest.TestCase):
    def test_fit(self):
        X = mat(array([[2, 4.3], [1, 2.4], [1, 3.3], [2, 1.8], [3, 9.2], [4, 6.3], [5, 10.1], [2.3, 3.4], [3.2, 6]]))
        Y = np.array([1, 1, 1, -1, 1, -1, 1, -1, -1])
        icons = {1: 'ko', -1: 'bo'}
        # print X
        for x, y in zip(X, Y): #Python中的zip函数
            plt.plot(x[0, 0], x[0, 1], icons[y])
        perceptron = Perceptron(alpha=0.1, n_iter=20)
        print (perceptron.fit(X, Y))
        # points on the hyperplane
        p1 = [0, -perceptron.intercept / perceptron.W[1, 0]]
        p2 = [5, (-perceptron.intercept - 5 * perceptron.W[0, 0]) / perceptron.W[1, 0]]
        # print the hyperplane
        plt.plot([p1[0], p2[0]], [p1[1], p2[1]])
        plt.title("gan zhi qi er fen lei")
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.show()
if __name__ == '__main__':
    unittest.main()  #这里是测试代码,供我们测试时使用...

简单,注意的是这里的激活函数是单位阶跃函数.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值