• 面向有监督学习与文本数据的通用分类器


    面向有监督学习与文本数据的通用分类器

    方法源码

    # 将源码命名为 ml.py
    __all__ = ['Classifier']
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    class Classifier:
        def __init__(self, num_classes: int, max_iter: int=200, lr: float=0.1):
            self.max_iter = max_iter # max iteration
            self.lr = lr # learning rate
            self.num_classes = num_classes # categories
            self.scores = []
        
        def __data_matrix(self, X):
            '''
            Parameters
            ----------
            X : numpy.array
                input matrix
    
            Returns
            -------
            numpy.array
                augmented matrix
    
            '''
            ones = np.ones(X.shape[0])
            return np.insert(X, 0, ones, axis=1)
        
        def __softmax(self, horizon):
            '''
            Parameters
            ----------
            horizon : numpy.array
                one line of data-set.
    
            Returns
            -------
            numpy.array
                softmax result.
    
            '''
            return np.exp(horizon) / np.sum(np.exp(horizon))
        
        def fit(self, X, y) -> None:
            '''
            Parameters
            ----------
            X : numpy.array
                data-set to be trained
            
            y : numpy.array
                correct labels
    
            Returns
            -------
            None
    
            '''
            augmented = self.__data_matrix(X)
            self.weights = np.zeros((augmented.shape[1], self.num_classes), dtype=np.float64)
            for step in range(self.max_iter):
                for index in range(augmented.shape[0]):
                    res = self.__softmax(np.dot(augmented[index], self.weights))
                    obj = np.eye(self.num_classes)[int(y[index])]
                    err = res - obj
                    self.weights -= self.lr * np.transpose([augmented[index]]) * err
                score = self.score(X_test, y_test) # working environment store the two values: X_test, y_test
                self.scores.append(score)
                if step % 20 == 0:
                    print("Training Error: {0:<}, Testing Score: {1:<}".format(np.linalg.norm(err), score))
                    
        def score(self, X, y) -> float:
            '''
            Parameters
            ----------
            X : numpy.array
                data-set to be tested
            
            y : numpy.array
                correct labels
    
            Returns
            -------
            float
                correct rate
    
            '''
            X = self.__data_matrix(X)
            corr = 0
            multiply = np.dot(X, self.weights)
            predicted = np.argmax(multiply, axis=1)
            corr += (predicted == y).sum()
            return corr / X.shape[0]
        
        def predict(self, X):
            '''
            Parameters
            ----------
            X : numpy.array
                data-set to be predicted
    
            Returns
            -------
            numpy.array
                 predicted result
    
            '''
            X = self.__data_matrix(X)
            multiply = np.dot(X, self.weights)
            return np.argmax(multiply, axis=1)
    
        def plot(self, color: str="slateblue", mark: str='o', style: str='dashed') -> None:
            '''
            Parameters
            ----------
            color : str
                The color of plot line.
    
            mark : str
                The mark of points.
    
            style : str
                The styple of plot.
    
            Returns
            -------
            None
    
            '''
            axis_x = [num for num in range(1, self.max_iter + 1)]
            # plt.xlabel, plt.ylabel, plt.title
            plt.plot(axis_x, self.scores, c=color, marker=mark, linestyle=style)
            plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134

    测试示例

    1. 环境依赖

    import numpy as np
    import matplotlib.pyplot as plt
    import scipy.io as sio # 用于解析.mat格式数据
    
    • 1
    • 2
    • 3

    2. 加载分类器

    from ml import Classifier # ml.py文件存储着分类器源码
    
    • 1

    3. 数据预处理

    下载实验所需的数据集:textretrieval.mat
    数据集维度是:2866*6603

    def process_data(url) -> tuple:
        data = sio.loadmat(url)
        return data['X'], data['class']
    features, labels = process_data('../data/textretrieval.mat') # 数据集路径由环境部署结构确定
    
    • 1
    • 2
    • 3
    • 4

    4. 拆分数据集

    def pretreat(features, labels) -> tuple:
        labels_mo = np.argwhere(labels == 1)[:, 1] # 对标签进行处理
        return features[:2000, :], features[2000:, :], labels_mo[:2000], labels_mo[2000:]
    X_train, X_test, y_train, y_test = pretreat(features, labels)
    
    • 1
    • 2
    • 3
    • 4

    5. 分类器训练

    model = Classifier(num_classes=10, max_iter=1000, lr=0.1)
    model.fit(X_train, y_train)
    model.score(X_test, y_test)
    
    • 1
    • 2
    • 3

    6. 训练日志

    model.plot(color="slateblue", mark='o', style='dashed')
    
    • 1

    在这里插入图片描述

    Train LossTest Score
    0.94084226740494070.14665127020785218
    0.9120610338426420.35219399538106233
    0.88033044690653840.6189376443418014
    0.84664296831802740.7274826789838337
    0.81192549183442740.7621247113163973
    0.77692144370875490.7875288683602771
    0.74217527528687410.7979214780600462
    0.70807140159703050.8175519630484989
    0.67488334153776170.8233256351039261
    0.64280835900063250.8290993071593533
    0.61198675812569450.8371824480369515
    0.58251267848795040.8418013856812933
    0.55444156161295140.8429561200923787
    0.52779658604848510.8418013856812933
    0.502574696373340.8441108545034642
    0.47875221099517520.8452655889145496
    0.456289857777819660.8464203233256351
    0.43513712796453930.8475750577367206
    0.41523591421781810.8498845265588915
    0.396523459842242630.851039260969977
    0.37893468414877150.851039260969977
    0.36240396694471910.8521939953810623
    0.34686647939071250.8533487297921478
    0.332259144347258060.8556581986143187
    0.318521300792551640.8579676674364896
    0.30559513655133370.8579676674364896
    0.293425943037112670.859122401847575
    0.28196223587341530.859122401847575
    0.27115577655602190.8602771362586605
    0.26096152289189850.8614318706697459
    0.25133752977956150.8602771362586605
    0.24224481687061540.8614318706697459
    0.233647215625798570.8602771362586605
    0.225511205095810350.8602771362586605
    0.217805743269646360.8614318706697459
    0.21050209890962150.8637413394919169
    0.203573687319341280.8637413394919169
    0.19699591237426660.8637413394919169
    0.190746016306653080.8648960739030023
    0.184802938115276930.8660508083140878
    0.179147181015635480.8683602771362586
    0.173760689019130530.8695150115473441
    0.16862673249933920.8706697459584296
    0.163729802446026030.8706697459584296
    0.159055513004599050.8695150115473441
    0.15459051183623610.8683602771362586
    0.150322397800876220.8683602771362586
    0.14623964545371890.8695150115473441
    0.142331535849432950.8706697459584296
    0.138588093162286260.8706697459584296
  • 相关阅读:
    电力监控系统的组网方案与设计
    React之路由的基本操作
    2019 Sichuan Province Programming Contest J. Jump on Axis
    mybatisPlus笔记
    【gradle】idea创建的gradle项目每个mudule有多余的iml文件
    短短 45 分钟发布会,OpenAI 如何再次让 AI 圈一夜未眠
    Beanshell的未授权利用
    字节面试官:“这92道 Spring Boot 面试题都答不上来?”
    基于AVR单片机的移动目标视觉追踪系统设计与实现
    你也可以很硬核「GitHub 热点速览 v.22.13」
  • 原文地址:https://blog.csdn.net/linjing_zyq/article/details/126869722