使用 scikit-learn 实现多类别及多标签分类算法
多标签分类格式
对于多标签分类问题而言,一个样本可能同时属于多个类别。如一个新闻属于多个话题。这种情况下,因变量yy需要使用一个矩阵表达出来。
而多类别分类指的是y的可能取值大于2,但是y所属类别是唯一的。它与多标签分类问题是有严格区别的。所有的scikit-learn分类器都是默认支持多类别分类的。但是,当你需要自己修改算法的时候,也是可以使用scikit-learn实现多类别分类的前期数据准备的。
多类别或多标签分类问题,有两种构建分类器的策略:One-vs-All及One-vs-One。下面,通过一些例子进行演示如何实现这两类策略。
#
from sklearn.preprocessing import MultiLabelBinarizer
y = [[2,3,4],[2],[0,1,3],[0,1,2,3,4],[0,1,2]]
MultiLabelBinarizer().fit_transform(y)
array([[0, 0, 1, 1, 1],
[0, 0, 1, 0, 0],
[1, 1, 0, 1, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 0, 0]])
One-Vs-The-Rest策略
这个策略同时也称为One-vs-all策略,即通过构造K个判别式(K为类别的个数),第ii个判别式将样本归为第ii个类别或非第ii个类别。这种分类方法虽然比较耗时间,但是能够通过每个类别对应的判别式获得关于该类别的直观理解(如文本分类中每个话题可以通过只属于该类别的高频特征词区分)。
多类别分类学习
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
iris = datasets.load_iris()
X,y = iris.data,iris.target
OneVsRestClassifier(LinearSVC(random_state = 0)).fit(X,y).predict(X)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
多标签分类学习
Kaggle上有一个关于多标签分类问题的竞赛:Multi-label classification of printed media articles to topics。
关于该竞赛的介绍如下:
This is a multi-label classification competition for articles coming from Greek printed media. Raw data comes from the scanning of print media, article segmentation, and optical character segmentation, and therefore is quite noisy. Each article is examined by a human annotator and categorized to one or more of the topics being monitored. Topics range from specific persons, products, and companies that can be easily categorized based on keywords, to more general semantic concepts, such as environment or economy. Building multi-label classifiers for the automated annotation of articles into topics can support the work of human annotators by suggesting a list of all topics by order of relevance, or even automate the annotation process for media and/or categories that are easier to predict. This saves valuable time and allows a media monitoring company to expand the portfolio of media being monitored.
我们从该网站下载相应的数据,作为多标签分类的案例学习。
数据描述
这个文本数据集已经用词袋模型进行形式化表示,共201561个特征词,每个文本对应一个或多个标签,共203个分类标签。该网站提供了两种数据格式:ARFF和LIBSVM,ARFF格式的数据主要适用于weka,而LIBSVM格式适用于matlab中的LIBSVM模块。这里,我们采用LIBSVM格式的数据。
数据的每一行以逗号分隔的整数序列开头,代表类别标签。紧接着是以\t分隔的id:value对。其中,id为特征词的ID,value为特征词在该文档中的TF-IDF值。
形式如下。
58,152 833:0.032582 1123:0.003157 1629:0.038548 ...
数据载入
# load modules
import os
import sys
import numpy as np
from sklearn.datasets import load_svmlight_file
from sklearn.preprocessing import LabelBinarizer
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn import metrics
# set working directory
os.chdir("D:\\my_python_workfile\\Thesis\\kaggle_multilabel_classification")
# read files
X_train,y_train = load_svmlight_file("./data/wise2014-train.libsvm",dtype=np.float64,multilabel=True)
X_test,y_test = load_svmlight_file("./data/wise2014-test.libsvm",dtype = np.float64,multilabel=True)
模型拟合及预测
# transform y into a matrix
mb = MultiLabelBinarizer()
y_train = mb.fit_transform(y_train)
# fit the model and predict
clf = OneVsRestClassifier(LogisticRegression(),n_jobs=-1)
clf.fit(X_train,y_train)
pred_y = clf.predict(X_test)
模型评估
由于没有关于测试集的真实标签,这里看看训练集的预测情况。
# training set result
y_predicted = clf.predict(X_train)
#report
#print(metrics.classification_report(y_train,y_predicted))
import numpy as np
np.mean(y_predicted == y_train)
0.99604661023482433
保存结果
# write the output
out_file = open("pred.csv","w")
out_file.write("ArticleId,Labels\n")
id = 64858
for i in xrange(pred_y.shape[0]):
label = list(mb.classes_[np.where(pred_y[i,:]==1)[0]].astype("int"))
label = " ".join(map(str,label))
if label == "": # if the label is empty
label = "103"
out_file.write(str(id+i)+","+label+"\n")
out_file.close()
One-Vs-One策略
One-Vs-One策略即是两两类别之间建立一个判别式,这样,总共需要K(K−1)/2K(K−1)/2个判别式,最后通过投票的方式确定样本所属类别。
多类别分类学习
from sklearn import datasets
from sklearn.multiclass import OneVsOneClassifier
from sklearn.svm import LinearSVC
iris = datasets.load_iris()
X,y = iris.data,iris.target
OneVsOneClassifier(LinearSVC(random_state = 0)).fit(X,y).predict(X)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
参考文献
http://yphuang.github.io/blog/2016/04/22/Multiclass-and-Multilabel-algorithms-Implementation-in-sklearn/
使用 scikit-learn 实现多类别及多标签分类算法的更多相关文章
- (原创)(四)机器学习笔记之Scikit Learn的Logistic回归初探
目录 5.3 使用LogisticRegressionCV进行正则化的 Logistic Regression 参数调优 一.Scikit Learn中有关logistics回归函数的介绍 1. 交叉 ...
- Scikit Learn: 在python中机器学习
转自:http://my.oschina.net/u/175377/blog/84420#OSC_h2_23 Scikit Learn: 在python中机器学习 Warning 警告:有些没能理解的 ...
- scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类 (python代码)
scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import ...
- (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探
一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...
- Scikit Learn
Scikit Learn Scikit-Learn简称sklearn,基于 Python 语言的,简单高效的数据挖掘和数据分析工具,建立在 NumPy,SciPy 和 matplotlib 上.
- Linear Regression with Scikit Learn
Before you read This is a demo or practice about how to use Simple-Linear-Regression in scikit-lear ...
- 如何使用scikit—learn处理文本数据
答案在这里:http://www.tuicool.com/articles/U3uiiu http://scikit-learn.org/stable/modules/feature_extracti ...
- Query意图分析:记一次完整的机器学习过程(scikit learn library学习笔记)
所谓学习问题,是指观察由n个样本组成的集合,并根据这些数据来预测未知数据的性质. 学习任务(一个二分类问题): 区分一个普通的互联网检索Query是否具有某个垂直领域的意图.假设现在有一个O2O领域的 ...
- 机器学习框架Scikit Learn的学习
一 安装 安装pip 代码如下:# wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=83 ...
随机推荐
- mysql函数的使用create function myfunction(...
use test //必须在某个数据库下面创建 delimiter $ //创建 CREATE FUNCTION myFunction(ln int, ls int) //参数这里不能加def ...
- PHP“Cannot use object of type stdClass as array”
php再调用json_decode从字符串对象生成json对象时,如果使用[]操作符取数据,会得到下面的错误 错误:Cannot use object of type stdClass as arra ...
- [Bug]IE11下,forms认证,出现无法保存cookie的问题
目录 ie11 解决方案 ie11 在ie11下,访问服务器上的网站地址,莫名其妙的多出一串东西,这一串字符串是由于客户端禁用cookie造成sessionid无法写入cookie,所以就拼在url上 ...
- vs code 使用Git进行源代码管理
第一步:用vs code 打开一个空文件夹,如本示例Demo2, 第二步:点击左侧第三个图标“源代码管理”,然后再点击初始化存储库按钮 初始化之后界面现变成下图所示: 此时文件夹中会新增一个隐藏文件夹 ...
- 两款工控控件对比评测:Iocomp和ProEssentials
对于程序员来说,要凭一己之力开发出漂亮逼真的工控仪表和工控图表是非常耗时间和精力的,那么使用专业的第三方控件就是不错的选择,不仅节约开发时间,降低了项目风险,最重要的是第三方控件写的程序更专业,工控图 ...
- tomcat下配置https环境(windows环境)
在网上搜了一下,内容不是很完善.现进行整理,做个学习笔记,以备以后使用. (1)进入到jdk下的bin目录 (2)输入如下指令“keytool -v -genkey -alias tomcat -ke ...
- mac 下安装 plink
1. 直接 brew install putty. 其自带 plink工具.
- 深入理解C#中的泛型(一)
为什么要有泛型? 请大家思考一个问题:由你来实现一个最简单的冒泡排序算法.假设没有使用泛型的经验.可能会毫不犹豫的写出下面代码: public class SortHelper { //參数为int数 ...
- RESTful最佳实践
哲学 不要为了RESTful而RESTful 在能表达清楚的情况下,简单就是美 接口路径设计 接口设计原则 URI指向的是唯一的资源对象 示例: 指向ID为yanbo.ai的Account对象 GET ...
- WORD中无损复制图片
问题 默认 Ctrl+C复制出来图片图片的严重模糊,复制出来的不是原图片!因为图片尺寸被修改后复制出来的则是模糊的 解决办法 解决办法把WORD中的图片恢复成默认的,如果对图片进行了缩放请把缩放比恢复 ...