Shark源码分析(十二):线性SVM

2024-04-27 00:48

本文主要是介绍Shark源码分析(十二):线性SVM,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Shark源码分析(十二):线性SVM

关于svm算法,这个在我关于机器学习的博客中已经描述的比较详实了,这里就不再赘述。svm主要有三种类型,这里我所介绍的是线性svm算法的代码。相较于使用核函数的svm算法,代码的整体框架应该是一样的,只是在对偶问题的求解上所使用的方法可能是不一样的。

LinearClassifier类

这个类所表示的是算法的决策平面,是一个多分类的线性分类模型。定义在<include/shark/Models/LinearClassifier.h>中。

template<class VectorType = RealVector>
class LinearClassifier : public ArgMaxConverter<LinearModel<VectorType> >
{
public:LinearClassifier(){}std::string name() const{ return "LinearClassifier"; }
};

相当简单的一个类,并没有什么好说明的地方。

ArgMaxConverter类

该类是LinearClassifier的基类,其作用是将一个输出的向量通过arg_max操作转变为一个类标记,就是输出分量最大的那一维。该类定义在<include/shark/Models/Converter.h>

template<class Model>
class ArgMaxConverter : public AbstractModel<typename Model::InputType, unsigned int>
{
private:typedef typename Model::BatchOutputType ModelBatchOutputType;
public:typedef typename Model::InputType InputType;typedef unsigned int OutputType;typedef typename Batch<InputType>::type BatchInputType;typedef Batch<unsigned int>::type BatchOutputType;ArgMaxConverter(){ }ArgMaxConverter(Model const& decisionFunction): m_decisionFunction(decisionFunction){ }std::string name() const{ return "ArgMaxConverter<"+m_decisionFunction.name()+">"; }RealVector parameterVector() const{return m_decisionFunction.parameterVector();}void setParameterVector(RealVector const& newParameters){m_decisionFunction.setParameterVector(newParameters);}std::size_t numberOfParameters() const{return m_decisionFunction.numberOfParameters();}Model const& decisionFunction()const{return m_decisionFunction;}Model& decisionFunction(){return m_decisionFunction;}// 计算输入数据的类标签void eval(BatchInputType const& input, BatchOutputType& output)const{ModelBatchOutputType modelResult;m_decisionFunction.eval(input,modelResult);std::size_t batchSize = shark::size(modelResult);output.resize(batchSize);if(modelResult.size2()== 1) //对于二分类的情况{for(std::size_t i = 0; i != batchSize; ++i){// 如果输出大于0表示正类,否则为负类output(i) = modelResult(i,0) > 0.0;}}else{for(std::size_t i = 0; i != batchSize; ++i){output(i) = static_cast<unsigned int>(arg_max(row(modelResult,i)));}}}void eval(BatchInputType const& input, BatchOutputType& output, State& state)const{eval(input,output);}void eval(InputType const & pattern, OutputType& output)const{typename Model::OutputType modelResult;m_decisionFunction.eval(pattern,modelResult);if(modelResult.size()== 1){output = modelResult(0) > 0.0;}else{output = static_cast<unsigned int>(arg_max(modelResult));}}void read(InArchive& archive){archive >> m_decisionFunction;}void write(OutArchive& archive) const{archive << m_decisionFunction;}private:Model m_decisionFunction;
};

在LinearClassifier类的代码中,该模板类的模板参数是LinearModel,这个模板类我们之前已经介绍过了。

AbstractLinearSvmTrainer类

这个类是所有线性svm训练方法的基类。该类定义在<include/shark/Algorithms/Trainers/AbstractSvmTrainer.h>中。

template <class InputType>
class AbstractLinearSvmTrainer
: public AbstractTrainer<LinearClassifier<InputType>, unsigned int>
, public QpConfig
, public IParameterizable
{
public:typedef AbstractTrainer<LinearClassifier<InputType>, unsigned int> base_type;typedef LinearClassifier<InputType> ModelType;AbstractLinearSvmTrainer(double C, bool unconstrained = false): m_C(C), m_unconstrained(unconstrained){ RANGE_CHECK( C > 0 ); }double C() const{ return m_C; }void setC(double C) {RANGE_CHECK( C > 0 );m_C = C;}bool isUnconstrained() const{ return m_unconstrained; }RealVector parameterVector() const{RealVector ret(1);ret(0) = (m_unconstrained ? std::log(m_C) : m_C);return ret;}void setParameterVector(RealVector const& newParameters){SHARK_ASSERT(newParameters.size() == 1);setC(m_unconstrained ? std::exp(newParameters(0)) : newParameters(0));}size_t numberOfParameters() const{ return 1; }// 对于以下的两个类成员,在QpConfig的构造函数中没有为它们赋值。稍后可以看到,它们自己的构造函数中是有默认值的using QpConfig::m_stoppingcondition; // 算法训练的停止条件using QpConfig::m_solutionproperties; // 当前解的一些性质using QpConfig::m_verbosity; // 冗长程度(字面翻译,在后面的代码中体现的不是这个意思),默认值是0,protected:double m_C; // 目标函数中正则化项的系数bool m_unconstrained; // 是否使用log C 代替了C,如果是的话则摆脱了C > 0的限制,并不知道这个有什么用
};

QpStoppingCondition类、QpStopType类和QpSolutionProperties类

这三个类都定义在<include/shark/Algorithms/QP/QuadraticProgram.h>中。

struct QpStoppingCondition
{QpStoppingCondition(double accuracy = 0.001, unsigned long long iterations = 0xffffffff, double value = 1e100, double seconds = 1e100){minAccuracy = accuracy;maxIterations = iterations;targetValue = value;maxSeconds = seconds;}//违反KKT条件的阈值下限double minAccuracy;//最大迭代次数unsigned long long maxIterations;//目标函数值的阈值double targetValue;//算法运行的最长时间double maxSeconds;
};
enum QpStopType
{QpNone = 0,QpAccuracyReached = 1,QpMaxIterationsReached = 4,QpTimeout = 8,
};
struct QpSolutionProperties
{QpSolutionProperties(){type = QpNone;accuracy = 1e100;iterations = 0;value = 1e100;seconds = 0.0;}QpStopType type;double accuracy;     //当前解违反KKT条件的程度unsigned long long iterations; //当前循环的次数double value;    // 当前目标函数的值double seconds; // 当前程序的运行时间
};

LinearCSvmTrainer类

该类就是用于训练线性SVM的,定义在<include/shark/Algorithms/Trainers/CSvmTrainer.h>

template <class InputType>
class LinearCSvmTrainer : public AbstractLinearSvmTrainer<InputType>
{
public:typedef AbstractLinearSvmTrainer<InputType> base_type;LinearCSvmTrainer(double C, bool unconstrained = false) : AbstractLinearSvmTrainer<InputType>(C, unconstrained){}std::string name() const{ return "LinearCSvmTrainer"; }void train(LinearClassifier<InputType>& model, LabeledData<InputType, unsigned int> const& dataset){std::size_t dim = inputDimension(dataset);QpBoxLinear<InputType> solver(dataset, dim);RealMatrix w(1, dim, 0.0);row(w, 0) = solver.solve(base_type::C(),0.0,QpConfig::stoppingCondition(),&QpConfig::solutionProperties(),QpConfig::verbosity() > 0);model.decisionFunction().setStructure(w);}
};

从代码中可以看出,主要还是调用QpBoxLinear类的solve方法来求解。

QpBoxLinear类

该类是利用矩阵分解的方法来求解目标函数是hinge损失函数的线性svm,定义在<include/shark/Algorithms/QP/QpBoxLinear.h>。光看代码你可能会不清楚一些操作的具体含义,需要看一下”A Dual Coordinate Descent Method for Large-scale Linear SVM”这篇论文。

template <class InputT>
class QpBoxLinear
{
public:typedef LabeledData<InputT, unsigned int> DatasetType;typedef typename LabeledData<InputT, unsigned int>::const_element_reference ElementType;QpBoxLinear(const DatasetType& dataset, std::size_t dim): m_data(dataset), m_xSquared(m_data.size()), m_dim(dim){SHARK_ASSERT(dim > 0);for (std::size_t i=0; i<m_data.size(); i++){ElementType x_i = m_data[i];m_xSquared(i) = inner_prod(x_i.input, x_i.input);}}// 参数reg相当于论文中的D_{ii}RealVector solve(double bound,double reg,QpStoppingCondition& stop,QpSolutionProperties* prop = NULL,bool verbose = false){SHARK_ASSERT(bound > 0.0);SHARK_ASSERT(reg >= 0.0);Timer timer;timer.start();std::size_t ell = m_data.size();RealVector alpha(ell, 0.0); // 表示拉格朗日乘子RealVector w(m_dim, 0.0); // 权值向量RealVector pref(ell, 1.0);          // measure of success of individual stepsdouble prefsum = ell;               // normalization constantstd::vector<std::size_t> schedule(ell); // 更新每一个拉格朗日乘子的顺序// prepare countersstd::size_t epoch = 0;std::size_t steps = 0;// prepare performance monitoring for self-adaptationdouble max_violation = 0.0;const double gain_learning_rate = 1.0 / ell;double average_gain = 0.0;bool canstop = true;// outer optimization loopwhile (true){// 计算更新的下标顺序,至于这种算法的原理我就不是很清楚了,论文里也没有说明double psum = prefsum;prefsum = 0.0;std::size_t pos = 0;for (std::size_t i=0; i<ell; i++){double p = pref[i];double num = (psum < 1e-6) ? ell - pos : std::min((double)(ell - pos), (ell - pos) * p / psum);std::size_t n = (std::size_t)std::floor(num);double prob = num - n;if (Rng::uni() < prob) n++;for (std::size_t j=0; j<n; j++){schedule[pos] = i;pos++;}psum -= p;prefsum += p;}SHARK_ASSERT(pos == ell);for (std::size_t i=0; i<ell; i++) std::swap(schedule[i], schedule[Rng::discrete(0, ell - 1)]);// inner loop// 算法的符号与论文中是相反的,包括g,pg和new_a的计算max_violation = 0.0;for (std::size_t j=0; j<ell; j++){// active variablestd::size_t i = schedule[j];ElementType e_i = m_data[i];double y_i = (e_i.label > 0) ? +1.0 : -1.0;// compute gradient and projected gradientdouble a = alpha(i);double wyx = y_i * inner_prod(w, e_i.input);double g = 1.0 - wyx - reg * a;double pg = (a == 0.0 && g < 0.0) ? 0.0 : (a == bound && g > 0.0 ? 0.0 : g);// update maximal KKT violation over the epochmax_violation = std::max(max_violation, std::abs(pg));double gain = 0.0;// 更新参数的过程if (pg != 0.0){// SMO-style coordinate descent stepdouble q = m_xSquared(i) + reg;double mu = g / q; // 该参数同时也表示了a的两次更新之间的差值double new_a = a + mu;// numerically stable updateif (new_a <= 0.0){mu = -a;new_a = 0.0;}else if (new_a >= bound){mu = bound - a;new_a = bound;}// 更新参数alpha(i) = new_a;w += (mu * y_i) * e_i.input;gain = mu * (g - 0.5 * q * mu);steps++;}// update gain-based preferences{if (epoch == 0) average_gain += gain / (double)ell;else{double change = CHANGE_RATE * (gain / average_gain - 1.0);double newpref = std::min(PREF_MAX, std::max(PREF_MIN, pref(i) * std::exp(change)));prefsum += newpref - pref(i);pref[i] = newpref;average_gain = (1.0 - gain_learning_rate) * average_gain + gain_learning_rate * gain;}}}epoch++;if (stop.maxIterations > 0 && ell * epoch >= stop.maxIterations) //这里的最大循环次数指的是内部循环的次数{if (prop != NULL) prop->type = QpMaxIterationsReached;break;}if (timer.stop() >= stop.maxSeconds){if (prop != NULL) prop->type = QpTimeout;break;}if (max_violation < stop.minAccuracy){if (verbose) std::cout << "#" << std::flush;if (canstop){if (prop != NULL) prop->type = QpAccuracyReached;break;}else{// prepare full sweep for a reliable checking of the stopping criterioncanstop = true;for (std::size_t i=0; i<ell; i++) pref[i] = 1.0;prefsum = ell;}}else{if (verbose) std::cout << "." << std::flush;canstop = false;}}timer.stop();// compute solution statisticsstd::size_t free_SV = 0; // 不在决策边界上的支持向量个数std::size_t bounded_SV = 0; // 在决策边界上的支持向量的个数double objective = -0.5 * shark::blas::inner_prod(w, w); //计算最终的目标函数值,但计算的值有些诡异,既不是原问题的目标值也不是对偶问题的目标值for (std::size_t i=0; i<ell; i++){double a = alpha(i);if (a > 0.0){objective += a;objective -= reg/2.0 * a * a;if (a == bound) bounded_SV++;else free_SV++;}}// return solution statisticsif (prop != NULL){prop->accuracy = max_violation;       // this is approximate, but a good guessprop->iterations = ell * epoch;prop->value = objective;prop->seconds = timer.lastLap();}// output solution statistics// 这里verbose只是一个是否需要输出信息的标志if (verbose){std::cout << std::endl;std::cout << "training time (seconds): " << timer.lastLap() << std::endl;std::cout << "number of epochs: " << epoch << std::endl;std::cout << "number of iterations: " << (ell * epoch) << std::endl;std::cout << "number of non-zero steps: " << steps << std::endl;std::cout << "dual accuracy: " << max_violation << std::endl;std::cout << "dual objective value: " << objective << std::endl;std::cout << "number of free support vectors: " << free_SV << std::endl;std::cout << "number of bounded support vectors: " << bounded_SV << std::endl;}// return the solutionreturn w;}protected:DataView<const DatasetType> m_data; // 训练数据            RealVector m_xSquared; //m_data^T m_data                      std::size_t m_dim; // 输入数据的维度              
};

由于线性svm只是针对于二分类问题(当然所有的svm都是这样),如果要对多分类问题建立分类器,则需要使用LinearMcSvmOVATrainer类来训练。

这篇关于Shark源码分析(十二):线性SVM的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/939115

相关文章

Go使用pprof进行CPU,内存和阻塞情况分析

《Go使用pprof进行CPU,内存和阻塞情况分析》Go语言提供了强大的pprof工具,用于分析CPU、内存、Goroutine阻塞等性能问题,帮助开发者优化程序,提高运行效率,下面我们就来深入了解下... 目录1. pprof 介绍2. 快速上手:启用 pprof3. CPU Profiling:分析 C

MySQL表锁、页面锁和行锁的作用及其优缺点对比分析

《MySQL表锁、页面锁和行锁的作用及其优缺点对比分析》MySQL中的表锁、页面锁和行锁各有特点,适用于不同的场景,表锁锁定整个表,适用于批量操作和MyISAM存储引擎,页面锁锁定数据页,适用于旧版本... 目录1. 表锁(Table Lock)2. 页面锁(Page Lock)3. 行锁(Row Lock

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步