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文件的三种状态:已提交,已修改,以暂存. 已提交:表示文件已经被保存到本地数据库. ...
随机推荐
- CentOS下使用autoenv实现进入特定目录后运行特定环境变量
安装 # Mac git clone git://github.com/kennethreitz/autoenv.git ~/.autoenv # 安装默认shell echo 'source ~/. ...
- TIMER门控模式控制PWM输出长度
TIMER门控模式控制PWM输出长度 参照一些网友代码做了些修改,由TIM4来控制TIM2的PWM输出长度, 采用主从的门控模式,即TIM4输出高时候TIM2使能输出 //TIM2 PWM输出,由TI ...
- 使用winrar自解压功能制作安装包
参考文献: bat脚本设置文件的只读属性:http://wenda.tianya.cn/question/0f484c28ffd8d4e9 bat脚本创建internet快捷方式:http://www ...
- C# webrequest 抓取数据时,多个域Cookie的问题
最近研究了下如何抓取为知笔记的内容,在抓取笔记里的图片内容时,老是提示403错误,用Chorme的开发者工具看了下: 这里的Cookie来自两个域,估计为知那边是验证了token(登录后才能获取到to ...
- Using Dtrace OEL 6.X
http://www.hhutzler.de/blog/using-dtrace/ http://docs.oracle.com/cd/E37670_01/E38608/html/dt_sdtparg ...
- WinForm多语言版本实战项目演练
一.课程介绍 关于如何实现“WinForm多语言版本”网上有很多实现技术方案,可以说是“琳琅满目”,"包罗万象".俗话说的好:一千个读者就有一千个哈姆雷特!如果您工作中恰好也遇到这 ...
- 为什要使用预编译SQL?(转)
本文转自https://www.cnblogs.com/zouqin/p/5314827.html 今天在研发部技术大牛的指点下,我终于明白了为什么要使用SQL预编译的形式执行数据库JDBC:
- pthread_join与pthread_detach细节问题
http://www.360doc.com/content/13/0106/09/9171956_258497083.shtml pthread_t pthr; pthread_create(& ...
- Swift - UITableView展开缩放动画
Swift - UITableView展开缩放动画 效果 源码 https://github.com/YouXianMing/Swift-Animations // // HeaderViewTapA ...
- nginx 413 500报错
采用nginx作反向代理,出现了一个诡异的问题,小文件可以提交,大文件会报500内部错误.这个是什么原因导致的呢? 查wiki可知,上传文件大小相关的有三个配置 client_body_buffer_ ...