sklearn库的学习

origin:
sklearn库的学习 - CSDN博客
https://blog.csdn.net/u014248127/article/details/78885180

sklearn库的学习

网上有很多关于sklearn的学习教程,大部分都是简单的讲清楚某一个方面。其实最好的教程就是官方文档(http://scikit-learn.org/stable/),但是官方文档讲述的太过于详细,同时很多人对官方文档的理解和结构认识上都不能很好的把握。我写这篇文章的目的是想用一篇文章讲清楚整个sklearn库,我会讲清楚怎么样用这个库,而不是讲清楚每一个知识点。(授人以鱼不如授人以渔)(本文很多都是从实践的角度出发,也仅仅只代表我个人的认识)
本篇文章主要从两个方面出发:1,介绍sklearn官方文档的类容和结构;2,从机器学习重要步骤出发讲清楚sklearn的使用方法。

一、sklearn官方文档的类容和结构
1,机器学习的认识:从实践的角度出发,机器学学习要做的工作就是在我们有的一个数据集上建立一个或者多个模型,然后对我们的模型进行优化和评估。我们将会在sklearn中看到下图各个模块到底是什么,怎么用。
这里写图片描述

2,sklearn库官方文档结构:
下图表示:官方文档有很多模块:
tutorials:是一个官方教程,可以理解快速上手教程,但是看完感觉并没有很快。
user guide(用户指南):这里对每一个算法有详细的介绍
API:这里是库调用的方法
FAQ:常见问题
contributing:贡献,还介绍最新的一些代码,功能。
(下面三个就跟没有用了)
这里写图片描述
总结:一般的做法是API里面找到你要调用的方法,然后可以查看方法参数的情况和使用情况。也可以在指南里面找到具体的解释。

3,sklearn库的结构:
这里写图片描述
(1)结构:
由图中,可以看到库的算法主要有四类:分类,回归,聚类,降维。其中:

  • 常用的回归:线性、决策树、SVM、KNN ;集成回归:随机森林、Adaboost、GradientBoosting、Bagging、ExtraTrees
  • 常用的分类:线性、决策树、SVM、KNN,朴素贝叶斯;集成分类:随机森林、Adaboost、GradientBoosting、Bagging、ExtraTrees
  • 常用聚类:k均值(K-means)、层次聚类(Hierarchical clustering)、DBSCAN
  • 常用降维:LinearDiscriminantAnalysis、PCA

(2)图片中隐含的操作流程:
这个流程图代表:蓝色圆圈内是判断条件,绿色方框内是可以选择的算法。你可以根据自己的数据特征和任务目标去找到一条自己的操作路线,一步步做就好了。

二、机器学习主要步骤中sklearn应用
1,数据集:面对自己的任务肯定有自己的数据集,但是对于学习来说,sklearn提供了一些数据,主要有两部分:现在网上一些常用的数据集,可以通过方法加载;另一种sklearn可以生成数据,可以生成你设定的数据。(设定规模,噪声等)
这里写图片描述

下面是一段python实例:

from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

#使用以后的数据集进行线性回归(这里是波士顿房价数据)
loaded_data=datasets.load_boston()
data_X=loaded_data.data
data_y=loaded_data.target

model=LinearRegression()
model.fit(data_X,data_y)

print(model.predict(data_X[:4,:]))
print(data_y[:4])

#使用生成线性回归的数据集,最后的数据集结果用散点图表示
X,y=datasets.make_regression(n_samples=100,n_features=1,n_targets=1,noise=10)   #n_samples表示样本数目,n_features特征的数目  n_tragets  noise噪音
plt.scatter(X,y)
plt.show()
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

2,数据预处理:数据预处理包括:降维、数据归一化、特征提取和特征转换(one-hot)等,这在sklearn里面有很多方法,具体查看api。这里用归一化(preprocessing.scale() )例子解释一下:

from sklearn import preprocessing #进行标准化数据时,需要引入个包
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.datasets.samples_generator import  make_classification
from sklearn.svm import SVC
import matplotlib.pyplot as plt


X,y=make_classification(n_samples=300,n_features=2,n_redundant=0,n_informative=2,random_state=22,n_clusters_per_class=1,scale=100)

#X=preprocessing.minmax_scale(X,feature_range=(-1,1))
X=preprocessing.scale(X)   #0.966666666667 没有 0.477777777778
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)
clf=SVC()
clf.fit(X_train,y_train)
print(clf.score(X_test,y_test))


plt.scatter(X[:,0],X[:,1],c=y)
plt.show()

a=np.array([[10,2.7,3.6],
            [-100,5,-2],
            [120,20,40]],dtype=np.float64)   #每一列代表一个属性
print(a)       #标准化之前a     
print(preprocessing.scale(a)) #标准化之后的a 
    
    
  • 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

3,选择模型并训练: sklearn里面有很多的机器学习方法,可以查看api找到你需要的方法,sklearn统一了所有模型调用的api,使用起来还是比较简单。

from sklearn import datasets
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

#使用以后的数据集进行线性回归
loaded_data=datasets.load_boston()
data_X=loaded_data.data
data_y=loaded_data.target

model=LinearRegression()
model.fit(data_X,data_y)

print(model.predict(data_X[:4,:]))
print(data_y[:4])

#参数
print(model.coef_)      #如果y=0.1x+0.3   则此行输出的结果为0.1
print(model.intercept_)             #此行输出的结果为0.3
print(model.get_params())       #模型定义时定义的参数,如果没有定义则返回默认值
print(model.score(data_X,data_y))   #给训练模型打分,注意用在LinearR中使用R^2 conefficient of determination打分
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

4,模型评分:
(1)模型的score方法:最简单的模型评估方法是调用模型自己的方法:

    #预测
    y_predict = knnClf.predict(x_test)
    print("score on the testdata:",knnClf.score(x_test,y_test))
    
    
  • 1
  • 2
  • 3

(2)sklearn的指标函数:库提供的一些计算方法,常用的有classification_report方法
这里写图片描述

下面是一个svm分类器,是关于图片分类的,具体数据这里没有给出,大家只需要关注模型的评估就好。

def svmClassify(x_train, x_test, y_train, y_test):
    id = range(1, x_test.shape[0]+1)
    print("start run svm!")
    #训练
    svc = svm.SVC(kernel='rbf', C=10,probability=True)
    svc.fit(x_train, y_train)
    #预测
    y_predict = svc.predict(x_test)
    print("svm mode's score on the test data:",svc.score(x_test,y_test))
    print("svm mode's evaluate:",classification_report(y_test,y_predict))
    # print(svc.coef_)  # 如果y=0.1x+0.3   则此行输出的结果为0.1
    # print(svc.intercept_)  # 此行输出的结果为0.3
    print(svc.get_params())  # 模型定义时定义的参数,如果没有定义则返回默认值

    #可能性计算
    probablity = svc.predict_proba(x_test)
    list_pro = []
    for i in range(probablity.shape[0]):
        pro = max(list(probablity[i]))
        list_pro.append(pro)
    #输出
    index = np.array(id).reshape(-1,1)
    result = pd.DataFrame(np.column_stack((np.array(id).reshape(-1, 1), np.array(y_test).reshape(-1, 1),np.array(y_predict).reshape(-1,1),np.array(list_pro).reshape(-1,1))),
                          columns=['ImageId','test_label','predict_lable','probablity'])

    result.to_csv("result/svm_result.csv", index=False, header=True, encoding='gbk')

    diff_index = []
    for i in range(result.shape[0]):
        # print(result['test_label'][i], result['predict_lable'][i],)
        diff_index.append(result['test_label'][i] != result['predict_lable'][i])
    print(diff_index)
    diff = result[diff_index]
    diff_x = x_test_original[diff_index]

    diff.to_csv('result/svm_result_diff.csv', index=False, header=True, encoding='gbk')
    # 查看每个错误
    for i in range(len(diff_index)):
        # print("label is:",diff['test_label'][i],"predict is:",diff['predict_lable'][i])
        print("test label is :", diff.iloc[i]['test_label'], 'predict label is :', diff.iloc[i]['predict_lable'])
        x = diff_x[i]
        img = x.reshape(28, 28)
        image_show(img)
    
    
  • 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
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

(3)sklearn也支持自己开发评价方法

5,模型的保存于恢复:模型的保存与恢复可以采用python的pickle,也可以用joblib的方法。

from sklearn import svm
from sklearn import datasets

clf=svm.SVC()
iris=datasets.load_iris()
X,y=iris.data,iris.target
clf.fit(X,y)

#method1:pickle
import pickle
#save
with open('save/clf.pickle','wb')as f:
    pickle.dump(clf,f)

#restore
with open('save/clf.pickle','rb') as f:
    clf=pickle.load(f)
    print(clf.predict(X[0:1]))


#method2:joblib
from sklearn.externals import joblib
#save
joblib.dump(clf,'save/clf.pkl')
clf3=joblib.load('save/clf.pkl')
print(clf3.predict(X[0:1]))
    
    
  • 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

这是一篇入门的文章,希望入门的人有一个很好的引导,接下来我也会跟新一些重要的内容。下一篇,我打算讲解交叉验证这个很重要的模块。

        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>

        </article>

    <div class="article-bar-bottom">
            <div class="article-copyright">
        版权声明:本文为博主原创文章,未经博主允许不得转载。          https://blog.csdn.net/u014248127/article/details/78885180       </div>
                    <div class="tags-box artic-tag-box">
        <span class="label">文章标签:</span>
                    <a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;库&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=库&amp;t=blog" target="_blank">库                       </a><a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;文档&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=文档&amp;t=blog" target="_blank">文档                        </a><a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;结构&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=结构&amp;t=blog" target="_blank">结构                        </a><a data-track-click="{&quot;mod&quot;:&quot;popu_626&quot;,&quot;con&quot;:&quot;sklearn-教程&quot;}" class="tag-link" href="http://so.csdn.net/so/search/s.do?q=sklearn-教程&amp;t=blog" target="_blank">sklearn-教程                        </a>
    </div>
                    <div class="tags-box">
        <span class="label">个人分类:</span>
                    <a class="tag-link" href="https://blog.csdn.net/u014248127/article/category/7189276" target="_blank">机器学习                       </a>
    </div>
                            <div class="tags-box hot-word">
        <span class="label">相关热词:</span>
                    <a class="tag-link" href="https://blog.csdn.net/u012526003/article/details/79109418" target="_blank">
        sklearn中            </a>
                    <a class="tag-link" href="https://blog.csdn.net/Jorocco/article/details/62892682" target="_blank">
        sklearn包            </a>
                    <a class="tag-link" href="https://blog.csdn.net/kevinelstri/article/details/60960574" target="_blank">
        sklearn库            </a>
                    <a class="tag-link" href="https://blog.csdn.net/sbtgmz/article/details/53919747" target="_blank">
        sklearn书            </a>
                    <a class="tag-link" href="https://blog.csdn.net/gamer_gyt/article/details/51232210" target="_blank">
        sklearn花            </a>
                </div>
        </div>

<!-- !empty($pre_next_article[0]) -->
        <div class="related-article related-article-prev text-truncate">
    <a href="https://blog.csdn.net/u014248127/article/details/78879046">
        <span>上一篇</span>PRML第四章笔记       </a>
</div>
            <div class="related-article related-article-next text-truncate">
    <a href="https://blog.csdn.net/u014248127/article/details/78899195">
        <span>下一篇</span>sklearn中的交叉验证与参数选择      </a>
</div>
</div>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值