美文网首页it
sklearn学习笔记

sklearn学习笔记

作者: Jlan | 来源:发表于2017-04-05 12:02 被阅读2026次

预处理

model_selection模块

train_test_split

分割数据集为训练集和测试集

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=4)

cross_val_score

from sklearn.model_selection import cross_val_score

knn = KNeighborsClassifier(n_neighbors=5)
scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy')
print(scores)
print(scores.mean())
[ 1.          0.93333333  1.          1.          0.86666667  0.93333333
  0.93333333  1.          1.          1.        ]
0.966666666667

分类器通用方法

iris = datasets.load_iris()        # 导入dataset中的数据
iris_x = iris.data                 # 特征
iris_y = iris.target               # 标签
#print(iris_x[:2, :])
train_x, test_x, train_y, test_y = train_test_split(iris_x, iris_y, test_size=0.3)     # 把训练数据和测试数据分开
knn = KNeighborsClassifier()    # 初始化一个机器学习算法
knn.fit(train_x, train_y)               # 开始训练
print(knn.predict(test_x))          # 预测
print(knn.score(test_x, test_y))    # 预测的准确率


分类器

svm

class sklearn.svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape=None, random_state=None)
  • C : float, optional (default=1.0)
    Penalty parameter C of the error term.
    C越大边界越复杂,会导致过拟合

  • kernel : string, optional (default=’rbf’)
    kernel必须是[‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’]中的一个或者是一个可调用对象,默认为’rbf’。

  • gamma : float, optional (default=’auto’)
    Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. If gamma is ‘auto’ then 1/n_features will be used instead.
    “伽玛”参数实际上对 SVM 的“线性”核函数没有影响。

  • 详情参考

  • http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC

  • http://scikit-learn.org/stable/modules/svm.html

核方法简单来讲就是把低维空间线性不可分的向量(x, y)映射到高维空间的向量(x1,x2,x3.......xn)以达到线性可分的目的。这个说法不准确,但是就先这样理解吧。

参考https://www.zhihu.com/question/30371867/answer/73428260

先给个定义:核函数K(kernel function)就是指K(x, y) = <f(x), f(y)>,其中x和y是n维的输入值,f(·) 是从n维到m维的映射(通常而言,m>>n)。<x, y>是x和y的内积(inner product),严格来说应该叫欧式空间的标准内积,也就是很多人常说的点积(dot product)。

光看这一段还是不明白kernel是什么,用来干什么的...对吧?不要急。一个好的知识分享者是不会把一篇空洞的定义扔下就不管的,TA会告诉你这个概念的intuition,然后给你举个小小的栗子,最后告诉你几个应用场景。Andrew Ng的Machine Learning为什么会成为一门现象级的MOOC?原因之一就是因为他除了是个学术上的大神,也同样是个极有质素的知识分享者。所以我要学习他。

好了,intuitively(这也模仿得太生硬了吧…),要计算<f(x), f(y)>,我们要先分别计算f(x)和f(y),然后再求它们的内积。上面的定义里也说了,经过映射后的x和y,维数大大增加,计算内积的成本可能会非常之大,而且在高位空间费力牛劲儿地计算内积,内积又是一个scalar,相当于说又把我们的计算从高维空间拉回到一维空间!所以我们特别想要一个“简便运算法”,帮助我们不需要奔向高维空间就能在家门口计算得到想要的内积。这时候该轮到我们的猪脚——kernel登场了,它能帮我们做到这一点。

举个小小栗子。
令 x = (x1, x2, x3, x4); y = (y1, y2, y3, y4);
令 f(x) = (x1x1, x1x2, x1x3, x1x4, x2x1, x2x2, x2x3, x2x4, x3x1, x3x2, x3x3, x3x4, x4x1, x4x2, x4x3, x4x4); f(y)亦然;
令核函数 K(x, y) = (<x, y>)^2.
接下来,让我们带几个简单的数字进去看看是个什么效果:x = (1, 2, 3, 4); y = (5, 6, 7, 8). 那么:
f(x) = ( 1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16) ;
f(y) = (25, 30, 35, 40, 30, 36, 42, 48, 35, 42, 49, 56, 40, 48, 56, 64) ;
<f(x), f(y)> = 25+60+105+160+60+144+252+384+105+252+441+672+160+384+672+1024
= 4900.
好累,对不对?可谁让f(·)把四维空间的数据映射到十六维空间里呢?
如果我们用核函数呢?
K(x, y) = (5+12+21+32)^2 = 70^2 = 4900.
就是这样!

所以现在你看出来了吧,kernel其实就是帮我们省去在高维空间里进行繁琐计算的“简便运算法”。甚至,它能解决<b>无限维空间</b>无法计算的问题!因为有时f(·)会把n维空间映射到无限维空间去,对此我们常常束手无策,除非是用kernel,尤其是RBF kernel(K(x,y) = exp(-||x-y||^2) )。

在有kernel之前,做machine learning的典型的流程应该是:data --> features --> learning algorithm,但kernel给我们提供了一个alternative,那就是,我们不必定义从data到feature的映射函数,而是可以直接kernel(data) --> learning algorithm,也可以是data --> features --> kernel(features) --> learning algorithm。
所以虽然我们看到kernel常被应用在SVM(SVM中的kernel应该是后一种用法,后文再说),但其实要用到内积的learning algorithm都可以使用kernel。“用到内积的learning algorithm”其实并不少见,不信你可以想一想最普通不过的linear classifier/regressor有没有一个步骤是计算特征向量(feature vectors)。



<b>那么kernel在SVM究竟扮演着什么角色?</b>
初学SVM时常常可能对kernel有一个误读,那就是误以为是kernel使得低维空间的点投射到高位空间后实现了线性可分。其实不然。这是<b>把kernel和feature space transformation</b><b>混为了一谈</b>。(这个错误其实很蠢,只要你把SVM从头到尾认真推导一遍就不会犯我这个错。)
还是简单回顾一下吧。SVM就是 y = w'·φ(x) + b,其中φ(x)是特征向量(feature vectors),并且是φ(x)使得数据从低维投射到高位空间后实现了线性可分。而kernel是在解对偶问题的最优化问题时,能够使φ(x)更方便地计算出来,特别是φ(x)维数很高的时候。


决策树

用法

class sklearn.tree.DecisionTreeClassifier(criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_split=1e-07, class_weight=None, presort=False)

逻辑回归

from sklearn.linear_model import LogisticRegression

logreg = LogisticRegression()
print(cross_val_score(logreg, X, y, cv=10, scoring='accuracy').mean())
0.953333333333

线性回归

import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.linear_model import LinearRegression

data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0)
print(data.head())
      TV  Radio  Newspaper  Sales
1  230.1   37.8       69.2   22.1
2   44.5   39.3       45.1   10.4
3   17.2   45.9       69.3    9.3
4  151.5   41.3       58.5   18.5
5  180.8   10.8       58.4   12.9
import seaborn as sns

%matplotlib inline
sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.7, kind='reg')
下载.png
feature_cols = ['TV', 'Radio', 'Newspaper']
X = data[feature_cols]
y = data.Sales
linreg = LinearRegression()
linreg.fit(X_train, y_train)
print(dict(zip(feature_cols, linreg.coef_)))
y_pred = linreg.predict(X_test)
print(y_test)
print(y_pred)
print(np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
{'TV': -0.15615389365322999, 'Radio': -0.021642394876836168, 'Newspaper': 0.23163615241203314}
[2 0 2 2 2 1 1 0 0 2 0 0 0 1 2 0 1 0 0 2 0 2 1 0 0 0 0 0 0 2 1 0 2 0 1 2 2
 1 1 0 2 0 1 0 2 0 0 1 1 2 0 1 2 2 1 1 0 1 2 1]
[ 1.92960022 -0.05631468  1.75924226  1.96952322  1.75400957  1.34503136
  1.55335259 -0.25708769  0.05337832  1.43933112 -0.01786772  0.0047061
 -0.09797524  1.31073213  1.8414079  -0.09259126  0.96397191 -0.04484088
  0.07419694  1.59020133 -0.11485066  1.89509647  1.32895025  0.10349746
  0.02464997 -0.00894958  0.07087912 -0.03927615 -0.06582262  1.77961658
  1.43655945 -0.00606188  1.74054079 -0.04857956  0.91115196  2.15514074
  1.6936414   1.07190357  1.27772238 -0.05079703  1.96811189 -0.0496883
  1.14322047 -0.11864257  1.99461128 -0.08938914 -0.05061628  1.28899166
  1.28540427  1.69145953 -0.08308331  1.0171239   2.16207777  2.12726337
  1.13745121  1.19236454  0.23135535  1.06899824  1.47599911  1.2114042 ]
0.212886736194
scores = cross_val_score(lm, X, y, cv=10, scoring='mean_squared_error')
print(scores)
mse_scores = -scores
rmse_scores = np.sqrt(mse_scores)
print(rmse_scores)
print(rmse_scores.mean())
[-3.56038438 -3.29767522 -2.08943356 -2.82474283 -1.3027754  -1.74163618
 -8.17338214 -2.11409746 -3.04273109 -2.45281793]
[ 1.88689808  1.81595022  1.44548731  1.68069713  1.14139187  1.31971064
  2.85891276  1.45399362  1.7443426   1.56614748]
1.69135317081

相关文章

网友评论

    本文标题:sklearn学习笔记

    本文链接:https://www.haomeiwen.com/subject/subtattx.html