python机器学习工具包scikit-learn
scikit-learn这个非常强大的python机器学习工具包
http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html
S1. 导入数据
大多数数据的格式都是M个N维向量,分为训练集和测试集。所以,知道如何导入向量(矩阵)数据是最为关键的一点。这里要用到numpy来协助。假设数据格式是:
|
Stock prices indicator1 indicator2 2.0 123 1252 1.0 .. .. .. . . . |
导入代码参考:
|
import numpy as np f = open("filename.txt") f.readline() # skip the header data = np.loadtxt(f) X = data[:, 1:] # select columns 1 through end y = data[:, 0] # select column 0, the stock price |
libsvm格式的数据导入:
|
>>> from sklearn.datasets import load_svmlight_file >>> X_train, y_train = load_svmlight_file("/path/to/train_dataset.txt") ... >>>X_train.todense()#将稀疏矩阵转化为完整特征矩阵 |
更多格式数据导入与生成参考:http://scikit-learn.org/stable/datasets/index.html
S2. Supervised Classification 几种常用方法:
Logistic Regression
|
>>> from sklearn.linear_model import LogisticRegression >>> clf2 = LogisticRegression().fit(X, y) >>> clf2 LogisticRegression(C=1.0, intercept_scaling=1, dual=False, fit_intercept=True, penalty='l2', tol=0.0001) >>> clf2.predict_proba(X_new) array([[ 9.07512928e-01, 9.24770379e-02, 1.00343962e-05]]) |
Linear SVM (Linear kernel)
|
>>> from sklearn.svm import LinearSVC >>> clf = LinearSVC() >>> clf.fit(X, Y) >>> X_new = [[ 5.0, 3.6, 1.3, 0.25]] >>> clf.predict(X_new)#reuslt[0] if class label array([0], dtype=int32) |
SVM (RBF or other kernel)
|
>>> from sklearn import svm >>> clf = svm.SVC() >>> clf.fit(X, Y) SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0, degree=3, gamma=0.0, kernel='rbf', probability=False, shrinking=True, tol=0.001, verbose=False) >>> clf.predict([[2., 2.]]) array([ 1.]) |
Naive Bayes (Gaussian likelihood)
|
from sklearn.naive_bayes import GaussianNB >>> from sklearn import datasets >>> gnb = GaussianNB() >>> gnb = gnb.fit(x, y) >>> gnb.predict(xx)#result[0] is the most likely class label |
Decision Tree (classification not regression)
|
>>> from sklearn import tree >>> clf = tree.DecisionTreeClassifier() >>> clf = clf.fit(X, Y) >>> clf.predict([[2., 2.]]) array([ 1.]) |
Ensemble (Random Forests, classification not regression)
|
>>> from sklearn.ensemble import RandomForestClassifier >>> clf = RandomForestClassifier(n_estimators=10) >>> clf = clf.fit(X, Y) >>> clf.predict(X_test) |
S3. Model Selection (Cross-validation)
手工分training data和testing data当然可以了,但是更方便的方法是自动进行,scikit-learn也有相关的功能,这里记录下cross-validation的代码:
|
>>> from sklearn import cross_validation >>> from sklearn import svm >>> clf = svm.SVC(kernel='linear', C=1) >>> scores = cross_validation.cross_val_score(clf, iris.data, iris.target, cv=5)#5-fold cv #change metrics >>> from sklearn import metrics >>> cross_validation.cross_val_score(clf, iris.data, iris.target, cv=5, score_func=metrics.f1_score) #f1 score: http://en.wikipedia.org/wiki/F1_score |
more about cross-validation: http://scikit-learn.org/stable/modules/cross_validation.html
Note: if using LR, clf = LogisticRegression().
S4. Sign Prediction Experiment
数据集,EPINIONS,有user与user之间的trust与distrust关系,以及interaction(对用户评论的有用程度打分)。
Features:网络拓扑feature参考"Predict positive and negative links in online social network",用户交互信息feature。
一共设了3类instances,每类3次训练+测试,训练数据是测试数据的10倍,~80,000个29/5/34维向量,得出下面一些结论。时间 上,GNB最快(所有instance都是2~3秒跑完),DT非常快(有一类instance只用了1秒,其他都要4秒),LR很快(三类 instance的时间分别是2秒,5秒,~30秒),RF也不慢(一个instance9秒,其他26秒),linear kernel的SVM要比LR慢好几倍(所有instance要跑30多秒),RBF kernel的SVM比linear SVM要慢20+倍到上百倍(第一个instance要11分钟,第二个instance跑了近两个小时)。准确度上 RF>LR>DT>GNB>SVM(RBF kernel)>SVM(Linear kernel)。GNB和SVM(linear kernel)、SVM(rbf kernel)在第二类instance上差的比较远(10~20个百分点),LR、DT都差不多,RF确实体现了ENSEMBLE方法的强大,比LR有 较为显著的提升(近2~4个百分点)。(注:由于到该文提交为止,RBF版的SVM才跑完一次测试中的两个instance,上面结果仅基于此。另外,我 还尝试了SGD等方法,总体上都不是特别理想,就不记了)。在feature的有效性上面,用户交互feature比网络拓扑feature更加有效百分 五到百分十。
S5.通用测试源代码
这里是我写的用包括上述算法在内的多种算法的自动分类并10fold cross-validation的python代码,只要输入文件保持本文开头所述的格式(且不包含注释信息),即可用多种不同算法测试分类效果。
python机器学习工具包scikit-learn的更多相关文章
- 【转】常见的python机器学习工具包比较
http://algosolo.com/ 分析对比了常见的python机器学习工具包,包括: scikit-learn mlpy Modular toolkit for Data Processing ...
- python机器学习工具包
1. scikit-learn: Machine Learning in Python scikit-learn是一个基于NumPy, SciPy, Matplotlib的开源机器学习工具包,主要涵盖 ...
- 机器学习框架Scikit Learn的学习
一 安装 安装pip 代码如下:# wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=83 ...
- [Python] 机器学习库资料汇总
声明:以下内容转载自平行宇宙. Python在科学计算领域,有两个重要的扩展模块:Numpy和Scipy.其中Numpy是一个用python实现的科学计算包.包括: 一个强大的N维数组对象Array: ...
- [resource]Python机器学习库
reference: http://qxde01.blog.163.com/blog/static/67335744201368101922991/ Python在科学计算领域,有两个重要的扩展模块: ...
- [转]Python机器学习工具箱
原文在这里 Python在科学计算领域,有两个重要的扩展模块:Numpy和Scipy.其中Numpy是一个用python实现的科学计算包.包括: 一个强大的N维数组对象Array: 比较成熟的(广播 ...
- 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 二.模型评价 模型训练好后,度量模型拟合效果的 ...
随机推荐
- linux环境下git的安装配置
1.查看git的最新版本: 查看最新版git:访问https://www.kernel.org/pub/software/scm/git/或者https://github.com/git/git/re ...
- MySql 中的 FIND_IN_SET 的使用和相关问题
MySql 中的 FIND_IN_SET 的使用和相关问题 QQ 群里有人讨论如果在 category_ids 中打开 12 的分类,而 category_ids 中的 ID 是以 逗号分开的. 使用 ...
- 1、hadoop HA分布式集群搭建
概述 hadoop2中NameNode可以有多个(目前只支持2个).每一个都有相同的职能.一个是active状态的,一个是standby状态的.当集群运行时,只有active状态的NameNode是正 ...
- emacs之配置yasnippet
~/emacsConfig/auto-complete-yasnippet-setting.el (require 'yasnippet) (setq ac-sources (append '(ac- ...
- 一个单元测试 学习 aysnc await
using System; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; name ...
- iis 在站点中新建虚拟目录站点之后,虚拟目录中的 web.config 与 主站点中的 web.config冲突解决方案
在虚拟目录站点中增加如下配置即可:<clear/>
- C++ 实例化对象 p->printX()
一.从栈实例化对象 我们首先定义一个类,类的名字叫TV,里面包括两个成员变量,两个成员函数. class TV // 定义一个电视的类TV { public: ]; // 定义类的属性,一个数组 in ...
- eclipse调试时增加jvm参数
下面的程中我们限制Java 堆的大小为20MB,不可扩展(将堆的最小值-Xms 参数与最大值-Xmx 参数设置为一样即可避免堆自动扩展),通过参数-XX:+HeapDumpOnOutOfMemoryE ...
- [html][javascript]动态增删页面元素
<script type="text/javascript"> function append(event){ var myhref = document.create ...
- 细说Cookie(转)
原文地址:http://www.cnblogs.com/fish-li/archive/2011/07/03/2096903.html#undefined Cookie虽然是个很简单的东西,但它又是W ...