yuanwen: http://blog.csdn.net/crossky_jing/article/details/49466127

scikit-learn 练习题 
题目:Try classifying classes 1 and 2 from the iris dataset with SVMs, with the 2 first features. Leave out 10% of each class and test prediction performance on these observations.(链接:http://scikit-learn.org/stable/tutorial/statistical_inference/supervised_learning.html) 
官方提供的答案如文末代码段 
通过这段源代码,我们主要可以学习到如下几个常用函数的使用:

numpy 库

import numpy as np

1、random

用法:产生伪随机数 
样例: 
np.random.seed(0) //产生以0为种子的伪随机数生成器 
order_arr = np.random.permutation(100) //返回100个伪随机数,返回值是一个array

2、mgrid

用法:返回多维结构,常见的如2D图形,3D图形。对比np.meshgrid,在处理大数据时速度更快,且能处理多维(np.meshgrid只能处理2维) 
ret = np.mgrid[ 第1维,第2维 ,第3维 , …] 
返回多值,以多个矩阵的形式返回,第1返回值为第1维数据在最终结构中的分布,第2返回值为第2维数据在最终结构中的分布,以此类推。(分布以矩阵形式呈现) 
例如np.mgrid[X , Y] 
样本(i,j)的坐标为 (X[i,j] ,Y[i,j]),X代表第1维,Y代表第2维,在此例中分别为横纵坐标。

例如1D结构(array),如下:

>>> pp = np.mgrid[-5:5:5j]
>>> pp
array([-5. , -2.5, 0. , 2.5, 5. ])
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

例如2D结构 (2D矩阵),如下:

>>> pp = np.mgrid[-1:1:2j,-2:2:3j]
>>> x , y = pp
>>> x
array([[-1., -1., -1.],
[ 1., 1., 1.]])
>>> y
array([[-2., 0., 2.],
[-2., 0., 2.]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

例如3D结构 (3D立方体),如下:

>>> pp = np.mgrid[-1:1:2j,-2:2:3j,-3:3:5j]
>>> print pp
[[[[-1. -1. -1. -1. -1. ]
[-1. -1. -1. -1. -1. ]
[-1. -1. -1. -1. -1. ]] [[ 1. 1. 1. 1. 1. ]
[ 1. 1. 1. 1. 1. ]
[ 1. 1. 1. 1. 1. ]]] [[[-2. -2. -2. -2. -2. ]
[ 0. 0. 0. 0. 0. ]
[ 2. 2. 2. 2. 2. ]] [[-2. -2. -2. -2. -2. ]
[ 0. 0. 0. 0. 0. ]
[ 2. 2. 2. 2. 2. ]]] [[[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]] [[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]]]]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

3、np.r_ , np.c_

用法:concatenation function 
np.r_按row来组合array, 
np.c_按colunm来组合array

>>> a = np.array([1,2,3])
>>> b = np.array([5,2,5])
>>> //测试 np.r_
>>> np.r_[a,b]
array([1, 2, 3, 5, 2, 5])
>>>
>>> //测试 np.c_
>>> np.c_[a,b]
array([[1, 5],
[2, 2],
[3, 5]])
>>> np.c_[a,[0,0,0],b]
array([[1, 0, 5],
[2, 0, 2],
[3, 0, 5]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

matplotlib.pyplot 库

import matplotlib.pyplot as plt

1、scatter

用来画散点图的,对样本点着色。如下:X为一个n*2的矩阵,代表n个2维样本点,且每个样本点对应一个label y,用y来对颜色变量c赋值来区分颜色,按照cmap来布局。 
plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired)

2、axis

用法:设置布局策略 
例如: plt.axis(‘tight’) ,表明采用紧致方案,需要将样本的边缘作为画布的边缘。

3、pcolormesh

用法:类似np.pcolor ,是对坐标点着色。 
np.pcolormesh(X, Y, C, **kwargs) 
例如有样本点(X[i,j] , Y[i,j]),对样本周围(包括样本所在坐标)的四个坐标点进行着色,C代表着色方案,kwargs里可以设置着色配置。

(X[i,   j],   Y[i,   j]),
(X[i, j+1], Y[i, j+1]),
(X[i+1, j], Y[i+1, j]),
(X[i+1, j+1], Y[i+1, j+1]).
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

样例:plt.pcolormesh(XX, YY, Z>0, cmap=plt.cm.Paired)

4、contour

用法:画轮廓 
样例:plt.contour(XX, YY, Z, colors=[‘k’, ‘k’, ‘k’], linestyles=[‘–’, ‘-‘, ‘–’],levels=[-.5, 0, .5])

svm 库

from sklearn import svm

1、decision_function

用法:Distance of the samples X to the separating hyperplane. 即样本点到超平面的距离。 
样例:

x_min = X[:, 0].min()
x_max = X[:, 0].max()
y_min = X[:, 1].min()
y_max = X[:, 1].max() XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] //分别得到样本第1维和第2维的分布:
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) //用np.c_()将XX,YY拉平后的两个array按照列合并(此时是n*2的举证,有n个样本点,每个样本点有横纵2维),然后调用分类器集合的decision_function函数获得样本到超平面的距离。Z是一个n*1的矩阵(列向量),记录了n个样本距离超平面的距离。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

附录(完整代码):

http://scikit-learn.org/stable/_downloads/plot_iris_exercise.py

"""
================================
SVM Exercise
================================ A tutorial exercise for using different SVM kernels. This exercise is used in the :ref:`using_kernels_tut` part of the
:ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`.
"""
print(__doc__) import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm iris = datasets.load_iris()
X = iris.data
y = iris.target X = X[y != 0, :2]
y = y[y != 0] n_sample = len(X) np.random.seed(0)
order = np.random.permutation(n_sample)
X = X[order]
y = y[order].astype(np.float) X_train = X[:.9 * n_sample]
y_train = y[:.9 * n_sample]
X_test = X[.9 * n_sample:]
y_test = y[.9 * n_sample:] # fit the model
for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')):
clf = svm.SVC(kernel=kernel, gamma=10)
clf.fit(X_train, y_train) plt.figure(fig_num)
plt.clf()
plt.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired) # Circle out the test data
plt.scatter(X_test[:, 0], X_test[:, 1], s=80, facecolors='none', zorder=10) plt.axis('tight')
x_min = X[:, 0].min()
x_max = X[:, 0].max()
y_min = X[:, 1].min()
y_max = X[:, 1].max() XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot
Z = Z.reshape(XX.shape)
plt.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],
levels=[-.5, 0, .5]) plt.title(kernel)
plt.show()

scikit-learn工具学习 - random,mgrid,np.r_ ,np.c_, scatter, axis, pcolormesh, contour, decision_function的更多相关文章

  1. Query意图分析:记一次完整的机器学习过程(scikit learn library学习笔记)

    所谓学习问题,是指观察由n个样本组成的集合,并根据这些数据来预测未知数据的性质. 学习任务(一个二分类问题): 区分一个普通的互联网检索Query是否具有某个垂直领域的意图.假设现在有一个O2O领域的 ...

  2. 机器学习框架Scikit Learn的学习

    一   安装 安装pip 代码如下:# wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=83 ...

  3. Scikit Learn: 在python中机器学习

    转自:http://my.oschina.net/u/175377/blog/84420#OSC_h2_23 Scikit Learn: 在python中机器学习 Warning 警告:有些没能理解的 ...

  4. (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探

    一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...

  5. (原创)(四)机器学习笔记之Scikit Learn的Logistic回归初探

    目录 5.3 使用LogisticRegressionCV进行正则化的 Logistic Regression 参数调优 一.Scikit Learn中有关logistics回归函数的介绍 1. 交叉 ...

  6. scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类 (python代码)

    scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import ...

  7. Scikit Learn

    Scikit Learn Scikit-Learn简称sklearn,基于 Python 语言的,简单高效的数据挖掘和数据分析工具,建立在 NumPy,SciPy 和 matplotlib 上.

  8. np.c_与np.r_

    import sys reload(sys) sys.setdefaultencoding('utf-8') import numpy as np def test(): ''' numpy函数np. ...

  9. Git版本控制工具学习

    Git代码管理工具学习 分布式管理工具:git 相比较svn它更加的方便,基本上我们的操作都是在本地进行的. Git文件的三种状态:已提交,已修改,以暂存. 已提交:表示文件已经被保存到本地数据库. ...

随机推荐

  1. QNJR-GROUP/EasyTransaction: 依赖于Spring的一个柔性事务实现,包含 TCC事务,补偿事务,基于消息的最终一致性事务,基于消息的最大努力交付事务交付QNJR-GROUP/EasyTransaction: 依赖于Spring的一个柔性事务实现,包含 TCC事务,补偿事务,基于消息的最终一致性事务,基于消息的最大努力交付事务交付

    QNJR-GROUP/EasyTransaction: 依赖于Spring的一个柔性事务实现,包含 TCC事务,补偿事务,基于消息的最终一致性事务,基于消息的最大努力交付事务交付 大规模SOA系统的分 ...

  2. 巧用CSS3 :target 伪类制作Dropdown下拉菜单(无JS)

    :target 是CSS3 中新增的一个伪类,用以匹配当前页面的URI中某个标志符的目标元素(比如说当前页面URL下添加#comment就会定位到id=“comment”的位置,俗称锚).CSS3 为 ...

  3. ZOJ 3765 Lights (伸展树splay)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3765 Lights Time Limit: 8 Seconds ...

  4. ASP.Net中关于WebAPI与Ajax进行跨域数据交互时Cookies数据的传递

    本文主要介绍了ASP.Net WebAPI与Ajax进行跨域数据交互时Cookies数据传递的相关知识.具有很好的参考价值.下面跟着小编一起来看下吧 前言 最近公司项目进行架构调整,由原来的三层架构改 ...

  5. delphi project of object

    http://www.cnblogs.com/ywangzi/archive/2012/08/28/2659811.html 其实要了解这些东西,适当的学些反汇编,WINDOWS内存管理机制,PE结构 ...

  6. 移动web前端小结

    原文地址:http://blog.csdn.net/small_rice_/article/details/22690535 在智能手机横行的时代,作为一个web前端,不会编写移动web界面,的确是件 ...

  7. SQL Server 2008 安装教程

    http://www.downcc.com/tech/4135.html 序列号:Developer: PTTFM-X467G-P7RH2-3Q6CG-4DMYB

  8. 【linux】在linux上生成SSH-key 简单原理介绍+生成步骤

    1.首先什么是SSH Secure Shell (SSH) 是一个允许两台电脑之间通过安全的连接进行数据交换的网络协议.通过加密保证了数据的保密性和完整性.SSH采用公钥加密技术来验证远程主机,以及( ...

  9. RDIFramework.NET V2.7 Web版本号升手风琴+树型文件夹(2级+)方法

    级+)"界面风格,以展示多级功能菜单,满足用户的要求.Web展示效果例如以下: 要以"手风琴+树型文件夹(2级+)"的风格来展示功能模块,我们须要在"系统配置& ...

  10. Java利用QRCode.jar包实现二维码编码与解码

    QRcode是日本人94年开发出来的.首先去QRCode的官网http://swetake.com/qrcode/java/qr_java.html,把要用的jar包下下来,导入到项目里去.qrcod ...