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. ant design的一些坑

    1.在本地修改ant design的某些样式可以生效,但在线上就失效了.比如collapse组件里的箭头图标在本地和在线上的类名有变化,本地类名,线上类名:箭头图标的svg样式在线上会自动添加一个内联 ...

  2. CentOS 7安装Gitlab时报错:undefined method `downcase' for nil:NilClass

    说明:其实这事怪我,我把系统的某些配置改了. 首先分析这个错误出现的位置在这个文件: /opt/gitlab/embedded/cookbooks/cache/cookbooks/package/li ...

  3. brew安装sshpass

    有以下解决方法: # 1 brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formu ...

  4. @Transactional导致AbstractRoutingDataSource动态数据源无法切换的解决办法

    上午花了大半天排查一个多数据源主从切换的问题,记录一下: 背景: 项目的数据库采用了读写分离多数据源,采用AOP进行拦截,利用ThreadLocal及AbstractRoutingDataSource ...

  5. HDU 4786 Fibonacci Tree (2013成都1006题)

    Fibonacci Tree Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  6. oracle 两个逗号分割的字符串 如何判断是否其中有相同值

    比如字段A: 'ab,cd,ef,gh'字段B: 'aa,bb,cc,dd' 没有相同值 字段A: 'ab,cd,ef,gh'字段B: 'aa,bb,cd,dd' 有相同值cd 1.CREATE OR ...

  7. MFC之菜单

    1菜单与菜单项的操作 //获取菜单指针----CWnd::GetMenu() //GetSubMenu()获取子菜单 /CheckMenuItem()加入/取消标记 GetMenu()->Get ...

  8. C#编程(七十)----------dynamic类型

    原文链接 : http://blog.csdn.net/shanyongxu/article/details/47296033 dynamic类型 C#新增了dynamic关键字,正是因为这一个小小的 ...

  9. Android tips(八)-->Android Studio打包apk,aar,jar包

    文本我们将讲解android studio打包apk,aar,jar包的相关知识.apk包就是android系统的安装包,这里没什么好说的,aar包是android中独有的类库包,而jar包是java ...

  10. 实用ExtJS教程100例-006:ExtJS中Window的用法示例

    在前面几个示例中,我们演示了MessageBox的各种用法,今天这篇文章将演示如何使用Window. 我们首先来创建一个窗口: var win = Ext.create("Ext.windo ...