[Python] Are predictions on scikit-learn models thread-safe?

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    Given some classifier (SVC/Forest/NN/whatever) is it safe to call .predict on the same instance concurrently from different threads?

    From a distant point of view, my guess is they do not mutate any internal state. But I did not find anything in the docs about it.

    Here is a minimal example showing what I mean:

    #!/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()

    Continue reading...

Compartilhe esta Página