机器学习1:scikit-learn简介(1)—— 机器学习的一般步骤(手写数字数据集案例)

scikit-learn 的介绍

scikit-learn的安装:
在cmd中输入 pip install scikit-learn 命令进行安装。

激活matplotlib,使得在notebook中显示内联图

%matplotlib inline
import matplotlib.pyplot as plt

scikit-learn是一个开源的Python语言机器学习工具包。它涵盖了几乎所有主流机器学习算法的实现,并且提供了一致的调用接口。它基于Numpy和SciPy等Python数值计算库,提供了高效的算法实现。
总结起来,scikit-learn工具包有以下几个优点:
(1) 文档齐全:官方文档齐全,更新及时。
(2) 接口易用:针对所有的算法提供了一致的接口调用规则,不管是KNN、K-Means还是PCA。
(3) 算法全面:涵盖主流机器学习任务的算法,包括回归算法、分类算法、聚类分析、数据降维处理等。
当然,scikit-learn不支持分布式计算,不适合用来处理超大型数据。

一、机器学习的一般步骤

1. 加载数据集

案列:

使用digits数据集,这是一个手写数字的数据集。

from sklearn.datasets import load_digits
from matplotlib import pyplot as plt
digits=load_digits()
images_and_labels=list(zip(digits.images,digits.target))
plt.figure(figsize=(8,6),dpi=200)
for index,(image,label)in enumerate(images_and_labels[:8]):
    plt.subplot(2,4,index+1)
    plt.axis('off') # 关闭坐标轴
    plt.imshow(image,cmap=plt.cm.gray_r,interpolation='nearest')
    plt.title('Digit:%i'%label,fontsize=20)

输出:

在这里插入图片描述

辅助理解:

zip() 函数: zip() 函数
enumerate()函数:enumerate()函数

plt.imshow() 函数负责对图像进行处理,并显示其格式,但是不能显示。其后跟着plt.show()才能显示出来。
cmap即colormaps,图谱
matplotlib.cm是matplotlib库中内置的色彩映射函数。
matplotlib.cm.[色彩] (’[数据集]’) 即对 [数据集] 应用 [色彩]

digits.data.shape

scikit-learn使用Numpy的array对象来表示数据,所有的图片数据保存在digits.images里,每个元素都是一个8x8尺寸的灰阶图片。我们在进行机器学习时,需要把数据保存为 [样本个数] x [特征个数] 格式的array对象,针对手写数字识别这个案例,scikit-learn已经为我们转换好了,把特征数据保存在digits.data数据里,可以通过digits.data.shape来查看它的数据格式。

print("shape of raw image_data:{0}".format(digits.images.shape))
print("shape if data:{0}".format(digits.data.shape))

输出:

shape of raw image_data:(1797, 8, 8)
shape if data:(1797, 64)

2. 划分训练集和测试集

在开始训练我们的模型之前,需要先把数据集分成训练数据集测试数据集。我们可以使用下面的代码吧数据集分出20%作为测试数据集,80%作为训练数据集。

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(digits.data,digits.target,test_size=0.20,random_state=2)

3. 训练模型

一旦我们拥有独立的训练集和测试集,我们就可以使用 fit方法 学习机器学习模型。我们将使用 score方法 来测试模型,通过准确度指标比较模型的好坏。

from sklearn.linear_model import LogisticRegression
# 求出逻辑回归 Logistic 的精确度得分
clf=LogisticRegression(solver='lbfgs',multi_class='ovr',max_iter=5000,random_state=42)
clf.fit(X_train,y_train)

输出:

LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=5000, multi_class='ovr',
          n_jobs=None, penalty='l2', random_state=42, solver='lbfgs',
          tol=0.0001, verbose=0, warm_start=False)

4. 测试模型

accuracy=clf.score(X_test,y_test)
print('Accuracy score of the {} is {:.2f}'.format(clf.__class__.__name__,accuracy))

输出:

Accuracy score of the LogisticRegression is 0.94

除此之外,还可以直接把测试数据集里的部分图片显示出来,并且在图片的左下角显示预测值,右下角显示真实值。

y_pred=clf.predict(X_test)
fig,axes=plt.subplots(4,4,figsize=(8,8))
fig.subplots_adjust(hspace=0.1,wspace=0.1)
for i,ax in enumerate(axes.flat):
    ax.imshow(X_test[i].reshape(8,8),cmap=plt.cm.gray_r,interpolation='nearest')
    ax.text(0.05,0.05,str(y_pred[i]),fontsize=32,transform=ax.transAxes,
            color='green' if y_pred[i] == y_test[i] else 'red')
    ax.text(0.8,0.05,str(y_test[i]),fontsize=32,transform=ax.transAxes,color='black')
    ax.set_xticks([])
    ax.set_yticks([])

输出:
在这里插入图片描述

  • 从图中可以看出,第二行第一个的出现错误,预测值与真实值不同。

5. 模型保存与加载

当我们对模型的准确度感到满意后,就可以把模型保存下来。这样下次需要预测时,可以直接加载模型来进行预测,而不是重新训练一遍模型。
可以使用下面的代码来保存模型:

from sklearn.externals import joblib
joblib.dump(clf,'digits_svm.pkl')

输出:

['digits_svm.pkl']

当我们需要这个模型来进行预测时,直接加载模型即可进行预测。

clf2=joblib.load('digits_svm.pkl')
clf2.score(X_test,y_test)

输出:

0.9361111111111111

6. 模型的轻松更改

scikit-learn的模型API在应用中是相似的。因此,我们通过随机森林分类器RandomForestClassifier轻松替换逻辑归回LogisticRegression分类器。这些更改很小,仅与分类器实例的创建有关。

from sklearn.ensemble import RandomForestClassifier    # RandomForestClassifier轻松替换LogisticRegression分类器
clf = RandomForestClassifier(n_estimators=100, n_jobs=-1, random_state=42)
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)
print('Accuracy score of the {} is {:.2f}'.format(clf.__class__.__name__, accuracy))

输出:

Accuracy score of the RandomForestClassifier is 0.96

练习

from sklearn.datasets import load_breast_cancer
breast = load_breast_cancer()
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(breast.data,breast.target,test_size=0.30,random_state=2)
from sklearn.ensemble import GradientBoostingClassifier
clf = GradientBoostingClassifier(n_estimators=100, random_state=0)
clf.fit(X_train, y_train)

输出:

GradientBoostingClassifier(criterion='friedman_mse', init=None,
              learning_rate=0.1, loss='deviance', max_depth=3,
              max_features=None, max_leaf_nodes=None,
              min_impurity_decrease=0.0, min_impurity_split=None,
              min_samples_leaf=1, min_samples_split=2,
              min_weight_fraction_leaf=0.0, n_estimators=100,
              n_iter_no_change=None, presort='auto', random_state=0,
              subsample=1.0, tol=0.0001, validation_fraction=0.1,
              verbose=0, warm_start=False)
  • 使用分类器预测测试集的分类标签。
y_pred = clf.predict(X_test)
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import accuracy_score
accuracy = balanced_accuracy_score(y_test, y_pred)
# accuracy = accuracy_score(y_test, y_pred)
print('Accuracy score of the {} is {:.2f}'.format(clf.__class__.__name__, accuracy))

输出:

Accuracy score of the GradientBoostingClassifier is 0.94
# Accuracy score of the GradientBoostingClassifier is 0.95

小结: 预测评分的方法包括三种:
(1) model.score(X_test, y_test)
(2) accuracy_score(y_test, y_pred)
(3) balanced_accuracy_score(y_test, y_pred)

(完。)

  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shi_jiaye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值