Skip to content

LassoLarsCV error if n_jobs > 1 #4597

Closed

Description

@DonBeo
n,p = 2194, 12277
X = np.random.normal(0, 1, (n, p))
y = X[:,1] + X[:,2] + np.random.normal(0,1, n)


l1 = LassoLarsCV(n_jobs=1).fit(X,y)
print(l1.coef_)
l = LassoLarsCV(n_jobs=-1).fit(X,y)
print(l.coef_)

OUTPUT

>>> 
>>> 
[ 0.          0.91122441  0.88051206 ...,  0.          0.          0.        ]
multiprocessing.pool.RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/sklearn/externals/joblib/parallel.py", line 94, in __call__
    return self.func(*args, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/least_angle.py", line 853, in _lars_path_residues
    X_train -= X_mean
ValueError: output array is read-only

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.4/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "/usr/local/lib/python3.4/dist-packages/sklearn/externals/joblib/parallel.py", line 104, in __call__
    raise TransportableException(text, e_type)
sklearn.externals.joblib.my_exceptions.TransportableException: TransportableException
___________________________________________________________________________
ValueError                                         Wed Apr 15 14:14:46 2015
PID: 4123                                    Python 3.4.0: /usr/bin/python3
...........................................................................
/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/least_angle.py in _lars_path_residues(X_train=memmap([[ 1.00577915, -1.05126903,  1.30304231, ... -0.35100295,
        -0.9267396 ,  0.63928884]]), y_train=array([ 1.3232542 ,  0.84262663, -2.62905025, ...,  1.62472897,
       -1.45902494, -5.00504709]), X_test=array([[-0.31256648, -0.8413869 ,  0.46347277, ....  1.21977537,
        -1.12781956, -1.12695671]]), y_test=array([ -1.91413301e-02,  -7.90822410e-01,  -2.1...2352138e-01,  -2.06750561e+00,  -3.79778359e-01]), Gram='auto', copy=False, method='lasso', verbose=0, fit_intercept=True, normalize=True, max_iter=500, eps=2.2204460492503131e-16)
    848         X_test = X_test.copy()
    849         y_test = y_test.copy()
    850 
    851     if fit_intercept:
    852         X_mean = X_train.mean(axis=0)
--> 853         X_train -= X_mean
        X_train = memmap([[ 1.00577915, -1.05126903,  1.30304231, ... -0.35100295,
        -0.9267396 ,  0.63928884]])
        X_mean = memmap([-0.01531417,  0.02889734, -0.01592266, ...,  0.00315228,
       -0.00060194,  0.01170645])
    854         X_test -= X_mean
    855         y_mean = y_train.mean(axis=0)
    856         y_train = as_float_array(y_train, copy=False)
    857         y_train -= y_mean

ValueError: output array is read-only
___________________________________________________________________________
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/sklearn/externals/joblib/parallel.py", line 518, in retrieve
    self._output.append(job.get())
  File "/usr/lib/python3.4/multiprocessing/pool.py", line 599, in get
    raise self._value
sklearn.externals.joblib.my_exceptions.TransportableException: TransportableException
___________________________________________________________________________
ValueError                                         Wed Apr 15 14:14:46 2015
PID: 4123                                    Python 3.4.0: /usr/bin/python3
...........................................................................
/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/least_angle.py in _lars_path_residues(X_train=memmap([[ 1.00577915, -1.05126903,  1.30304231, ... -0.35100295,
        -0.9267396 ,  0.63928884]]), y_train=array([ 1.3232542 ,  0.84262663, -2.62905025, ...,  1.62472897,
       -1.45902494, -5.00504709]), X_test=array([[-0.31256648, -0.8413869 ,  0.46347277, ....  1.21977537,
        -1.12781956, -1.12695671]]), y_test=array([ -1.91413301e-02,  -7.90822410e-01,  -2.1...2352138e-01,  -2.06750561e+00,  -3.79778359e-01]), Gram='auto', copy=False, method='lasso', verbose=0, fit_intercept=True, normalize=True, max_iter=500, eps=2.2204460492503131e-16)
    848         X_test = X_test.copy()
    849         y_test = y_test.copy()
    850 
    851     if fit_intercept:
    852         X_mean = X_train.mean(axis=0)
--> 853         X_train -= X_mean
        X_train = memmap([[ 1.00577915, -1.05126903,  1.30304231, ... -0.35100295,
        -0.9267396 ,  0.63928884]])
        X_mean = memmap([-0.01531417,  0.02889734, -0.01592266, ...,  0.00315228,
       -0.00060194,  0.01170645])
    854         X_test -= X_mean
    855         y_mean = y_train.mean(axis=0)
    856         y_train = as_float_array(y_train, copy=False)
    857         y_train -= y_mean

ValueError: output array is read-only
___________________________________________________________________________

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/donbeo/Desktop/prova.py", line 31, in <module>
    l = LassoLarsCV(n_jobs=-1).fit(X,y)
  File "/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/least_angle.py", line 999, in fit
    for train, test in cv)
  File "/usr/local/lib/python3.4/dist-packages/sklearn/externals/joblib/parallel.py", line 666, in __call__
    self.retrieve()
  File "/usr/local/lib/python3.4/dist-packages/sklearn/externals/joblib/parallel.py", line 549, in retrieve
    raise exception_type(report)
sklearn.externals.joblib.my_exceptions.JoblibValueError: JoblibValueError
___________________________________________________________________________
Multiprocessing exception:
    ...........................................................................
/home/donbeo/Desktop/<stdin> in <module>()
----> 1 
      2 
      3 
      4 
      5 
      6 
      7 
      8 
      9 
     10 

...........................................................................
/home/donbeo/Desktop/prova.py in <module>()
     26 y = X[:,1] + X[:,2] + np.random.normal(0,1, n)
     27 
     28 
     29 l1 = LassoLarsCV(n_jobs=1).fit(X,y)
     30 print(l1.coef_)
---> 31 l = LassoLarsCV(n_jobs=-1).fit(X,y)
     32 print(l.coef_)
     33 
     34 
     35 

...........................................................................
/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/least_angle.py in fit(self=LassoLarsCV(copy_X=True, cv=None, eps=2.22044604...normalize=True, precompute='auto', verbose=False), X=array([[-0.31256648, -0.8413869 ,  0.46347277, .... -0.35100295,
        -0.9267396 ,  0.63928884]]), y=array([-0.01914133, -0.79082241, -2.15777265, ...,  1.62472897,
       -1.45902494, -5.00504709]))
    994             delayed(_lars_path_residues)(
    995                 X[train], y[train], X[test], y[test], Gram=Gram, copy=False,
    996                 method=self.method, verbose=max(0, self.verbose - 1),
    997                 normalize=self.normalize, fit_intercept=self.fit_intercept,
    998                 max_iter=self.max_iter, eps=self.eps)
--> 999             for train, test in cv)
        cv = sklearn.cross_validation.KFold(n=2194, n_folds=3, shuffle=False, random_state=None)
   1000         all_alphas = np.concatenate(list(zip(*cv_paths))[0])
   1001         # Unique also sorts
   1002         all_alphas = np.unique(all_alphas)
   1003         # Take at most max_n_alphas values

...........................................................................
/usr/local/lib/python3.4/dist-packages/sklearn/externals/joblib/parallel.py in __call__(self=Parallel(n_jobs=-1), iterable=<generator object <genexpr>>)
    661             if pre_dispatch == "all" or n_jobs == 1:
    662                 # The iterable was consumed all at once by the above for loop.
    663                 # No need to wait for async callbacks to trigger to
    664                 # consumption.
    665                 self._iterating = False
--> 666             self.retrieve()
        self.retrieve = <bound method Parallel.retrieve of Parallel(n_jobs=-1)>
    667             # Make sure that we get a last message telling us we are done
    668             elapsed_time = time.time() - self._start_time
    669             self._print('Done %3i out of %3i | elapsed: %s finished',
    670                         (len(self._output),

    ---------------------------------------------------------------------------
    Sub-process traceback:
    ---------------------------------------------------------------------------
    ValueError                                         Wed Apr 15 14:14:46 2015
PID: 4123                                    Python 3.4.0: /usr/bin/python3
...........................................................................
/usr/local/lib/python3.4/dist-packages/sklearn/linear_model/least_angle.py in _lars_path_residues(X_train=memmap([[ 1.00577915, -1.05126903,  1.30304231, ... -0.35100295,
        -0.9267396 ,  0.63928884]]), y_train=array([ 1.3232542 ,  0.84262663, -2.62905025, ...,  1.62472897,
       -1.45902494, -5.00504709]), X_test=array([[-0.31256648, -0.8413869 ,  0.46347277, ....  1.21977537,
        -1.12781956, -1.12695671]]), y_test=array([ -1.91413301e-02,  -7.90822410e-01,  -2.1...2352138e-01,  -2.06750561e+00,  -3.79778359e-01]), Gram='auto', copy=False, method='lasso', verbose=0, fit_intercept=True, normalize=True, max_iter=500, eps=2.2204460492503131e-16)
    848         X_test = X_test.copy()
    849         y_test = y_test.copy()
    850 
    851     if fit_intercept:
    852         X_mean = X_train.mean(axis=0)
--> 853         X_train -= X_mean
        X_train = memmap([[ 1.00577915, -1.05126903,  1.30304231, ... -0.35100295,
        -0.9267396 ,  0.63928884]])
        X_mean = memmap([-0.01531417,  0.02889734, -0.01592266, ...,  0.00315228,
       -0.00060194,  0.01170645])
    854         X_test -= X_mean
    855         y_mean = y_train.mean(axis=0)
    856         y_train = as_float_array(y_train, copy=False)
    857         y_train -= y_mean

ValueError: output array is read-only
___________________________________________________________________________
>>> >>> 

Activity

  1. agramfort commented on Apr 15, 2015

    @agramfort
    Member
  2. DonBeo commented on Apr 15, 2015

    @DonBeo
    Author

    I am having this problem on Ubuntu 14.04 running the 0.17dev version. It
    was working fine with 0.16

    On Wed, Apr 15, 2015, 14:36 Alexandre Gramfort [email protected]
    wrote:

    works fine for me with anaconda on mac os

    —
    Reply to this email directly or view it on GitHub
    #4597 (comment)
    .

  3. lesteve commented on Apr 15, 2015

    @lesteve
    Member

    I can reproduce it (Ubuntu 14.04 too) but it doesn't seem to be related to 0.17dev0. I get the same error with scikit-learn 0.15.2 and 0.16.0.

  4. amueller commented on Apr 16, 2015

    @amueller
    Member

    ping @ogrisel @GaelVaroquaux, our parallelization experts?

  5. added this to the 0.17 milestone on Apr 16, 2015
  6. koefoed commented on Apr 22, 2015

    @koefoed

    I can reproduce DonBeo's error with sklearn 0.16.1.

    Also, I have experienced a similar issue with GridSearchCV and Pandas data frames (see below).
    Oddly, the behavior seems to depend on the shape of the data set. A small data set runs fine whereas a larger data set does not.

    A suggested workaround is to use gs2.fit(X.values, y.values) below.

    import numpy as np
    #from sklearn.linear_model import LassoLarsCV
    import pandas as pd
    from sklearn.ensemble import RandomForestRegressor
    from sklearn.grid_search import GridSearchCV
    
    # n, p = 1453, 1931  # Runs
    n, p = 58509, 1247  # Fails
    
    X = np.random.normal(0, 1, (n, p))
    y = X[:, 1] + X[:, 2] + np.random.normal(0, 1, n)
    
    X = pd.DataFrame(X)
    y = pd.DataFrame(y)
    
    model = RandomForestRegressor()
    parameters = {'n_estimators': [10, 50, 100]}
    gs1 = GridSearchCV(model, param_grid=parameters, n_jobs=1)
    gs1.fit(X, y)
    print('Single job succeeded')
    gs2 = GridSearchCV(model, param_grid=parameters, n_jobs=3)
    gs2.fit(X, y)
    print('three jobs succeeded -- I never got to this')

    Results in (a bunch of DataConversionWarning: A column-vector y was passed when a 1d array was expected has been omitted):

    Traceback (most recent call last):
      File "scikit-learn-bugtest.py", line 22, in <module>
        gs2.fit(X, y)
      File "~/.local/lib/python2.7/site-packages/sklearn/grid_search.py", line 732, in fit
        return self._fit(X, y, ParameterGrid(self.param_grid))
      File "~/.local/lib/python2.7/site-packages/sklearn/grid_search.py", line 505, in _fit
        for parameters in parameter_iterable
      File "~/.local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 666, in __call__
        self.retrieve()
      File "~/.local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 549, in retrieve
        raise exception_type(report)
    sklearn.externals.joblib.my_exceptions.JoblibValueError: JoblibValueError
    ___________________________________________________________________________
    Multiprocessing exception:
        ...........................................................................
    ~/thesis/tmp/scikit-learn-bugtest/scikit-learn-bugtest.py in <module>()
         17 parameters = {'n_estimators': [10, 50, 100]}  # 250]}
         18 # gs1 = GridSearchCV(model, param_grid=parameters, n_jobs=1)
         19 # gs1.fit(X, y)
         20 # print('Single job succeeded')
         21 gs2 = GridSearchCV(model, param_grid=parameters, n_jobs=3)
    ---> 22 gs2.fit(X, y)
         23 print('three jobs succeeded -- I never got to this')
         24 
         25 
         26 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/sklearn/grid_search.py in fit(self=GridSearchCV(cv=None, error_score='raise',
         ...t=True, score_func=None, scoring=None, verbose=0), X=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], y=              0
    0      0.050503
    1     -1.129171
    ....454451
    58508 -0.176651
    
    [58509 rows x 1 columns])
        727         y : array-like, shape = [n_samples] or [n_samples, n_output], optional
        728             Target relative to X for classification or regression;
        729             None for unsupervised learning.
        730 
        731         """
    --> 732         return self._fit(X, y, ParameterGrid(self.param_grid))
            self._fit = <bound method GridSearchCV._fit of GridSearchCV(...=True, score_func=None, scoring=None, verbose=0)>
            X =            0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns]
            y =               0
    0      0.050503
    1     -1.129171
    ....454451
    58508 -0.176651
    
    [58509 rows x 1 columns]
            self.param_grid = {'n_estimators': [10, 50, 100]}
        733 
        734 
        735 class RandomizedSearchCV(BaseSearchCV):
        736     """Randomized search on hyper parameters.
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/sklearn/grid_search.py in _fit(self=GridSearchCV(cv=None, error_score='raise',
         ...t=True, score_func=None, scoring=None, verbose=0), X=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], y=              0
    0      0.050503
    1     -1.129171
    ....454451
    58508 -0.176651
    
    [58509 rows x 1 columns], parameter_iterable=<sklearn.grid_search.ParameterGrid object>)
        500         )(
        501             delayed(_fit_and_score)(clone(base_estimator), X, y, self.scorer_,
        502                                     train, test, self.verbose, parameters,
        503                                     self.fit_params, return_parameters=True,
        504                                     error_score=self.error_score)
    --> 505                 for parameters in parameter_iterable
            parameters = undefined
            parameter_iterable = <sklearn.grid_search.ParameterGrid object>
        506                 for train, test in cv)
        507 
        508         # Out is a list of triplet: score, estimator, n_test_samples
        509         n_fits = len(out)
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py in __call__(self=Parallel(n_jobs=3), iterable=<itertools.islice object>)
        661             if pre_dispatch == "all" or n_jobs == 1:
        662                 # The iterable was consumed all at once by the above for loop.
        663                 # No need to wait for async callbacks to trigger to
        664                 # consumption.
        665                 self._iterating = False
    --> 666             self.retrieve()
            self.retrieve = <bound method Parallel.retrieve of Parallel(n_jobs=3)>
        667             # Make sure that we get a last message telling us we are done
        668             elapsed_time = time.time() - self._start_time
        669             self._print('Done %3i out of %3i | elapsed: %s finished',
        670                         (len(self._output),
    
        ---------------------------------------------------------------------------
        Sub-process traceback:
        ---------------------------------------------------------------------------
        ValueError                                         Wed Apr 22 16:11:19 2015
    PID: 4161                                     Python 2.7.9: /usr/bin/python
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/sklearn/cross_validation.pyc in _fit_and_score(estimator=RandomForestRegressor(bootstrap=True, criterion=...ate=None,
               verbose=0, warm_start=False), X=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], y=              0
    0      0.050503
    1     -1.129171
    ....454451
    58508 -0.176651
    
    [58509 rows x 1 columns], scorer=<function _passthrough_scorer>, train=array([19503, 19504, 19505, ..., 58506, 58507, 58508]), test=array([    0,     1,     2, ..., 19500, 19501, 19502]), verbose=0, parameters={'n_estimators': 10}, fit_params={}, return_train_score=False, return_parameters=True, error_score='raise')
       1447     if parameters is not None:
       1448         estimator.set_params(**parameters)
       1449 
       1450     start_time = time.time()
       1451 
    -> 1452     X_train, y_train = _safe_split(estimator, X, y, train)
       1453     X_test, y_test = _safe_split(estimator, X, y, test, train)
       1454 
       1455     try:
       1456         if y_train is None:
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/sklearn/cross_validation.pyc in _safe_split(estimator=RandomForestRegressor(bootstrap=True, criterion=...ate=None,
               verbose=0, warm_start=False), X=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], y=              0
    0      0.050503
    1     -1.129171
    ....454451
    58508 -0.176651
    
    [58509 rows x 1 columns], indices=array([19503, 19504, 19505, ..., 58506, 58507, 58508]), train_indices=None)
       1514             if train_indices is None:
       1515                 X_subset = X[np.ix_(indices, indices)]
       1516             else:
       1517                 X_subset = X[np.ix_(indices, train_indices)]
       1518         else:
    -> 1519             X_subset = safe_indexing(X, indices)
       1520 
       1521     if y is not None:
       1522         y_subset = safe_indexing(y, indices)
       1523     else:
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/sklearn/utils/__init__.pyc in safe_indexing(X=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], indices=array([19503, 19504, 19505, ..., 58506, 58507, 58508]))
        147     indices : array-like, list
        148         Indices according to which X will be subsampled.
        149     """
        150     if hasattr(X, "iloc"):
        151         # Pandas Dataframes and Series
    --> 152         return X.iloc[indices]
        153     elif hasattr(X, "shape"):
        154         if hasattr(X, 'take') and (hasattr(indices, 'dtype') and
        155                                    indices.dtype.kind == 'i'):
        156             # This is often substantially faster than X[indices]
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/indexing.pyc in __getitem__(self=<pandas.core.indexing._iLocIndexer object>, key=array([19503, 19504, 19505, ..., 58506, 58507, 58508]))
       1212 
       1213     def __getitem__(self, key):
       1214         if type(key) is tuple:
       1215             return self._getitem_tuple(key)
       1216         else:
    -> 1217             return self._getitem_axis(key, axis=0)
       1218 
       1219     def _getitem_axis(self, key, axis=0):
       1220         raise NotImplementedError()
       1221 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/indexing.pyc in _getitem_axis(self=<pandas.core.indexing._iLocIndexer object>, key=[19503, 19504, 19505, 19506, 19507, 19508, 19509, 19510, 19511, 19512, 19513, 19514, 19515, 19516, 19517, 19518, 19519, 19520, 19521, 19522, ...], axis=0)
       1503                                     "non-integer key")
       1504 
       1505                 # validate the location
       1506                 self._is_valid_integer(key, axis)
       1507 
    -> 1508             return self._get_loc(key, axis=axis)
       1509 
       1510     def _convert_to_indexer(self, obj, axis=0, is_setter=False):
       1511         """ much simpler as we only have to deal with our valid types """
       1512 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/indexing.pyc in _get_loc(self=<pandas.core.indexing._iLocIndexer object>, key=[19503, 19504, 19505, 19506, 19507, 19508, 19509, 19510, 19511, 19512, 19513, 19514, 19515, 19516, 19517, 19518, 19519, 19520, 19521, 19522, ...], axis=0)
         87             raise IndexingError('no slices here, handle elsewhere')
         88 
         89         return self.obj._xs(label, axis=axis)
         90 
         91     def _get_loc(self, key, axis=0):
    ---> 92         return self.obj._ixs(key, axis=axis)
         93 
         94     def _slice(self, obj, axis=0, kind=None):
         95         return self.obj._slice(obj, axis=axis, kind=kind)
         96 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/frame.pyc in _ixs(self=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], i=[19503, 19504, 19505, 19506, 19507, 19508, 19509, 19510, 19511, 19512, 19513, 19514, 19515, 19516, 19517, 19518, 19519, 19520, 19521, 19522, ...], axis=0)
       1709                 return self[i]
       1710             else:
       1711                 label = self.index[i]
       1712                 if isinstance(label, Index):
       1713                     # a location index by definition
    -> 1714                     result = self.take(i, axis=axis)
            i = [19503, 19504, 19505, 19506, 19507, 19508, 19509, 19510, 19511, 19512, 19513, 19514, 19515, 19516, 19517, 19518, 19519, 19520, 19521, 19522, ...]
            values = undefined
            values.DataFrame.stack = undefined
            axis = 0
            axis.Return = undefined
            result = undefined
       1715                     copy=True
       1716                 else:
       1717                     new_values = self._data.fast_xs(i)
       1718 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/generic.pyc in take(self=           0         1         2         3      ...0.446357  0.506371  
    
    [58509 rows x 1247 columns], indices=[19503, 19504, 19505, 19506, 19507, 19508, 19509, 19510, 19511, 19512, 19513, 19514, 19515, 19516, 19517, 19518, 19519, 19520, 19521, 19522, ...], axis=0, convert=True, is_copy=True)
       1346         taken : type of caller
       1347         """
       1348 
       1349         new_data = self._data.take(indices,
       1350                                    axis=self._get_block_manager_axis(axis),
    -> 1351                                    convert=True, verify=True)
       1352         result = self._constructor(new_data).__finalize__(self)
       1353 
       1354         # maybe set copy if we didn't actually change the index
       1355         if is_copy:
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/internals.pyc in take(self=BlockManager
    Items: Int64Index([0, 1, 2, 3, 4, 5...: slice(0, 1247, 1), 1247 x 58509, dtype: float64, indexer=array([19503, 19504, 19505, ..., 58506, 58507, 58508]), axis=1, verify=True, convert=True)
       3264                 raise Exception('Indices must be nonzero and less than '
       3265                                 'the axis length')
       3266 
       3267         new_labels = self.axes[axis].take(indexer)
       3268         return self.reindex_indexer(new_axis=new_labels, indexer=indexer,
    -> 3269                                     axis=axis, allow_dups=True)
       3270 
       3271     def merge(self, other, lsuffix='', rsuffix=''):
       3272         if not self._is_indexed_like(other):
       3273             raise AssertionError('Must have same axes to merge managers')
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/internals.pyc in reindex_indexer(self=BlockManager
    Items: Int64Index([0, 1, 2, 3, 4, 5...: slice(0, 1247, 1), 1247 x 58509, dtype: float64, new_axis=Int64Index([19503, 19504, 19505, 19506, 19507, 1... 19599, 19600, 19601, 19602, ...], dtype='int64'), indexer=array([19503, 19504, 19505, ..., 58506, 58507, 58508]), axis=1, fill_value=None, allow_dups=True, copy=True)
       3151                 indexer, fill_tuple=(fill_value,))
       3152         else:
       3153             new_blocks = [blk.take_nd(indexer, axis=axis,
       3154                                       fill_tuple=(fill_value if fill_value is not None else
       3155                                                   blk.fill_value,))
    -> 3156                           for blk in self.blocks]
       3157 
       3158         new_axes = list(self.axes)
       3159         new_axes[axis] = new_axis
       3160         return self.__class__(new_blocks, new_axes)
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/internals.pyc in take_nd(self=FloatBlock: slice(0, 1247, 1), 1247 x 58509, dtype: float64, indexer=array([19503, 19504, 19505, ..., 58506, 58507, 58508]), axis=1, new_mgr_locs=None, fill_tuple=(nan,))
        846             new_values = com.take_nd(self.get_values(), indexer, axis=axis,
        847                                      allow_fill=False)
        848         else:
        849             fill_value = fill_tuple[0]
        850             new_values = com.take_nd(self.get_values(), indexer, axis=axis,
    --> 851                                      allow_fill=True, fill_value=fill_value)
        852 
        853         if new_mgr_locs is None:
        854             if axis == 0:
        855                 slc = lib.indexer_as_slice(indexer)
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/core/common.pyc in take_nd(arr=memmap([[-1.43861754,  0.59312065, -0.16608052, ...  0.5328391 ,
            -0.44635687,  0.50637109]]), indexer=array([19503, 19504, 19505, ..., 58506, 58507, 58508]), axis=0, out=array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],
        ...0.],
           [ 0.,  0.,  0., ...,  0.,  0.,  0.]]), fill_value=nan, mask_info=None, allow_fill=True)
        818 
        819     func = _get_take_nd_function(arr.ndim, arr.dtype, out.dtype,
        820                                  axis=axis, mask_info=mask_info)
        821 
        822     indexer = _ensure_int64(indexer)
    --> 823     func(arr, indexer, out, fill_value)
        824 
        825     if flip_order:
        826         out = out.T
        827     return out
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/algos.so in pandas.algos.take_2d_axis0_float64_float64 (pandas/algos.c:89674)()
       3467 
       3468 
       3469 
       3470 
       3471 
    -> 3472 
       3473 
       3474 
       3475 
       3476 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/algos.so in View.MemoryView.memoryview_cwrapper (pandas/algos.c:175798)()
        609 
        610 
        611 
        612 
        613 
    --> 614 
        615 
        616 
        617 
        618 
    
    ...........................................................................
    ~/.local/lib/python2.7/site-packages/pandas/algos.so in View.MemoryView.memoryview.__cinit__ (pandas/algos.c:172387)()
        316 
        317 
        318 
        319 
        320 
    --> 321 
        322 
        323 
        324 
        325 
    
    ValueError: buffer source array is read-only
    ___________________________________________________________________________

    The same issue has been reported by other people as well:

  7. agramfort commented on Apr 23, 2015

    @agramfort
    Member
  8. koefoed commented on Apr 25, 2015

    @koefoed

    @agramfort, I do not quite understand what you mean by

    it's a pb check_array

    Also, it does not work when passing (large) pandas data frames.
    Maybe I am not understanding what you mean.

  9. agramfort commented on Apr 26, 2015

    @agramfort
    Member
  10. amueller commented on Apr 27, 2015

    @amueller
    Member

    I think the problem is in the slicing of the data, which doesn't call check_array as we don't want to convert data to an array in the cross-validation / grid-search part.
    If the data is a large list of strings, that would be pretty bad. Also, someone might want to use a pd dataframe as input in their estimator, and converting to numpy array early would be bad for that.
    So safe_indexing seems to break for pandas dataframes sometimes...
    So the problem is with return X.iloc[indices]

  11. amueller commented on May 1, 2015

    @amueller
    Member

    I opened an issue at pandas: pandas-dev/pandas#10043 I don't understand the behavior, maybe using iloc is not the right way to slice.

  12. amueller commented on May 1, 2015

    @amueller
    Member

    @ogrisel @GaelVaroquaux could either of you explain why X is not writable? This is multi-processing, and X is copied, right?

  13. amueller commented on May 1, 2015

    @amueller
    Member

    This is actually a Cython issue, there are no read-only cython buffers, so input on why there is a read-only flag would be great.

  14. ogrisel commented on May 5, 2015

    @ogrisel
    Member

    By default the automated memory mapping feature of joblib is converting all big arrays into read-only np.memmap instances in the multiprocessing workers.

    There exists two additional modes for memory mapping:

    • read-write: but we don't want to use that otherwise it would mean that concurrent workers could corrupt each other input data,
    • copy-on-write: to avoid memory copies when the input data is untouched and to automatically copy memory pages whenever they are accessed in write mode to simulate memory isolation.

    Ideally we would therefore use copy-on-write as a reasonable default. Unfortunately the support for the copy-on-write mode under Windows is half broken and tends to crash on large data: see joblib/joblib#150.

    In this case we should separate the issue with LassoLarsCV from the one related to slicing a pandas data frame backed by a memory mapped array in read-only mode. For the original problem with LassoLarsCV I think it's a design problem in this class (or its internals): no estimator should try to edit the input data by default, unless the user explicitly pass copy=False. I will try to have deeper look.

    For the problem happening when using grid search on a large data frame, I think it better to track the discussion in pandas-dev/pandas#10043 as I think this is might be a problem with the way pandas.DataFrame.iloc is currently implemented.

    Side note: joblib uses memory mapping to share arrays between Python processes (forked by multiprocessing when doing a GridSearchCV or LassoLarsCV with n_jobs != 1). memory mapping is not used when using joblib in threading mode as it the case in RandomForestClassifier with n_jobs != 1. Threading used shared memory by default but unfortunately the threading mode can only be used efficiently by Cython code that releeases the GIL, this is why we cannot use it for general utilities like GridSearchCV.

  15. 15 remaining items

  16. amueller commented on May 6, 2015

    @amueller
    Member

    I can reproduce the lassoCV failure with the code that is provided, but not "manually":

    from joblib import load, dump
    import numpy as np
    from sklearn.linear_model import LassoLarsCV
    
    n,p = 21, 122
    X = np.random.normal(0, 1, (n, p))
    y = X[:,1] + X[:,2] + np.random.normal(0,1, n)
    
    dump(X, "/tmp/dump.joblib", compress=0)
    X_ = load("/tmp/dump.joblib", mmap_mode="r")
    l1 = LassoLarsCV(n_jobs=1).fit(X_,y)

    runs through just fine. I don't understand.

  17. ogrisel commented on May 7, 2015

    @ogrisel
    Member

    Indeed, it's the inner, CV'ed data that is read-only when using LassoLarsCV on a large input (more than 100MB). I have a fix but it's hard to comme up with a non-regression test that executes quickly...

  18. ogrisel commented on May 7, 2015

    @ogrisel
    Member

    I can write a unittest on _lars_path_residues but this does not feel satisfactory.

  19. ogrisel commented on May 7, 2015

    @ogrisel
    Member

    FYI here is the fix I have in mind:

    diff --git a/sklearn/linear_model/least_angle.py b/sklearn/linear_model/least_angle.py
    index f851df3..15c0704 100644
    --- a/sklearn/linear_model/least_angle.py
    +++ b/sklearn/linear_model/least_angle.py
    @@ -782,6 +782,12 @@ class LassoLars(Lars):
     ###############################################################################
     # Cross-validated estimator classes
    
    +def _check_copy_and_writeable(array, copy=False):
    +    if copy or not array.flags.writeable:
    +        return array.copy()
    +    return array
    +
    +
     def _lars_path_residues(X_train, y_train, X_test, y_test, Gram=None,
                             copy=True, method='lars', verbose=False,
                             fit_intercept=True, normalize=True, max_iter=500,
    @@ -842,11 +848,10 @@ def _lars_path_residues(X_train, y_train, X_test, y_test, Gram=None,
         residues : array, shape (n_alphas, n_samples)
             Residues of the prediction on the test data
         """
    -    if copy:
    -        X_train = X_train.copy()
    -        y_train = y_train.copy()
    -        X_test = X_test.copy()
    -        y_test = y_test.copy()
    +    X_train = _check_copy_and_writeable(X_train, copy)
    +    y_train = _check_copy_and_writeable(y_train, copy)
    +    X_test = _check_copy_and_writeable(X_test, copy)
    +    y_test = _check_copy_and_writeable(y_test, copy)
    
         if fit_intercept:
             X_mean = X_train.mean(axis=0)
    
  20. ogrisel commented on May 7, 2015

    @ogrisel
    Member

    Let me do a fix with a unittest on _lars_path_residues only.

  21. added a commit that references this issue on May 7, 2015
    dd9641f
  22. amueller commented on May 7, 2015

    @amueller
    Member

    Do all four arrays need to be writable?

  23. mozark24 commented on May 11, 2018

    @mozark24

    I'm facing this issue. n_jobs cannot be set > 1.

  24. jnothman commented on May 13, 2018

    @jnothman
    Member

    This is very likely fixed in master if the most recent version of cython is used to compile it.

  25. g1t-h1j4ck3r commented on Oct 30, 2018

    @g1t-h1j4ck3r

    I have the same problem with OneClassSVM using GridSearchCV with n_jobs > 1.
    Since the training/cv is very slow already, it is not really practicable to use just one job.

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

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions