首页 > 其他分享 >机器学习 之 liblinear的帮助文档翻译

机器学习 之 liblinear的帮助文档翻译

时间:2022-10-31 20:35:26浏览次数:122  
标签:翻译 feature param scipy train 文档 model liblinear


文章目录

  • ​​〇、推荐​​
  • ​​一、liblinear版本​​
  • ​​二、翻译整合​​
  • ​​介绍​​
  • ​​安装​​
  • ​​快速开始​​
  • ​​Scipy快速入门​​
  • ​​设计说明​​
  • ​​数据结构​​
  • ​​效用函数​​
  • ​​附加信息​​
  • ​​三、整体翻译​​
  • ​​四、原文​​

〇、推荐

无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。教程不仅是零基础,通俗易懂,而且非常风趣幽默,像看小说一样!觉得太牛了,所以分享给大家。​​点这里可以跳转到教程。​

一、liblinear版本

liblinear版本:2.21
liblinear官网:​​​https://www.csie.ntu.edu.tw/~cjlin/liblinear/​​​ liblinear作者:Chih-Jen Lin’s,台湾大学(​​https://www.csie.ntu.edu.tw/~cjlin/index.html)​

二、翻译整合

介绍

Python(​​http://www.python.org/)是一种适合快速编程的编程语言​​​ 发展。该工具为LIBLINEAR(一个库)提供了一个简单的Python接口
用于支持向量机(​​http://www.csie.ntu.edu.tw/~cjlin/liblinear)。​​ 该界面非常易于使用,因为其用法与LIBLINEAR的用法相同。该界面是使用内置的Python库“ctypes”开发的。

安装

在Unix系统上,输入

> make

该接口只需要生成的LIBLINEAR共享库
上面的命令。我们假设共享库在LIBLINEAR上
主目录或系统路径。

对于Windows,共享库liblinear.dll已在目录中准备就绪’… \ WINDOWS’。您也可以将其复制到系统目录(例如,
用于Windows XP的’C:\ WINDOWS \ system32 '。要重新生成共享库,
请按照LIBLINEAR README中构建Windows二进制文件的说明进行操作。

快速开始

“Scipy快速入门”将在下一节中介绍。

有两个级别的使用。高级别使用实用功能
在liblinearutil.py中,用法与LIBLINEAR MATLAB接口相同。

>>>来自liblinearutil import *

#以LIBSVM格式读取数据

>>> y,x = svm_read_problem('../ heart_scale')
>>> m = train(y [:200],x [:200],' - c 4')
>>> p_label,p_acc,p_val = predict(y [200:],x [200:],m)

#以python格式构造问题
#密集数据

>>> y,x = [1,-1],[[1,0,1],[ -  1,0,-1]]

#稀疏数据

>>> y,x = [1,-1],[{1:1,3:1},{1:-1,3:-1}]
>>> prob = problem(y,x)
>>> param = parameter(' - s 0 -c 4 -B 1')
>>> m =train(prob,param)

#其他实用功能

>>> save_model('heart_scale.model',m)
>>> m = load_model('heart_scale.model')
>>> p_label,p_acc,p_val = predict(y,x,m,' - b 1')
>>> ACC,MSE,SCC = evaluations(y,p_label)

#获取在线帮助

>>>help (train)

低级用法直接调用liblinear.py导入的C接口。注意
所有参数和返回值都是ctypes格式。你需要处理它们
小心。

>>>来自liblinear import *
>>> prob = problem([1,-1],[{1:1,3:1},{1:-1,3:-1}])
>>> param = parameter(' - c 4')
>>> m = liblinear.train(prob,param)#m是指向模型的ctype指针
#将Python格式的实例转换为feature_nodearray,一个ctypes结构
>>> x0,max_idx = gen_feature_nodearray({1:1,3:1})
>>> label = liblinear.predict(m,x0)

Scipy快速入门

确保已安装Scipy以继续本节。
如果安装了numba(​​​http://numba.pydata.org​​),一些操作会快得多。

有两个级别的使用。高级别使用实用功能
在liblinearutil.py中,用法与LIBLINEAR MATLAB接口相同。

>>>导入scipy
>>>来自liblinearutil import *

#以LIBSVM格式读取数据

>>> y,x = svm_read_problem('../ heart_scale',return_scipy = True)#y:ndarray,x:csr_matrix
>>> m = train(y [:200],x [:200,:],' - c 4')
>>> p_label,p_acc,p_val = predict(y [200:],x [200:,:],m)

#以Scipy格式构造问题
#密集数据:numpy ndarray

>>> y,x = scipy.asarray([1,-1]),scipy.asarray([[1,0,1],[ -  1,0,-1]])

#稀疏数据:scipy csr_matrix((data,(row_ind,col_ind))

>>> y,x = scipy.asarray([1,-1]),scipy.sparse.csr_matrix(([1,1,-1,-1],([0,0,1,1],[ 0,2,0,2])))
>>> prob =problem(y,x)
>>> param = parameter(' - s 0 -c 4 -B 1')
>>> m =train(prob,param)

#以Scipy格式应用数据缩放

>>> y,x = svm_read_problem('../ heart_scale',return_scipy = True)
>>> scale_param = csr_find_scale_param(x,lower = 0)
>>> scaled_x = csr_scale(x,scale_param)

#其他实用功能

>>> save_model('heart_scale.model',m)
>>> m = load_model('heart_scale.model')
>>> p_label,p_acc,p_val = predict(y,x,m,' - b 1')
>>> ACC,MSE,SCC =evaluations(y,p_label)

#获取在线帮助

>>>help (train)

低级用法直接调用liblinear.py导入的C接口。注意
所有参数和返回值都是ctypes格式。你需要处理它们
小心。

>>>来自liblinear import *
>>> prob = problem(scipy.asarray([1,-1]),scipy.sparse.csr_matrix(([1,1,-1,-1],([0,0,1,1],[ 0,2,0,2]))))
>>> param = parameter(' - c 4')
>>> m = liblinear.train(prob,param)#m是指向模型的ctype指针

#将ndarray(索引,数据)的元组转换为feature_nodearray,一个ctypes结构
#请注意,索引从0开始,但以下示例将在内部更改为1:1,3:1

>>> x0,max_idx = gen_feature_nodearray((scipy.asarray([0,2]),scipy.asarray([1,1])))
>>> label = liblinear.predict(m,x0)

设计说明

​有两个文件liblinear.py和liblinearutil.py​​​,分别对应于
低级和高级别使用界面。

在liblinear.py中,我们采用Python内置库“ctypes”来实现
Python可以直接访问定义的C结构和接口函数
在linear.h中。

高级用户可以在liblinear.py中使用结构/函数
避免处理ctypes结构,在liblinearutil.py中我们提供了一些易于使用的方法
功能。用法类似于LIBLINEAR MATLAB接口。

数据结构

从linear.h派生的三个数据结构是node,problem和
参数。它们都包含具有相同名称的字段
linear.h。请仔细访问这些字段,因为您直接使用C结构
而不是Python对象。以下描述引入了附加内容
领域和方法。

在使用数据结构之前,请执行以下命令来加载
LIBLINEAR共享库:

>>> from liblinear import *
  • class feature_node:
    构造一个feature_node。
>>> node = feature_node(idx,val)

idx:整数表示特征索引。
val:浮点数表示特征值。
显示索引和节点的值。

>>> print(node)
  • 功能:gen_feature_nodearray(xi [,feature_max = None])
    从Python列表/元组/字典,numpy ndarray或(索引,数据)元组生成特征向量:
>>> xi_ctype,max_idx = gen_feature_nodearray({1:1,3:1,5:-2})

xi_ctype:返回的feature_nodearray(一个ctypes结构)

max_idx:xi的最大特征索引

feature_max:如果指定了feature_max,则索引大于的特征
feature_max已删除。

  • 课堂问题:
    构造一个问题实例
>>> prob = problem(y,x [,bias = -1])

y:l标签的Python列表/元组/ ndarray(类型必须是int / double)。

x:1。l个训练实例的列表/元组。特征向量
每个训练实例都是一个列表/元组或字典。

  1. l * n numpy ndarray或scipy spmatrix(n:特征数)。

偏差:如果偏差> = 0,则实例x变为[x;偏压];如果<0,则没有偏差项
添加(默认-1)

您还可以通过修改偏差值

>>> prob.set_bias(1)

请注意,如果您的x包含稀疏数据(即字典),则为内部
ctypes数据格式仍然稀疏。

  • class parameter:
构造一个参数实例
>>> param = parameter('training_options')

如果’training_options’为空,则应用LIBLINEAR默认值。

将param设置为LIBLINEAR默认值。
>>> param.set_to_default_values()
解析一串选项。
>>> param.parse_options('training_options')
显示参数值。
>>> print(param)
  • class model:
    有两种方法可以获取模型实例:
>>> model_ = train(y,x)
>>> model_ = load_model('model_file_name')

注意返回的接口函数结构
liblinear.train和liblinear.load_model是一个ctypes指针
model,与返回的模型对象不同
通过train和load_model在liblinearutil.py中。我们提供了一个
函数toPyModel进行转换:

>>> model_ptr = liblinear.train(prob,param)
>>> model_ = toPyModel(model_ptr)

如果您以上述方法以外的方式获得模型,
小心处理,以避免内存泄漏或分段故障。

一些用于访问LIBLINEAR模型的接口函数被包装为
类模型的成员:

>>> nr_feature = model_.get_nr_feature()
>>> nr_class = model_.get_nr_class()
>>> class_labels = model_.get_labels()
>>> is_prob_model = model_.is_probability_model()
>>> is_regression_model = model_.is_regression_model()

决策函数是W * x + b,其中
W是一个nr_class-by-nr_feature矩阵,和
b是大小为nr_class的向量。
访问W_kj(即第k类和第j个特征的系数)
和b_k(即第k类的偏差),使用以下函数。

>>> W_kj = model_.get_decfun_coef(feat_idx = j,label_idx = k)
>>> b_k = model_.get_decfun_bias(label_idx = k)

我们还提供了提取w_k(即,第k行W)和
b_k直接如下。

>>> [w_k,b_k] = model_.get_decfun(label_idx = k)

请注意,w_k是长度为nr_feature的Python列表,这意味着
w_k [0] = W_k1。
对于回归模型,W只是长度为nr_feature的向量。或
set label_idx = 0或省略label_idx参数以访问系数。

>>> W_j = model_.get_decfun_coef(feat_idx = j)
>>> b = model_.get_decfun_bias()
>>> [W,b] = model_.get_decfun()

请注意,在get_decfun_coef,get_decfun_bias和get_decfun中,feat_idx
从1开始,而label_idx从0开始。如果label_idx不在
有效范围(0到nr_class-1),然后返回NaN;如果是feat_idx
不在有效范围内(1到nr_feature),则为零值
回。对于回归模型,将忽略label_idx。

效用函数

要使用实用程序功能,请键入

>>>from liblinearutil import *

上面的命令加载
train():训练线性模型
predict():预测测试数据
svm_read_problem():从LIBSVM格式文件中读取数据。
load_model():加载LIBLINEAR模型。
save_model():将模型保存到文件中。
evaluationations():评估预测结果。

  • 功能:train
    训练有三种方式
>>> model = train(y,x [,'training_options'])
>>> model = train(prob [,'training_options'])
>>> model = train(prob,param)

y:l训练标签的列表/元组/ ndarray(类型必须是int / double)。

x:1。l个训练实例的列表/元组。特征向量
每个训练实例都是一个列表/元组或字典。
2. l * n numpy ndarray或scipy spmatrix(n:特征数)。
training_options:与LIBLINEAR命令格式相同的字符串模式。
prob:通过调用生成的问题实例问题(y,x)。
param:通过调用生成的参数实例
参数( ‘training_options’)
model:返回的模型实例。有关详细信息,请参见linear.h
结构体。如果指定’-v’,则交叉验证为
进行并返回的模型只是一个标量:交叉验证
分类的准确性和回归的均方误差。
如果指定了’-C’选项,则找到最佳参数C.
通过交叉验证。返回的模型是最好的C的元组
以及相应的交叉验证准确性。参数
选择实用程序仅受-s 0和-s 2支持。
用不同的方法多次训练相同的数据
参数,第二种和第三种方式应该更快…
例子:

>>> y,x = svm_read_problem('../ heart_scale')
>>> prob = problem(y,x)
>>> param = parameter(' - s 3 -c 5 -q')
>>> m = train(y,x,' - c 5')
>>> m =train(prob,' - w1 5 -c 5')
>>> m =train(prob,param)
>>> CV_ACC = train(y,x,' - v 3')
>>> best_C,best_rate = train(y,x,' - C -s 0')
>>> m = train(y,x,' - c {0} -s 0'.format(best_C))#使用相同的求解器:-s 0
  • 功能:预测
    要使用模型预测测试数据,请使用
>>> p_labs,p_acc,p_vals = predict(y,x,model [,'predicting_options'])

y:l标签的列表/元组/ ndarray(类型必须是int / double)。
它用于计算精度。如果是真标签,请使用[]
不可用。

x:1。l个训练实例的列表/元组。特征向量
每个训练实例都是一个列表/元组或字典。

  1. l * n numpy ndarray或scipy spmatrix(n:特征数)。

predicting_options:一系列预测选项,格式与
LIBLINEAR的。

model:模型实例。

p_labels:预测标签列表

p_acc:包含准确性(用于分类)的元组,平均值
平方误差和平方相关系数(for
回归)。

p_vals:决策值或概率估计的列表(如果’-b 1’
已指定)。如果k是类的数量,对于决策值,
每个元素包括预测k二进制类的结果
支持向量机。如果k = 2且求解器不是MCSVM_CS,则只有一个决策值
退回。对于概率,每个元素包含k个值
指示测试实例在每个类中的概率。
请注意,此处的类顺序与’model.label’相同
模型结构中的字段。

例:

>>> m = train(y,x,' -  c 5')
>>> p_labels,p_acc,p_vals = predict(y,x,m)
  • 函数:svm_read_problem / load_model / save_model
    通过示例查看用法:
>>> y,x = svm_read_problem('data.txt')
>>> m = load_model('model_file')
>>> save_model('model_file',m)
  • 功能:评估
    使用真值(ty)和预测值计算一些评估
    值(pv):
>>>(ACC,MSE,SCC)= evaluation(ty,pv,useScipy)

ty:真值的列表/元组/ ndarray。
pv:预测值的列表/元组/ ndarray。
useScipy:将ty,pv转换为ndarray,并使用scipy函数进行评估
ACC:准确性。
MSE:均方误差。
SCC:平方相关系数。

  • 功能:csr_find_scale_parameter / csr_scale
    以csr格式缩放数据。
>>> param = csr_find_scale_param(x [,lower = l,upper = u])
>>> x = csr_scale(x,param)

x:数据的csr_matrix。
l:x缩放下限;默认-1。
u:x缩放上限;默认1。

缩放过程是:x * diag(coef)+ ones(1,1)* offset’
param:缩放参数字典,其中param [‘coef’] = coef和param [‘offset’] = offset。
coef:缩放系数的scipy数组。
offset:一个scipy数组的缩放偏移量。

附加信息

该界面由计算机系的Hsiang-Fu Yu编写
国立台湾大学理学院。如果您觉得此工具有用,请
引用LIBLINEAR如下

回覆。范,K.-W。 Chang,C.-J。谢,X.-R。王和C.-J.林。
LIBLINEAR:大型线性分类库,期刊
机器学习研究9(2008),1871-1874。软件可在
​​​http://www.csie.ntu.edu.tw/~cjlin/liblinear​

或查看常见问题页面:

​http://www.csie.ntu.edu.tw/~cjlin/liblinear/faq.html​

三、整体翻译

我翻译的可能不是很准,有什么问题,大家可以指出来,我好改

-------------------------------------
--- LIBLINEAR的Python接口---
-------------------------------------

目录
=================

- 介绍
- 安装
- 快速开始
- Scipy快速入门
- 设计说明
- 数据结构
- 效用函数
- 附加信息

介绍
============

Python(http://www.python.org/)是一种适合快速编程的编程语言
发展。该工具为LIBLINEAR(一个库)提供了一个简单的Python接口
用于支持向量机(http://www.csie.ntu.edu.tw/~cjlin/liblinear)。
该界面非常易于使用,因为其用法与LIBLINEAR的用法相同。该界面是使用内置的Python库“ctypes”开发的。

安装
============

在Unix系统上,输入

>make

该接口只需要生成的LIBLINEAR共享库
上面的命令。我们假设共享库在LIBLINEAR上
主目录或系统路径。

对于Windows,共享库liblinear.dll已在目录中准备就绪
`.. \ WINDOWS'。您也可以将其复制到系统目录(例如,
用于Windows XP的`C:\ WINDOWS \ system32 \'。要重新生成共享库,
请按照LIBLINEAR README中构建Windows二进制文件的说明进行操作。

快速开始
===========

“Scipy快速入门”将在下一节中介绍。

有两个级别的使用。高级别使用实用功能
在liblinearutil.py中,用法与LIBLINEAR MATLAB接口相同。

>>>来自liblinearutil import *
#以LIBSVM格式读取数据
>>> y,x = svm_read_problem('../ heart_scale')
>>> m = train(y [:200],x [:200],' - c 4')
>>> p_label,p_acc,p_val = predict(y [200:],x [200:],m)

#以python格式构造问题
#密集数据
>>> y,x = [1,-1],[[1,0,1],[ - 1,0,-1]]
#稀疏数据
>>> y,x = [1,-1],[{1:1,3:1},{1:-1,3:-1}]
>>> prob = problem(y,x)
>>> param = parameter(' - s 0 -c 4 -B 1')
>>> m =train(prob,param)

#其他实用功能
>>> save_model('heart_scale.model',m)
>>> m = load_model('heart_scale.model')
>>> p_label,p_acc,p_val = predict(y,x,m,' - b 1')
>>> ACC,MSE,SCC = evaluations(y,p_label)

#获取在线帮助
>>>帮助(train)

低级用法直接调用liblinear.py导入的C接口。注意
所有参数和返回值都是ctypes格式。你需要处理它们
小心。

>>>来自liblinear import *
>>> prob = problem([1,-1],[{1:1,3:1},{1:-1,3:-1}])
>>> param = parameter(' - c 4')
>>> m = liblinear.train(prob,param)#m是指向模型的ctype指针
#将Python格式的实例转换为feature_nodearray,一个ctypes结构
>>> x0,max_idx = gen_feature_nodearray({1:1,3:1})
>>> label = liblinear.predict(m,x0)

Scipy快速入门
======================

确保已安装Scipy以继续本节。
如果安装了numba(http://numba.pydata.org),一些操作会快得多。

有两个级别的使用。高级别使用实用功能
在liblinearutil.py中,用法与LIBLINEAR MATLAB接口相同。

>>>导入scipy
>>>来自liblinearutil import *
#以LIBSVM格式读取数据
>>> y,x = svm_read_problem('../ heart_scale',return_scipy = True)#y:ndarray,x:csr_matrix
>>> m = train(y [:200],x [:200,:],' - c 4')
>>> p_label,p_acc,p_val = predict(y [200:],x [200:,:],m)

#以Scipy格式构造问题
#密集数据:numpy ndarray
>>> y,x = scipy.asarray([1,-1]),scipy.asarray([[1,0,1],[ - 1,0,-1]])
#稀疏数据:scipy csr_matrix((data,(row_ind,col_ind))
>>> y,x = scipy.asarray([1,-1]),scipy.sparse.csr_matrix(([1,1,-1,-1],([0,0,1,1],[ 0,2,0,2])))
>>> prob =problem(y,x)
>>> param = parameter(' - s 0 -c 4 -B 1')
>>> m =train(prob,param)

#以Scipy格式应用数据缩放
>>> y,x = svm_read_problem('../ heart_scale',return_scipy = True)
>>> scale_param = csr_find_scale_param(x,lower = 0)
>>> scaled_x = csr_scale(x,scale_param)

#其他实用功能
>>> save_model('heart_scale.model',m)
>>> m = load_model('heart_scale.model')
>>> p_label,p_acc,p_val = predict(y,x,m,' - b 1')
>>> ACC,MSE,SCC =evaluations(y,p_label)

#获取在线帮助
>>>帮助(train)

低级用法直接调用liblinear.py导入的C接口。注意
所有参数和返回值都是ctypes格式。你需要处理它们
小心。

>>>来自liblinear import *
>>> prob = problem(scipy.asarray([1,-1]),scipy.sparse.csr_matrix(([1,1,-1,-1],([0,0,1,1],[ 0,2,0,2]))))
>>> param = parameter(' - c 4')
>>> m = liblinear.train(prob,param)#m是指向模型的ctype指针
#将ndarray(索引,数据)的元组转换为feature_nodearray,一个ctypes结构
#请注意,索引从0开始,但以下示例将在内部更改为1:1,3:1
>>> x0,max_idx = gen_feature_nodearray((scipy.asarray([0,2]),scipy.asarray([1,1])))
>>> label = liblinear.predict(m,x0)

设计说明
==================

有两个文件liblinear.py和liblinearutil.py,分别对应于
低级和高级别使用界面。

在liblinear.py中,我们采用Python内置库“ctypes”来实现
Python可以直接访问定义的C结构和接口函数
在linear.h中。

高级用户可以在liblinear.py中使用结构/函数
避免处理ctypes结构,在liblinearutil.py中我们提供了一些易于使用的方法
功能。用法类似于LIBLINEAR MATLAB接口。

数据结构
===============

从linear.h派生的三个数据结构是node,problem和
参数。它们都包含具有相同名称的字段
linear.h。请仔细访问这些字段,因为您直接使用C结构
而不是Python对象。以下描述引入了附加内容
领域和方法。

在使用数据结构之前,请执行以下命令来加载
LIBLINEAR共享库:

>>> from liblinear import *

- class feature_node:

构造一个feature_node。

>>> node = feature_node(idx,val)

idx:整数表示特征索引。

val:浮点数表示特征值。

显示索引和节点的值。

>>> print(node)

- 功能:gen_feature_nodearray(xi [,feature_max = None])

从Python列表/元组/字典,numpy ndarray或(索引,数据)元组生成特征向量:

>>> xi_ctype,max_idx = gen_feature_nodearray({1:1,3:1,5:-2})

xi_ctype:返回的feature_nodearray(一个ctypes结构)

max_idx:xi的最大特征索引

feature_max:如果指定了feature_max,则索引大于的特征
feature_max已删除。

- 课堂问题:

构造一个问题实例

>>> prob = problem(y,x [,bias = -1])

y:l标签的Python列表/元组/ ndarray(类型必须是int / double)。

x:1。l个训练实例的列表/元组。特征向量
每个训练实例都是一个列表/元组或字典。

2. l * n numpy ndarray或scipy spmatrix(n:特征数)。

偏差:如果偏差> = 0,则实例x变为[x;偏压];如果<0,则没有偏差项
添加(默认-1)

您还可以通过修改偏差值

>>> prob.set_bias(1)
请注意,如果您的x包含稀疏数据(即字典),则为内部
ctypes数据格式仍然稀疏。

- 类参数:

构造一个参数实例

>>> param = parameter('training_options')

如果'training_options'为空,则应用LIBLINEAR默认值。

将param设置为LIBLINEAR默认值。

>>> param.set_to_default_values()

解析一串选项。

>>> param.parse_options('training_options')

显示参数值。

>>> print(param)

- class model:

有两种方法可以获取模型实例:

>>> model_ = train(y,x)
>>> model_ = load_model('model_file_name')

注意返回的接口函数结构
liblinear.train和liblinear.load_model是一个ctypes指针
model,与返回的模型对象不同
通过train和load_model在liblinearutil.py中。我们提供了一个
函数toPyModel进行转换:

>>> model_ptr = liblinear.train(prob,param)
>>> model_ = toPyModel(model_ptr)

如果您以上述方法以外的方式获得模型,
小心处理,以避免内存泄漏或分段故障。

一些用于访问LIBLINEAR模型的接口函数被包装为
类模型的成员:

>>> nr_feature = model_.get_nr_feature()
>>> nr_class = model_.get_nr_class()
>>> class_labels = model_.get_labels()
>>> is_prob_model = model_.is_probability_model()
>>> is_regression_model = model_.is_regression_model()

决策函数是W * x + b,其中
W是一个nr_class-by-nr_feature矩阵,和
b是大小为nr_class的向量。
访问W_kj(即第k类和第j个特征的系数)
和b_k(即第k类的偏差),使用以下函数。

>>> W_kj = model_.get_decfun_coef(feat_idx = j,label_idx = k)
>>> b_k = model_.get_decfun_bias(label_idx = k)

我们还提供了提取w_k(即,第k行W)和
b_k直接如下。

>>> [w_k,b_k] = model_.get_decfun(label_idx = k)

请注意,w_k是长度为nr_feature的Python列表,这意味着
w_k [0] = W_k1。
对于回归模型,W只是长度为nr_feature的向量。或
set label_idx = 0或省略label_idx参数以访问系数。

>>> W_j = model_.get_decfun_coef(feat_idx = j)
>>> b = model_.get_decfun_bias()
>>> [W,b] = model_.get_decfun()

请注意,在get_decfun_coef,get_decfun_bias和get_decfun中,feat_idx
从1开始,而label_idx从0开始。如果label_idx不在
有效范围(0到nr_class-1),然后返回NaN;如果是feat_idx
不在有效范围内(1到nr_feature),则为零值
回。对于回归模型,将忽略label_idx。

效用函数
=================

要使用实用程序功能,请键入

>>>from liblinearutil import *

上面的命令加载
train():训练线性模型
predict():预测测试数据
svm_read_problem():从LIBSVM格式文件中读取数据。
load_model():加载LIBLINEAR模型。
save_model():将模型保存到文件中。
evaluationations():评估预测结果。

- 功能:train

训练有三种方式

>>> model = train(y,x [,'training_options'])
>>> model = train(prob [,'training_options'])
>>> model = train(prob,param)

y:l训练标签的列表/元组/ ndarray(类型必须是int / double)。

x:1。l个训练实例的列表/元组。特征向量
每个训练实例都是一个列表/元组或字典。

2. l * n numpy ndarray或scipy spmatrix(n:特征数)。

training_options:与LIBLINEAR命令格式相同的字符串
模式。

prob:通过调用生成的问题实例
问题(y,x)。

param:通过调用生成的参数实例
参数( 'training_options')

model:返回的模型实例。有关详细信息,请参见linear.h
结构体。如果指定'-v',则交叉验证为
进行并返回的模型只是一个标量:交叉验证
分类的准确性和回归的均方误差。
如果指定了'-C'选项,则找到最佳参数C.
通过交叉验证。返回的模型是最好的C的元组
以及相应的交叉验证准确性。参数
选择实用程序仅受-s 0和-s 2支持。


用不同的方法多次训练相同的数据
参数,第二种和第三种方式应该更快..

例子:
>>> y,x = svm_read_problem('../ heart_scale')
>>> prob = problem(y,x)
>>> param = parameter(' - s 3 -c 5 -q')
>>> m = train(y,x,' - c 5')
>>> m =train(prob,' - w1 5 -c 5')
>>> m =train(prob,param)
>>> CV_ACC = train(y,x,' - v 3')
>>> best_C,best_rate = train(y,x,' - C -s 0')
>>> m = train(y,x,' - c {0} -s 0'.format(best_C))#使用相同的求解器:-s 0

- 功能:预测

要使用模型预测测试数据,请使用

>>> p_labs,p_acc,p_vals = predict(y,x,model [,'predicting_options'])

y:l标签的列表/元组/ ndarray(类型必须是int / double)。
它用于计算精度。如果是真标签,请使用[]
不可用。

x:1。l个训练实例的列表/元组。特征向量
每个训练实例都是一个列表/元组或字典。

2. l * n numpy ndarray或scipy spmatrix(n:特征数)。

predicting_options:一系列预测选项,格式与
LIBLINEAR的。

model:模型实例。

p_labels:预测标签列表

p_acc:包含准确性(用于分类)的元组,平均值
平方误差和平方相关系数(for
回归)。

p_vals:决策值或概率估计的列表(如果'-b 1'
已指定)。如果k是类的数量,对于决策值,
每个元素包括预测k二进制类的结果
支持向量机。如果k = 2且求解器不是MCSVM_CS,则只有一个决策值
退回。对于概率,每个元素包含k个值
指示测试实例在每个类中的概率。
请注意,此处的类顺序与'model.label'相同
模型结构中的字段。

例:

>>> m = train(y,x,' - c 5')
>>> p_labels,p_acc,p_vals = predict(y,x,m)

- 函数:svm_read_problem / load_model / save_model

通过示例查看用法:

>>> y,x = svm_read_problem('data.txt')
>>> m = load_model('model_file')
>>> save_model('model_file',m)

- 功能:评估

使用真值(ty)和预测值计算一些评估
值(pv):

>>>(ACC,MSE,SCC)= evaluation(ty,pv,useScipy)

ty:真值的列表/元组/ ndarray。

pv:预测值的列表/元组/ ndarray。

useScipy:将ty,pv转换为ndarray,并使用scipy函数进行评估

ACC:准确性。

MSE:均方误差。

SCC:平方相关系数。

- 功能:csr_find_scale_parameter / csr_scale

以csr格式缩放数据。

>>> param = csr_find_scale_param(x [,lower = l,upper = u])
>>> x = csr_scale(x,param)

x:数据的csr_matrix。

l:x缩放下限;默认-1。

u:x缩放上限;默认1。

缩放过程是:x * diag(coef)+ ones(1,1)* offset'

param:缩放参数字典,其中param ['coef'] = coef和param ['offset'] = offset。

coef:缩放系数的scipy数组。

offset:一个scipy数组的缩放偏移量。

附加信息
======================

该界面由计算机系的Hsiang-Fu Yu编写
国立台湾大学理学院。如果您觉得此工具有用,请
引用LIBLINEAR如下

回覆。范,K.-W。 Chang,C.-J。谢,X.-R。王和C.-J.林。
LIBLINEAR:大型线性分类库,期刊
机器学习研究9(2008),1871-1874。软件可在
http://www.csie.ntu.edu.tw/~cjlin/liblinear

如有任何问题,请联系Chih-Jen Lin <[email protected]>,
或查看常见问题页面:

http://www.csie.ntu.edu.tw/~cjlin/liblinear/faq.html

四、原文

-------------------------------------
--- Python interface of LIBLINEAR ---
-------------------------------------

Table of Contents
=================

- Introduction
- Installation
- Quick Start
- Quick Start with Scipy
- Design Description
- Data Structures
- Utility Functions
- Additional Information

Introduction
============

Python (http://www.python.org/) is a programming language suitable for rapid
development. This tool provides a simple Python interface to LIBLINEAR, a library
for support vector machines (http://www.csie.ntu.edu.tw/~cjlin/liblinear). The
interface is very easy to use as the usage is the same as that of LIBLINEAR. The
interface is developed with the built-in Python library "ctypes."

Installation
============

On Unix systems, type

> make

The interface needs only LIBLINEAR shared library, which is generated by
the above command. We assume that the shared library is on the LIBLINEAR
main directory or in the system path.

For windows, the shared library liblinear.dll is ready in the directory
`..\windows'. You can also copy it to the system directory (e.g.,
`C:\WINDOWS\system32\' for Windows XP). To regenerate the shared library,
please follow the instruction of building windows binaries in LIBLINEAR README.

Quick Start
===========

"Quick Start with Scipy" is in the next section.

There are two levels of usage. The high-level one uses utility functions
in liblinearutil.py and the usage is the same as the LIBLINEAR MATLAB interface.

>>> from liblinearutil import *
# Read data in LIBSVM format
>>> y, x = svm_read_problem('../heart_scale')
>>> m = train(y[:200], x[:200], '-c 4')
>>> p_label, p_acc, p_val = predict(y[200:], x[200:], m)

# Construct problem in python format
# Dense data
>>> y, x = [1,-1], [[1,0,1], [-1,0,-1]]
# Sparse data
>>> y, x = [1,-1], [{1:1, 3:1}, {1:-1,3:-1}]
>>> prob = problem(y, x)
>>> param = parameter('-s 0 -c 4 -B 1')
>>> m = train(prob, param)

# Other utility functions
>>> save_model('heart_scale.model', m)
>>> m = load_model('heart_scale.model')
>>> p_label, p_acc, p_val = predict(y, x, m, '-b 1')
>>> ACC, MSE, SCC = evaluations(y, p_label)

# Getting online help
>>> help(train)

The low-level use directly calls C interfaces imported by liblinear.py. Note that
all arguments and return values are in ctypes format. You need to handle them
carefully.

>>> from liblinear import *
>>> prob = problem([1,-1], [{1:1, 3:1}, {1:-1,3:-1}])
>>> param = parameter('-c 4')
>>> m = liblinear.train(prob, param) # m is a ctype pointer to a model
# Convert a Python-format instance to feature_nodearray, a ctypes structure
>>> x0, max_idx = gen_feature_nodearray({1:1, 3:1})
>>> label = liblinear.predict(m, x0)

Quick Start with Scipy
======================

Make sure you have Scipy installed to proceed in this section.
If numba (http://numba.pydata.org) is installed, some operations will be much faster.

There are two levels of usage. The high-level one uses utility functions
in liblinearutil.py and the usage is the same as the LIBLINEAR MATLAB interface.

>>> import scipy
>>> from liblinearutil import *
# Read data in LIBSVM format
>>> y, x = svm_read_problem('../heart_scale', return_scipy = True) # y: ndarray, x: csr_matrix
>>> m = train(y[:200], x[:200, :], '-c 4')
>>> p_label, p_acc, p_val = predict(y[200:], x[200:, :], m)

# Construct problem in Scipy format
# Dense data: numpy ndarray
>>> y, x = scipy.asarray([1,-1]), scipy.asarray([[1,0,1], [-1,0,-1]])
# Sparse data: scipy csr_matrix((data, (row_ind, col_ind))
>>> y, x = scipy.asarray([1,-1]), scipy.sparse.csr_matrix(([1, 1, -1, -1], ([0, 0, 1, 1], [0, 2, 0, 2])))
>>> prob = problem(y, x)
>>> param = parameter('-s 0 -c 4 -B 1')
>>> m = train(prob, param)

# Apply data scaling in Scipy format
>>> y, x = svm_read_problem('../heart_scale', return_scipy=True)
>>> scale_param = csr_find_scale_param(x, lower=0)
>>> scaled_x = csr_scale(x, scale_param)

# Other utility functions
>>> save_model('heart_scale.model', m)
>>> m = load_model('heart_scale.model')
>>> p_label, p_acc, p_val = predict(y, x, m, '-b 1')
>>> ACC, MSE, SCC = evaluations(y, p_label)

# Getting online help
>>> help(train)

The low-level use directly calls C interfaces imported by liblinear.py. Note that
all arguments and return values are in ctypes format. You need to handle them
carefully.

>>> from liblinear import *
>>> prob = problem(scipy.asarray([1,-1]), scipy.sparse.csr_matrix(([1, 1, -1, -1], ([0, 0, 1, 1], [0, 2, 0, 2]))))
>>> param = parameter('-c 4')
>>> m = liblinear.train(prob, param) # m is a ctype pointer to a model
# Convert a tuple of ndarray (index, data) to feature_nodearray, a ctypes structure
# Note that index starts from 0, though the following example will be changed to 1:1, 3:1 internally
>>> x0, max_idx = gen_feature_nodearray((scipy.asarray([0,2]), scipy.asarray([1,1])))
>>> label = liblinear.predict(m, x0)

Design Description
==================

There are two files liblinear.py and liblinearutil.py, which respectively correspond to
low-level and high-level use of the interface.

In liblinear.py, we adopt the Python built-in library "ctypes," so that
Python can directly access C structures and interface functions defined
in linear.h.

While advanced users can use structures/functions in liblinear.py, to
avoid handling ctypes structures, in liblinearutil.py we provide some easy-to-use
functions. The usage is similar to LIBLINEAR MATLAB interface.

Data Structures
===============

Three data structures derived from linear.h are node, problem, and
parameter. They all contain fields with the same names in
linear.h. Access these fields carefully because you directly use a C structure
instead of a Python object. The following description introduces additional
fields and methods.

Before using the data structures, execute the following command to load the
LIBLINEAR shared library:

>>> from liblinear import *

- class feature_node:

Construct a feature_node.

>>> node = feature_node(idx, val)

idx: an integer indicates the feature index.

val: a float indicates the feature value.

Show the index and the value of a node.

>>> print(node)

- Function: gen_feature_nodearray(xi [,feature_max=None])

Generate a feature vector from a Python list/tuple/dictionary, numpy ndarray or tuple of (index, data):

>>> xi_ctype, max_idx = gen_feature_nodearray({1:1, 3:1, 5:-2})

xi_ctype: the returned feature_nodearray (a ctypes structure)

max_idx: the maximal feature index of xi

feature_max: if feature_max is assigned, features with indices larger than
feature_max are removed.

- class problem:

Construct a problem instance

>>> prob = problem(y, x [,bias=-1])

y: a Python list/tuple/ndarray of l labels (type must be int/double).

x: 1. a list/tuple of l training instances. Feature vector of
each training instance is a list/tuple or dictionary.

2. an l * n numpy ndarray or scipy spmatrix (n: number of features).

bias: if bias >= 0, instance x becomes [x; bias]; if < 0, no bias term
added (default -1)

You can also modify the bias value by

>>> prob.set_bias(1)

Note that if your x contains sparse data (i.e., dictionary), the internal
ctypes data format is still sparse.

- class parameter:

Construct a parameter instance

>>> param = parameter('training_options')

If 'training_options' is empty, LIBLINEAR default values are applied.

Set param to LIBLINEAR default values.

>>> param.set_to_default_values()

Parse a string of options.

>>> param.parse_options('training_options')

Show values of parameters.

>>> print(param)

- class model:

There are two ways to obtain an instance of model:

>>> model_ = train(y, x)
>>> model_ = load_model('model_file_name')

Note that the returned structure of interface functions
liblinear.train and liblinear.load_model is a ctypes pointer of
model, which is different from the model object returned
by train and load_model in liblinearutil.py. We provide a
function toPyModel for the conversion:

>>> model_ptr = liblinear.train(prob, param)
>>> model_ = toPyModel(model_ptr)

If you obtain a model in a way other than the above approaches,
handle it carefully to avoid memory leak or segmentation fault.

Some interface functions to access LIBLINEAR models are wrapped as
members of the class model:

>>> nr_feature = model_.get_nr_feature()
>>> nr_class = model_.get_nr_class()
>>> class_labels = model_.get_labels()
>>> is_prob_model = model_.is_probability_model()
>>> is_regression_model = model_.is_regression_model()

The decision function is W*x + b, where
W is an nr_class-by-nr_feature matrix, and
b is a vector of size nr_class.
To access W_kj (i.e., coefficient for the k-th class and the j-th feature)
and b_k (i.e., bias for the k-th class), use the following functions.

>>> W_kj = model_.get_decfun_coef(feat_idx=j, label_idx=k)
>>> b_k = model_.get_decfun_bias(label_idx=k)

We also provide a function to extract w_k (i.e., the k-th row of W) and
b_k directly as follows.

>>> [w_k, b_k] = model_.get_decfun(label_idx=k)

Note that w_k is a Python list of length nr_feature, which means that
w_k[0] = W_k1.
For regression models, W is just a vector of length nr_feature. Either
set label_idx=0 or omit the label_idx parameter to access the coefficients.

>>> W_j = model_.get_decfun_coef(feat_idx=j)
>>> b = model_.get_decfun_bias()
>>> [W, b] = model_.get_decfun()

Note that in get_decfun_coef, get_decfun_bias, and get_decfun, feat_idx
starts from 1, while label_idx starts from 0. If label_idx is not in the
valid range (0 to nr_class-1), then a NaN will be returned; and if feat_idx
is not in the valid range (1 to nr_feature), then a zero value will be
returned. For regression models, label_idx is ignored.

Utility Functions
=================

To use utility functions, type

>>> from liblinearutil import *

The above command loads
train() : train a linear model
predict() : predict testing data
svm_read_problem() : read the data from a LIBSVM-format file.
load_model() : load a LIBLINEAR model.
save_model() : save model to a file.
evaluations() : evaluate prediction results.

- Function: train

There are three ways to call train()

>>> model = train(y, x [, 'training_options'])
>>> model = train(prob [, 'training_options'])
>>> model = train(prob, param)

y: a list/tuple/ndarray of l training labels (type must be int/double).

x: 1. a list/tuple of l training instances. Feature vector of
each training instance is a list/tuple or dictionary.

2. an l * n numpy ndarray or scipy spmatrix (n: number of features).

training_options: a string in the same form as that for LIBLINEAR command
mode.

prob: a problem instance generated by calling
problem(y, x).

param: a parameter instance generated by calling
parameter('training_options')

model: the returned model instance. See linear.h for details of this
structure. If '-v' is specified, cross validation is
conducted and the returned model is just a scalar: cross-validation
accuracy for classification and mean-squared error for regression.
If the '-C' option is specified, the best parameter C is found
by cross validation. The returned model is a tuple of the best C
and the corresponding cross-validation accuracy. The parameter
selection utility is supported by only -s 0 and -s 2.


To train the same data many times with different
parameters, the second and the third ways should be faster..

Examples:

>>> y, x = svm_read_problem('../heart_scale')
>>> prob = problem(y, x)
>>> param = parameter('-s 3 -c 5 -q')
>>> m = train(y, x, '-c 5')
>>> m = train(prob, '-w1 5 -c 5')
>>> m = train(prob, param)
>>> CV_ACC = train(y, x, '-v 3')
>>> best_C, best_rate = train(y, x, '-C -s 0')
>>> m = train(y, x, '-c {0} -s 0'.format(best_C)) # use the same solver: -s 0

- Function: predict

To predict testing data with a model, use

>>> p_labs, p_acc, p_vals = predict(y, x, model [,'predicting_options'])

y: a list/tuple/ndarray of l true labels (type must be int/double).
It is used for calculating the accuracy. Use [] if true labels are
unavailable.

x: 1. a list/tuple of l training instances. Feature vector of
each training instance is a list/tuple or dictionary.

2. an l * n numpy ndarray or scipy spmatrix (n: number of features).

predicting_options: a string of predicting options in the same format as
that of LIBLINEAR.

model: a model instance.

p_labels: a list of predicted labels

p_acc: a tuple including accuracy (for classification), mean
squared error, and squared correlation coefficient (for
regression).

p_vals: a list of decision values or probability estimates (if '-b 1'
is specified). If k is the number of classes, for decision values,
each element includes results of predicting k binary-class
SVMs. If k = 2 and solver is not MCSVM_CS, only one decision value
is returned. For probabilities, each element contains k values
indicating the probability that the testing instance is in each class.
Note that the order of classes here is the same as 'model.label'
field in the model structure.

Example:

>>> m = train(y, x, '-c 5')
>>> p_labels, p_acc, p_vals = predict(y, x, m)

- Functions: svm_read_problem/load_model/save_model

See the usage by examples:

>>> y, x = svm_read_problem('data.txt')
>>> m = load_model('model_file')
>>> save_model('model_file', m)

- Function: evaluations

Calculate some evaluations using the true values (ty) and the predicted
values (pv):

>>> (ACC, MSE, SCC) = evaluations(ty, pv, useScipy)

ty: a list/tuple/ndarray of true values.

pv: a list/tuple/ndarray of predicted values.

useScipy: convert ty, pv to ndarray, and use scipy functions to do the evaluation

ACC: accuracy.

MSE: mean squared error.

SCC: squared correlation coefficient.

- Function: csr_find_scale_parameter/csr_scale

Scale data in csr format.

>>> param = csr_find_scale_param(x [, lower=l, upper=u])
>>> x = csr_scale(x, param)

x: a csr_matrix of data.

l: x scaling lower limit; default -1.

u: x scaling upper limit; default 1.

The scaling process is: x * diag(coef) + ones(l, 1) * offset'

param: a dictionary of scaling parameters, where param['coef'] = coef and param['offset'] = offset.

coef: a scipy array of scaling coefficients.

offset: a scipy array of scaling offsets.

Additional Information
======================

This interface was written by Hsiang-Fu Yu from Department of Computer
Science, National Taiwan University. If you find this tool useful, please
cite LIBLINEAR as follows

R.-E. Fan, K.-W. Chang, C.-J. Hsieh, X.-R. Wang, and C.-J. Lin.
LIBLINEAR: A Library for Large Linear Classification, Journal of
Machine Learning Research 9(2008), 1871-1874. Software available at
http://www.csie.ntu.edu.tw/~cjlin/liblinear

For any question, please contact Chih-Jen Lin <[email protected]>,
or check the FAQ page:

http://www.csie.ntu.edu.tw/~cjlin/liblinear/faq.html


标签:翻译,feature,param,scipy,train,文档,model,liblinear
From: https://blog.51cto.com/u_15854865/5811173

相关文章

  • linux文档编辑的命令都有哪些?linux命令详解
    在Linux系统中,所有的操作都是需要执行命令才能完成的,可以说,命令的掌握程度对于Linux运维工程师来说至关重要,本篇文章将为大家介绍几个Linux文档编辑命令,以下是详细的内容:1......
  • 如何实现导入Word文档到kindeditor编辑器中?
    ​ 图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码目前限chrome浏览器使用首先以um-editor的二进制流保存为例:打开umeditor.j......
  • kindeditor改造word文档快速发帖,一键转存
    ​ 如何做到ueditor批量上传word图片?1、前端引用代码<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml......
  • JavaDoc生成自己的API文档
    JavaDoc的注释参数@author作者名@version版本号@since需要的最早java版本@param 函数参数@return返回值@throws异常抛出情况 生成JavaDoc步骤如下代码......
  • 【自然语言处理(NLP)】基于Transformer的中-英机器翻译
    文章目录​​【自然语言处理(NLP)】基于Transformer的中-英机器翻译​​​​前言​​​​(一)、任务描述​​​​(二)、环境配置​​​​一、数据准备​​​​(一)、加载开发......
  • 基于web的网络考试设计与实现-计算机毕业设计源码+LW文档
    摘 要21世纪的今天,随着社会的不断发展与进步,人们对于信息科学化的认识,已由低层次向高层次发展,由原来的感性认识向理性认识提高,管理工作的重要性已逐渐被人们所认识,科学化......
  • 基于web的招标投标系统的设计与实现-计算机毕业设计源码+LW文档
    课题研究的意义;国内外研究现状和发展趋势随着时代的不断发展,我国科学技术水平显著提升。就企业而言,其需要在大环境不断变化的今天进行管理体系的革新,如此才能跟上时代发展......
  • 专业手语翻译预约系统设计与实现-计算机毕业设计源码+LW文档
    网站基于B/S结构,主要功能有:用户管理(用户注册/登录、用户信息修改、冻结用户、用户信息查询);翻译员管理(新译员入职、翻译员离职、翻译员个人信息维护、翻译员信息展示、意向/......
  • WSL 官方文档集锦
    ​​适用于Linux的Windows子系统文档​​​:微软官方文档​​​DockerDesktopWSL2backend​​​:Docker官方文档​​​UsingDockerinWSL2​​:VSCode官方文档​​......
  • 数据库表结构文档生成工具
    背景之前在一家小公司工作时,由于没有完善的应用发布流程,包括配置发布平台,和数据库发布系统,导致测试环境(实际上就是一个IP撑起来的简简单单的服务节点)正常的逻辑,到生产环境(3......