scikit-learn工具学习 - random,mgrid,np.r_ ,np.c_, scatter, axis, pcolormesh, contour, decision_function
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的更多相关文章
- 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 ...
- Scikit Learn: 在python中机器学习
转自:http://my.oschina.net/u/175377/blog/84420#OSC_h2_23 Scikit Learn: 在python中机器学习 Warning 警告:有些没能理解的 ...
- (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探
一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...
- (原创)(四)机器学习笔记之Scikit Learn的Logistic回归初探
目录 5.3 使用LogisticRegressionCV进行正则化的 Logistic Regression 参数调优 一.Scikit Learn中有关logistics回归函数的介绍 1. 交叉 ...
- scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类 (python代码)
scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import ...
- Scikit Learn
Scikit Learn Scikit-Learn简称sklearn,基于 Python 语言的,简单高效的数据挖掘和数据分析工具,建立在 NumPy,SciPy 和 matplotlib 上.
- np.c_与np.r_
import sys reload(sys) sys.setdefaultencoding('utf-8') import numpy as np def test(): ''' numpy函数np. ...
- Git版本控制工具学习
Git代码管理工具学习 分布式管理工具:git 相比较svn它更加的方便,基本上我们的操作都是在本地进行的. Git文件的三种状态:已提交,已修改,以暂存. 已提交:表示文件已经被保存到本地数据库. ...
随机推荐
- ftp通用类2
using System; using System.Net; using System.IO; using System.Text; using System.Net.Sockets; /// &l ...
- 使用jqprint插件完成页面打印
使用jqprint插件完成页面打印 jqprint是一个基于jQuery编写的页面打印的一个小插件,但是不得不承认这个插件确实很厉害,最近的项目中帮了我的大忙,在Web打印的方面,前端的打印基本是靠w ...
- oracle HA 高可用性具体解释(之二,深入解析TAF,以及HA框架)
oracle HA 高可用性具体解释(之中的一个,client.server端服务具体解释):http://write.blog.csdn.net/postedit 我们已经看到TAF是的Oracle ...
- Why I Left the .NET Framework
The .NET Framework was good. Really good. Until it wasn't. Why did I leave .NET? In short, it constr ...
- ListBox使用
一.什么是ListBox? ListBox 是一个显示项集合的控件.一次可以显示 ListBox 中的多个项. ListBox继承自ItemsControl,可以使用Items或者ItemsSourc ...
- Grid布局方式
wp7中Grid布局类似HTML中的表格,但是又不太一致! 为了测试新一个3行3列的Grid 方了方便,剔除掉其它XAML代码 [c-sharp:collapse] view plaincopy ...
- sqlite3 插入数据的时候,返回SQLITE_CONSTRAINT
sqlite3 插入数据的时候.返回SQLITE_CONSTRAINT 原因是:数据库的表的名字是纯数字. 大改这个原因太诡异了.创建的时候能够创建成功. 插入数据的时候就失败,由于表名是纯数字. 附 ...
- Unity3D 经常使用库
JSON.NET:http://james.newtonking.com/json LitJSON: http://lbv.github.io/litjson/ ProtoBuf - net:htt ...
- Android Lint简介
Android Lint是SDK Tools 16 (ADT 16)之后才引入的工具,通过它对Android工程源代码进行扫描和检查,可发现潜在的问题,以便程序员及早修正这个问题.Android Li ...
- Kubernetes中Pod的健康检查
本文介绍 Pod 中容器健康检查相关的内容.配置方法以及实验测试,实验环境为 Kubernetes 1.11,搭建方法参考kubeadm安装kubernetes V1.11.1 集群 0. 什么是 C ...