question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot save items in a defaultdict in the scorer of a GridSearchCV with joblib backend

See original GitHub issue

I’m trying to store some information about a training of a custom sklearn-compatible SVM in a shared defautdict in the context of joblib in sklearn GridSearchCV. So I have the following:

    from collections import defaultdict

    from sklearn.model_selection import GridSearchCV
    from sklearn.datasets import make_regression

    X, y = make_regression(n_samples=100, n_features=1, noise=10, bias=2, random_state=123456)

    train_loss_history = defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))

    def dual_r2_scorer(svr, X, y):
        # (f_t - f*) / f*
        f_star = np.full_like(svr.train_loss_history, svr.obj.f_star())
        train_loss_history[svr.dual][svr.kernel][svr.C][svr.epsilon] = np.divide((svr.train_loss_history - f_star),
                                                                                 np.abs(f_star))
        return {'r2': svr.score(X, y),
                'n_iter': svr.optimizer.iter,
                'n_sv': len(svr.support_)}
    

    grid = GridSearchCV(DualSVR(loss=squared_epsilon_insensitive,
                                optimizer=AdaGrad,
                                max_iter=1000,
                                learning_rate=1.),
                        param_grid={'epsilon': [0.1, 0.2, 0.3],
                                    'C': [1, 10, 100]},
                        scoring=dual_r2_scorer,
                        n_jobs=-1,
                        refit='r2',  # refit the best model (wrt r2) on the full development set
                        return_train_score=True,
                        verbose=True).fit(lin_X, lin_y)

But with -1 option for n_jobs, at the end of the execution, the dictionary train_loss_history is empty. For n_jobs=None, it works.

How can I fix it?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
NicolasHugcommented, Jun 9, 2021

I’m glad these docs are helpful ❤️

1reaction
NicolasHugcommented, Jun 9, 2021

Here’s a more minimal example:

from collections import defaultdict

from sklearn.model_selection import GridSearchCV
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression

X, y = make_regression()

train_loss_history = defaultdict(str)

def dual_r2_scorer(svr, X, y):
    train_loss_history['hello'] = 12
    return 3


grid = GridSearchCV(LinearRegression(),
                    param_grid={'fit_intercept': [True, False]},
                    scoring=dual_r2_scorer,
                    n_jobs=-1,
                    refit=False,
                    ).fit(X, y)
print(train_loss_history)
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to save GridSearchCV object? - python - Stack Overflow
Use. import joblib directly. instead of. from sklearn.externals import joblib. Save objects or results with: joblib.dump(gs, 'model_file_name.pkl').
Read more >
Save and Load Machine Learning Models in Python with scikit ...
Save Your Model with joblib​​ It provides utilities for saving and loading Python objects that make use of NumPy data structures, efficiently. ...
Read more >
How to create a dictionary of multiple keys and pairs in python?
You can possibly use defaultdict to do this simply. from collections import defaultdict lines = string.split('\n') d = defaultdict(list) for line in lines: ......
Read more >
Analysis Report scikit_learn-0.22.2.post1-cp37-cp37m ...
Startdate: 15/04/2020 Architecture: WINDOWS Score: 4 unarchiver.exe 5 started 7za.exe 502 started C:\Users\...\murmurhash.cp37-win_amd64.pyd, PE32+ dropped ...
Read more >
beer_project/model_building.ipynb at master - GitHub
This notebook contains the fruits of an effort to build numerous models from data I scraped from BrewersFriend.com. The first model uses only...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found