Scikit-learn 模型的预测是否支持多线程?

9

如果给定某个分类器(SVC / Forest / NN / 等),是否可以在不同的线程中同时对同一个实例调用.predict?

从远处看,我猜测它们不会改变任何内部状态。但是我在文档中没有找到相关说明。

下面是一个最简示例来说明我的意思:

#!/usr/bin/env python3
import threading

from sklearn import datasets
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier

X, y = datasets.load_iris(return_X_y=True)

# Some model. Might be any type, e.g.:
clf = svm.SVC()
clf = RandomForestClassifier(),
clf = MLPClassifier(solver='lbfgs')

clf.fit(X, y)


def use_model_for_predictions():
    for _ in range(10000):
        clf.predict(X[0:1])


# Is this safe?
thread_1 = threading.Thread(target=use_model_for_predictions)
thread_2 = threading.Thread(target=use_model_for_predictions)
thread_1.start()
thread_2.start()

1
你考虑过在scikit-learn的github仓库中提出问题吗?那里的开发者非常友好,通常也很快回复。这是一个有趣的问题,如果你在那里找到答案,请在这里提供答案。 - Shihab Shahriar Khan
1
@ShihabShahriarKhan 谢谢,我按照您的建议刚刚创建了一个问题(https://github.com/scikit-learn/scikit-learn/issues/18530)。 - Tobias Hermann
1个回答

1

请查看这个问答predictpredict_proba方法应该是线程安全的,因为它们只调用NumPy,它们在任何情况下都不会影响模型本身,所以回答你的问题是肯定的。

你也可以在这里的回复中找到一些信息。

例如,在朴素贝叶斯中,代码如下:

def predict(self, X):
    """
    Perform classification on an array of test vectors X.
    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
    Returns
    -------
    C : ndarray of shape (n_samples,)
        Predicted target values for X
    """
    check_is_fitted(self)
    X = self._check_X(X)
    jll = self._joint_log_likelihood(X)
    return self.classes_[np.argmax(jll, axis=1)]

你可以看到前两行只是检查输入。抽象方法_joint_log_likelihood是我们感兴趣的,它被描述为:
@abstractmethod
def _joint_log_likelihood(self, X):
    """Compute the unnormalized posterior log probability of X
    I.e. ``log P(c) + log P(x|c)`` for all rows x of X, as an array-like of
    shape (n_classes, n_samples).
    Input is passed to _joint_log_likelihood as-is by predict,
    predict_proba and predict_log_proba.
    """

最后举例多项式朴素贝叶斯分类器的函数如下(source):
def _joint_log_likelihood(self, X):
    """
    Compute the unnormalized posterior log probability of X, which is
    the features' joint log probability (feature log probability times
    the number of times that word appeared in that document) times the
    class prior (since we're working in log space, it becomes an addition)
    """
    joint_prob = X * self.feature_log_prob_.T + self.class_log_prior_
    return joint_prob

您可以看到,在predict中没有任何线程不安全的内容。当然,您可以查看任何一个分类器的代码,并检查这一点 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接