为了账号安全,请及时绑定邮箱和手机立即绑定

Scikit-Learn 实现分类

! python ../.convert_notebook_to_script.py --input ch02.ipynb --output ch02.py 转换操作.

from IPython.display import Image
%matplotlib inline

分类算法的选择

由于每个算法都基于某些特定的假设, 且均含有某些缺点, 因此需要通过大量的实践为特定的问题选择合适的算法. ("天下没有免费的午餐"理论). 分类器的性能, 计算能力和预测能力, 在很大程度上都依赖于用于模型训练的相关数据. 训练机器学习算法所涉及的五个主要步骤如下:

  • 特征的选择
  • 确定性能评价标准
  • 选择分类器及其优化算法
  • 对模型性能的评估
  • 算法的调优

感知器 (perceptron)

from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
X = iris.data[:, [2, 3]]    # 为了可视化方便, 这里仅仅选用两种特征
y = iris.target

# 0=Iris-Setosa, 1=Iris-Versicolor, 2=Iris-Virginica
print('Class labels:', np.unique(y)) # 返回存储数据的类标
Class labels: [0 1 2]

划分数据集

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=1, stratify=y)
print('Labels counts in y:', np.bincount(y))
print('Labels counts in y_train:', np.bincount(y_train))
print('Labels counts in y_test:', np.bincount(y_test))
Labels counts in y: [50 50 50]
Labels counts in y_train: [35 35 35]
Labels counts in y_test: [15 15 15]

每个 bin 给出了它的索引值在x中出现的次数

np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1], dtype=int64)
# 我们可以看到 x 中最大的数为 7,因此 bin 的数量为 8,那么它的索引值为 0->7
x = np.array([0, 1, 1, 3, 2, 1, 7])
# 索引 0 出现了 1 次,索引 1 出现了 3 次......索引 5 出现了 0 次......
np.bincount(x)
array([1, 3, 1, 1, 0, 0, 0, 1], dtype=int64)
x = np.array([7, 6, 2, 1, 4])
# 索引 0 出现了 0 次,索引 1 出现了1次......索引 5 出现了0次......
np.bincount(x)
array([0, 1, 1, 0, 1, 0, 1, 1], dtype=int64)

如果 weights 参数被指定,那么 x 会被它加权,也就是说,如果值 n 发现在位置 i,那么 out[n] += weight[i] 而不是 out[n] += 1.因此,我们 weights 的大小必须与x相同,否则报错。下面,我举个例子让大家更好的理解一下:

w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6])
# 我们可以看到 x 中最大的数为 4,因此 bin 的数量为 5,那么它的索引值为 0->4
x = np.array([2, 1, 3, 4, 4, 3])
# 索引0 -> 0
# 索引1 -> w[1] = 0.5
# 索引2 -> w[0] = 0.3
# 索引3 -> w[2] + w[5] = 0.2 - 0.6 = -0.4
# 索引4 -> w[3] + w[4] = 0.7 + 1 = 1.7
np.bincount(x, weights=w)
array([ 0. ,  0.5,  0.3, -0.4,  1.7])

最后,我们来看一下 minlength 这个参数。文档说,如果 minlength 被指定,那么输出数组中 bin 的数量至少为它指定的数(如果必要的话,bin 的数量会更大,这取决于 x)。下面,我举个例子让大家更好的理解一下:

# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为7,因此现在bin的数量为7,所以现在它的索引值为0->6
np.bincount(x, minlength=7)
# 因此,输出结果为:array([0, 2, 1, 2, 0, 0, 0])

# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为1,那么它指定的数量小于原本的数量,因此这个参数失去了作用,索引值还是0->3
np.bincount(x, minlength=1)
# 因此,输出结果为:array([0, 2, 1, 2])
array([0, 2, 1, 2], dtype=int64)

特征缩放

from sklearn.preprocessing import StandardScaler

# 标准化处理
sc = StandardScaler()  
sc.fit(X_train)   # 计算数据中的每个特征的样本均值和标准差
X_train_std = sc.transform(X_train)   # 使用样本均值和标准差做标准化处理
X_test_std = sc.transform(X_test)

需要注意的是: 我们要使用相同的缩放参数来处理训练和测试数据, 以保证它们的值是彼此相当的.

perceptron

from sklearn.linear_model import Perceptron

# random_state 每次迭代后初始化重排训练数据集
ppn = Perceptron(tol=40, eta0=0.1, random_state=1)   # tol 迭代次数,eta0 学习率
ppn.fit(X_train_std, y_train)   # 训练模型
Perceptron(alpha=0.0001, class_weight=None, eta0=0.1, fit_intercept=True,
      max_iter=None, n_iter=None, n_jobs=1, penalty=None, random_state=1,
      shuffle=True, tol=40, verbose=0, warm_start=False)
y_pred = ppn.predict(X_test_std)
print('Misclassified samples: %d' % (y_test != y_pred).sum())
Misclassified samples: 3

mertrics 模块中实现了许多不同的性能矩阵, 如

from sklearn.metrics import accuracy_score

# y_test 真实的类标, y_pred 预测的类标
print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))
Accuracy: 0.93

绘制模型的决策区域

使用小圆圈来高亮显示测试数据

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt


def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):

    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(
        np.arange(x1_min, x1_max, resolution),
        np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(
            x=X[y == cl, 0],
            y=X[y == cl, 1],
            alpha=0.8,
            c=colors[idx],
            marker=markers[idx],
            label=cl,
            edgecolor='black')

    # highlight test samples
    if test_idx:
        # plot all samples
        X_test, y_test = X[test_idx, :], y[test_idx]

        plt.scatter(
            X_test[:, 0],
            X_test[:, 1],
            c='',
            edgecolor='black',
            alpha=1.0,
            linewidth=1,
            marker='o',
            s=100,
            label='test set')
X_combined_std = np.vstack((X_train_std, X_test_std))
y_combined = np.hstack((y_train, y_test))

plot_decision_regions(X=X_combined_std, y=y_combined,
                      classifier=ppn, test_idx=range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc='upper left')

plt.tight_layout()
#plt.savefig('images/03_01.png', dpi=300)
plt.show()

output_25_0

更多内容请看: Notebook

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消