机器学习常用 Python 函数

import numpy as np
import pandas as pd

np.bincoun

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

x = np.array([0, 1, 1, 3, 2, 1, 7])
b = np.bincount(x)
b
array([1, 3, 1, 1, 0, 0, 0, 1], dtype=int64)

我们可以看到 x 中最大的数为 7,因此 bin 的数量为 8,那么它的索引值为 0 \sim 7,对应关系是:

pd.DataFrame(data=b, columns=['bin'])
index bin
0 1
1 3
2 1
3 1
4 0
5 0
6 0
7 1

如果 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], dtype=int64)
# 我们可以看到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], dtype=int64)

np.unique

np.unique: Find the unique elements of an array.

np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
np.unique(a, axis=0)
array([[1, 0, 0],
       [2, 3, 4]])
a = np.array(['a', 'b', 'b', 'c', 'a'])
u, indices = np.unique(a, return_index=True)
u
array(['a', 'b', 'c'], dtype='<U1')
indices
array([0, 1, 3], dtype=int64)
a = np.array([1, 2, 6, 4, 2, 3, 2])
u, indices = np.unique(a, return_inverse=True)
u
array([1, 2, 3, 4, 6])
indices
array([0, 1, 4, 3, 1, 2, 1], dtype=int64)
u[indices]
array([1, 2, 6, 4, 2, 3, 2])

一个实例

以感知机为例来说明,如何组合使用各种 Python 函数。

from sklearn import datasets

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]

特征缩放

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

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)
# 感知机
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, early_stopping=False, eta0=0.1,
      fit_intercept=True, max_iter=None, n_iter=None, n_iter_no_change=5,
      n_jobs=None, penalty=None, random_state=1, shuffle=True, tol=40,
      validation_fraction=0.1, verbose=0, warm_start=False)
y_pred = ppn.predict(X_test_std)
print('Misclassified samples: %d' % (y_test != y_pred).sum())
Misclassified samples: 20

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

from sklearn.metrics import accuracy_score

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

绘制模型的决策区域

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

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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,110评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,443评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,474评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,881评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,902评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,698评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,418评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,332评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,796评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,968评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,110评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,792评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,455评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,003评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,130评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,348评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,047评论 2 355

推荐阅读更多精彩内容

  • 目录faster rcnn论文备注caffe代码框架简介faster rcnn代码分析后记 faster rcnn...
    db24cc阅读 9,615评论 2 12
  • 改进神经网络的学习方法(下) 权重初始化 创建了神经网络后,我们需要进行权重和偏差的初始化。到现在,我们一直是根据...
    nightwish夜愿阅读 1,867评论 0 0
  • 2016快过了,2017要到了 墙上的挂历,卷成一个意味深长的角 零点钟声敲响 电视节目里的人声鼎沸 响彻雾霾下的...
    seawaterbird阅读 394评论 0 0
  • 太阳光芒四射,照亮了多姿多彩的大地。 初生的浅草摇摆着叶片,似乎在向春天招手。五彩缤纷的大自然是多么绚丽,...
    歆赵不宣阅读 963评论 0 1
  • 001 不给自己留后路 文中用印度人作为例子讲述了为什么他们能够在一个领域里取得非常好的成绩。 因为没有多余的选择...
    诺诺爱皓皓阅读 195评论 0 0