【问题标题】:Why sklearn Random Forest takes the same time to predict one sample than n samples为什么 sklearn 随机森林需要相同的时间来预测一个样本而不是 n 个样本
【发布时间】:2018-11-13 13:27:45
【问题描述】:

我在 Python 3.6 上使用 sklearn,我注意到将单个样本预测为 1D numpy 数组所需的运行时间与将 n 个样本预测为具有随机森林的 2D numpy 数组所需的运行时间相同(两者都约为 0.1 秒)。看起来 sklearn 在每个预测步骤首先需要一定的时间来设置树,然后立即进行预测。这可以解释为什么预测大型二维数组的运行时间与一维数组相同?

这是我训练模型的代码:

clf = RandomForestClassifier(n_estimators=1, #or > 1 
        n_jobs=-1,
        random_state=2,
        max_depth=15,
        min_samples_leaf=1,
        verbose=0,
        max_features='auto'
        )

clf.fit(X_train, y_train)

with open('classifier.pkl', 'wb') as fid:
   cPickle.dump(clf, fid)  

就我而言,我必须像这样在循环中一一进行实时预测:

with open('classifier.pkl', 'rb') as fid:
   clf = cPickle.load(fid)

for s in samples:
   #my feature extraction method
   pred = clf.predict(feature) #feature is a 1D np array containing features 
                               #computed for the sample s

是不是因为我用错了方法?还是 sklearn 没有针对一一预测进行优化?

【问题讨论】:

  • 你确定你测量的运行时间不是由分类器的解压控制的吗?
  • 是的,我在不使用pickle的情况下在训练步骤之后进行预测时发现了同样的问题。
  • max_depth 设置为 15。这可能是它变慢的原因之一。其次,您的特征提取方法也可能很耗时。我的作品中的两个之一。

标签: python machine-learning scikit-learn runtime random-forest


【解决方案1】:

你是对的,sklearn 针对向量运算进行了高度优化。您正在正确使用它。如果您执行以下操作,您应该会看到显着的加速:

features = np.zeros((len(samples), n_features))
for i, s in enumerate(samples):
   features[i] = feature_extraction(s)
preds = clf.predict(features)

【讨论】:

  • 感谢您的回答 :) 很有趣,但就我而言,我必须“即时”计算特征并进行预测,因此我必须在特征计算循环中进行预测。我是否应该得出结论 sklearn 不是此应用程序的正确工具?我应该重新实现这些树吗?
  • 另一个事实是,在我的情况下(运行时约 0.002 秒),sklearn 随机森林只有一棵树,但不超过一棵树(约 0.1 秒)。
猜你喜欢
  • 2017-05-13
  • 2019-01-01
  • 2017-02-21
  • 2019-07-22
  • 2018-12-25
  • 2023-03-27
  • 2022-12-17
  • 2021-03-23
  • 2016-01-21
相关资源
最近更新 更多