python - 为什么 sklearn 的 LabelBinarizer 速度慢或不慢?

标签 python performance scikit-learn

我正在尝试将 sklearn 中的 LabelBinarizer 与简单字典的性能进行比较:

from sklearn.preprocessing import LabelBinarizer
import time

sample_list = list('abcdefg')
lb = LabelBinarizer()
lb.fit(dep_tag_list)
lb_t = lb.transform(sample_list)
sample_dict = {key:value for (key,value) in zip(sample_list, lb_t)}

此代码运行: --- 2.9169740676879883 秒 ---

start_time = time.time()
result = lb.transform(sample_list*1000000)
print("--- %s seconds ---" % (time.time() - start_time))

这段代码运行了: --- 0.6299951076507568 秒 ---

start_time = time.time()
result = [sample_dict[el] for el in sample_list*1000000]
print("--- %s seconds ---" % (time.time() - start_time))

我是在比较苹果吗?为什么 LableBinarizer 这么慢?

最佳答案

LabelBinarizer 是 label_binarize 的包装器。也可以在其他一些 scikit 实用程序内部使用。因此它需要注意传递给它的数据是否合适。

为此,它对传递的数据执行多次检查。请看transform() function here的源码:

y_is_multilabel = type_of_target(y).startswith('multilabel')
if y_is_multilabel and not self.y_type_.startswith('multilabel'):
    raise ValueError("The object was not fitted with multilabel"
                     " input.")

return label_binarize(y, self.classes_,
                      pos_label=self.pos_label,
                      neg_label=self.neg_label,
                      sparse_output=self.sparse_output)

因此您会看到它检查传递的 y 是否是可以由 scikit 算法处理的合适类型。之后,数据被传递到label_binarize,其 source code is ,对其执行其他附加检查。在我看来,这就是其缓慢的原因。

关于python - 为什么 sklearn 的 LabelBinarizer 速度慢或不慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47820700/

相关文章:

python - pybind11 加速函数调用

python - 绘制 Pandas 时间序列数据框的线性回归线的置信区间

python - 如何在多变量/3D 中实现核密度估计

PHP - Zend 说避免魔术方法?

java - 使用 RandomAccessFile 的最佳方法是 Java

python - 如何为 class.DeleteView 创建确认弹出窗口

python - pip 未指向虚拟环境,在虚拟环境中

python - RuntimeWarning : numpy. dtype 大小已更改,可能表示二进制不兼容

python - python-pandas 数据框中给定权重的加权平均值

Python Django-如何从表单中的输入文件标记获取文件路径?