Skip to content

cross_val_score issue with n_jobs = -1 on Windows #13228

Closed

Description

@rfernandezv

Description

The error is thrown when utilizing n_jobs = -1 with the function: cross_val_score. If I use n_jobs = 1, it works fine.

Steps/Code to Reproduce

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('example.csv')
X = dataset.iloc[:, 3:13].values    
y = dataset.iloc[:, 13].values      

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])  
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])   

onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense


def build_classifier():
    classifier = Sequential()
    classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
    classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
    classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    return classifier
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

Expected Results

Expect my example to run multiple epochs at a time.

Actual Results

Error:

accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
Traceback (most recent call last):

  File "<ipython-input-4-cc51c2d2980a>", line 1, in <module>
    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

  File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 402, in cross_val_score
    error_score=error_score)

  File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 240, in cross_validate
    for train, test in cv.split(X, y, groups))

  File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
    self.retrieve()

  File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
    self._output.extend(job.get(timeout=self.timeout))

  File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in wrap_future_result
    return future.result(timeout=timeout)

  File "C:\Users\Richar\Anaconda3\lib\concurrent\futures\_base.py", line 432, in result
    return self.__get_result()

  File "C:\Users\Richar\Anaconda3\lib\concurrent\futures\_base.py", line 384, in __get_result
    raise self._exception

BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

I think the problem is related to Windows, Keras and joblib

Versions

I'm using:

  • 64-bit Windows 10
  • Python 3.7.1
  • scikit-learn 0.20.1
  • Spyder 3.3.3

Thanks for the help.

Activity

  1. jnothman commented on Feb 24, 2019

    @jnothman
    Member

    Put build_classifier in a separate module and import it

  2. christian-steinmeyer commented on Feb 25, 2019

    @christian-steinmeyer

    May I ask how this fixes the issue and is this intended behavior?

  3. albertcthomas commented on Feb 25, 2019

    @albertcthomas
    Contributor

    @rfernandezv or anyone else having this error, could you please try @jnothman's solution and tell us if this solves the issue?

  4. christian-steinmeyer commented on Feb 25, 2019

    @christian-steinmeyer

    For me, this seems to do the trick. My code didn't run through yet (total runtime is many hours), but so far no errors (which was the case before).

  5. jnothman commented on Feb 25, 2019

    @jnothman
    Member

    Something can only be unpickled if it can be imported by name.

  6. albertcthomas commented on Feb 25, 2019

    @albertcthomas
    Contributor

    This should work with cloudpickle, maybe with the next release of joblib.

  7. rfernandezv commented on Feb 26, 2019

    @rfernandezv
    Author

    @rfernandezv or anyone else having this error, could you please try @jnothman's solution and tell us if this solves the issue?

    I tried but I still get the same error.

    from newFile import build_classifier_function
    # Evaluating the ANN
    
    classifier = KerasClassifier(build_fn = build_classifier_function, batch_size = 10, epochs = 100)
    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)

    Error:

    Traceback (most recent call last):
    
      File "<ipython-input-50-cc51c2d2980a>", line 1, in <module>
        accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 402, in cross_val_score
        error_score=error_score)
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 240, in cross_validate
        for train, test in cv.split(X, y, groups))
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
        self.retrieve()
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
        self._output.extend(job.get(timeout=self.timeout))
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in wrap_future_result
        return future.result(timeout=timeout)
    
      File "C:\Users\Richar\Anaconda3\lib\concurrent\futures\_base.py", line 432, in result
        return self.__get_result()
    
      File "C:\Users\Richar\Anaconda3\lib\concurrent\futures\_base.py", line 384, in __get_result
        raise self._exception
    
    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

    Updated to version 0.13.2 (joblib) and still have the same error.
    Only works for me with n_jobs = 1, no -1

  8. albertcthomas commented on Feb 26, 2019

    @albertcthomas
    Contributor

    cross_val_score is using the version of joblib vendored with scikit-learn so updating joblib won't solve the error, you need to wait for the update of the vendored joblib to try it in your case.

    However I don't know why you still have the error when importing from another module.

  9. tomMoral commented on Mar 7, 2019

    @tomMoral
    Contributor

    I could not reproduce your bug with the latest versiono of sklearn.
    Could you update your version to 0.20.2 and report if there is any changes?

    For the record, this should work even if you do not put the build_classifier function in a new module with newest versions of joblib as we are relying on cloudpickle.

  10. rfernandezv commented on Mar 8, 2019

    @rfernandezv
    Author

    I could not reproduce your bug with the latest versiono of sklearn.
    Could you update your version to 0.20.2 and report if there is any changes?

    For the record, this should work even if you do not put the build_classifier function in a new module with newest versions of joblib as we are relying on cloudpickle.

    I tried but the same error :(

    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

    Updated to version 0.20.3

    import sklearn print(sklearn.__version__) 0.20.3

  11. tomMoral commented on Mar 8, 2019

    @tomMoral
    Contributor
  12. rfernandezv commented on Mar 9, 2019

    @rfernandezv
    Author

    Look, this is the complete error:

    accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
    Traceback (most recent call last):
    
      File "<ipython-input-6-cc51c2d2980a>", line 1, in <module>
        accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 402, in cross_val_score
        error_score=error_score)
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 240, in cross_validate
        for train, test in cv.split(X, y, groups))
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 930, in __call__
        self.retrieve()
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 833, in retrieve
        self._output.extend(job.get(timeout=self.timeout))
    
      File "C:\Users\Richar\Anaconda3\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py", line 521, in wrap_future_result
        return future.result(timeout=timeout)
    
      File "C:\Users\Richar\Anaconda3\lib\concurrent\futures\_base.py", line 432, in result
        return self.__get_result()
    
      File "C:\Users\Richar\Anaconda3\lib\concurrent\futures\_base.py", line 384, in __get_result
        raise self._exception
    
    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.
  13. albertcthomas commented on Mar 9, 2019

    @albertcthomas
    Contributor

    @rfernandezv I could not reproduce the error either with the following code on windows

    from keras.layers import Dense
    from keras.models import Sequential
    from sklearn.model_selection import cross_val_score
    from keras.wrappers.scikit_learn import KerasClassifier
    from sklearn.preprocessing import StandardScaler
    from sklearn.model_selection import train_test_split
    
    from sklearn.datasets import make_classification
    
    X, y = make_classification(n_features=11)
    
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=0)
    
    sc = StandardScaler()
    X_train = sc.fit_transform(X_train)
    X_test = sc.transform(X_test)
    
    
    def build_classifier():
        classifier = Sequential()
        classifier.add(Dense(units=6, kernel_initializer='uniform',
                             activation='relu', input_dim=11))
        classifier.add(
            Dense(units=6, kernel_initializer='uniform', activation='relu'))
        classifier.add(
            Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))
        classifier.compile(
            optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
        return classifier
    
    
    classifier = KerasClassifier(
        build_fn=build_classifier, batch_size=10, epochs=100)
    accuracies = cross_val_score(
        estimator=classifier, X=X_train, y=y_train, cv=10, n_jobs=-1)

    The versions that I'm using:
    Windows 10
    Python 3.6.6
    NumPy 1.15.4
    SciPy 1.2.0
    Scikit-Learn 0.20.2
    Keras 2.2.4
    Tensorflow 1.12.0

  14. olgazju commented on Mar 11, 2019

    @olgazju

    I have the same error with cross_val_score and n_jobs=1

    BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.

    Python 3.7.2
    scikit-learn==0.20.3
    joblib==0.13.2
    windows 8.1

  15. 16 remaining items

  16. streetr0ck commented on Jul 26, 2019

    @streetr0ck

    @rth i'm using :
    Windows-10-10.0.17134-SP0
    Python 3.6.8 |Anaconda, Inc.| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
    scikit-learn version is 0.20.3.
    joblib version is 0.13.0.

  17. rfernandezv commented on Jul 27, 2019

    @rfernandezv
    Author

    @streetr0ck
    I was using Spyder and had the problem, but now I run it in Visual Code and the same code worked correctly.

  18. streetr0ck commented on Jul 27, 2019

    @streetr0ck

    @rfernandezv
    I had some problems with visual studio code, but after launching the python script, I was able to exploit all the cores. It worked fine.
    It's a pity there's no solution on spyder.
    Thank you for the help.

  19. streetr0ck commented on Jul 28, 2019

    @streetr0ck

    @rfernandezv
    I'm just curious to know if you had a broken display in the terminal, as shown in the picture attached to this message.

    Capture d’écran (26)

  20. trungnghia2009 commented on Oct 2, 2019

    @trungnghia2009

    I also got the same problem on spyder (work only with n_jobs = 1), but on vscode it worked well.
    Using windows platform for the tutorial

    paralell computing

  21. streetr0ck commented on Oct 2, 2019

    @streetr0ck

    Thank you very much @trungnghia2009 for the answer.

  22. suvofalcon commented on Oct 29, 2019

    @suvofalcon

    How will n_jobs=-1 will work or will it at all work, if you run your tensorflow backend on gpu?

    in my opinion, n_jobs=-1 will try and use all the cores for CV and each of tit will try to start a tf session on GPU.

    In short n_jobs=-1 doesn't work for me, when using GPU

  23. hanss01 commented on Jan 3, 2020

    @hanss01

    so you all come from deep learning a-z right? XD

  24. metalglove commented on Jan 9, 2020

    @metalglove

    I am having the same problem.

  25. blurred-machine commented on Apr 26, 2020

    @blurred-machine

    For me, the same error came but it was solved when I removed
    n_jobs=-1
    from the code, then it worked perfectly.
    Maybe there is some issue with the multithreading compatibility for parallel computing.
    Can you help me understand what could be the real reason?

  26. negrinij commented on May 21, 2020

    @negrinij

    Hi, Just in case is helpful. I had to update Anaconda to 1.9.12 and Spyder to 4.1.3, their current latest versions. Updating joblib and other packages above did not do the trick for me. As other users mentioned, maybe is something with spyder / anaconda.

  27. Jolomi-Tosanwumi commented on Dec 7, 2020

    @Jolomi-Tosanwumi

    Any solution to this issue? I am having the same errors when n_jobs is set to any number greater than 1. I am trying to do cross validation on a Keras model wrapped in sklearn's KerasClassifier.

  28. mattiaguerri commented on Apr 23, 2021

    @mattiaguerri

    Issue still persists, the suggested solution does not fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions