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

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

方法源码

# 将源码命名为 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. 环境依赖

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

2. 加载分类器

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

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') # 数据集路径由环境部署结构确定

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)

5. 分类器训练

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

6. 训练日志

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

在这里插入图片描述

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeeGLMath

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值