dask-ml icon indicating copy to clipboard operation
dask-ml copied to clipboard

Dask-ml imputer cannot covert NA values

Open ks233ever opened this issue 6 years ago • 13 comments

I'm running the following code;

from dask_ml import impute imputer = impute.SimpleImputer(strategy='mean') X = imputer.fit_transform(X_pred).compute() X_pred is a dask distributed dataframe of 371 columns which are float64 and int64

This returns a ValueError -- ValueError: Cannot convert non-finite values (NA or inf) to integer

Expected Outcome: convert NA to integer

ks233ever avatar May 01 '20 03:05 ks233ever

Thanks for the report. Do you have a minimal example? http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports

TomAugspurger avatar May 01 '20 11:05 TomAugspurger

Are you using pandas' nullable integer dtype? I'd only expect NA in that, but it seems like dask handles that case fine

In [6]: ddf = dd.from_pandas(pd.DataFrame({"A": pd.array([1, None, 3])}), 2)

In [7]: ddf
Out[7]:
Dask DataFrame Structure:
                   A
npartitions=1
0              Int64
2                ...
Dask Name: from_pandas, 1 tasks

In [8]: from dask_ml import impute
   ...: imputer = impute.SimpleImputer(strategy='mean')

In [11]: imputer.fit_transform(ddf).compute()
Out[11]:
   A
0  1
1  2
2  3

TomAugspurger avatar May 01 '20 14:05 TomAugspurger

here is the more hashed out code--

-- is there a way to force dtypes if that's the issue?

X_pred= dd.read_sql_table(table='XXXXXX', uri=uri, index_col='rownumber', schema='data_science')

X_pred.info() <class 'dask.dataframe.core.DataFrame'> Columns: 371 entries, iutilityid to financial_store_credit_card_user dtypes: float64(240), int64(131)

from dask_ml import impute imputer = impute.SimpleImputer(strategy='mean') X = imputer.fit_transform(X_pred).compute()

ValueError: Cannot convert non-finite values (NA or inf) to integer

Note that I've used the dask_ml imputer on a subset of the same data-- just a pandas dataframe rather than dask-- with no problem--

pandas_X_pred = pd.read_sql_query(sql = query, con = engine)

pandas_X_pred.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 351985 entries, 0 to 351984 Columns: 371 entries, iutilityid to financial_store_credit_card_user dtypes: float64(259), int64(112)

X = imputer.fit_transform(pandas_X_pred)

-- NA values filled as expected

ks233ever avatar May 01 '20 17:05 ks233ever

See http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports. Ideally the example wouldn't involve reading from sql, just build the small dataset that reproduces the example in memory.

TomAugspurger avatar May 01 '20 18:05 TomAugspurger

Can you also post a full traceback and your versions of dask-ml, dask, and scikit-learn? I'm having a hard time seeing where the ValueError might even be raised right now, but I could be missing something.

TomAugspurger avatar May 01 '20 19:05 TomAugspurger

sure i can work on creating an example dataset

full traceback is here

X = imputer.fit_transform(X_pred).compute()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-53-916a5b634120> in <module>()
----> 1 X = imputer.fit_transform(X_pred).compute()
      2 
      3 #11:21

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/sklearn/base.py in fit_transform(self, X, y, **fit_params)
    551         if y is None:
    552             # fit method of arity 1 (unsupervised transformation)
--> 553             return self.fit(X, **fit_params).transform(X)
    554         else:
    555             # fit method of arity 2 (supervised transformation)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask_ml/impute.py in fit(self, X, y)
     51             self._fit_array(X)
     52         else:
---> 53             self._fit_frame(X)
     54         return self
     55 

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask_ml/impute.py in _fit_frame(self, X)
     77             avg = np.concatenate(*dask.compute(avg))
     78 
---> 79         self.statistics_ = pd.Series(dask.compute(avg)[0], index=X.columns)
     80 
     81     def transform(self, X):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/base.py in compute(*args, **kwargs)
    434     keys = [x.__dask_keys__() for x in collections]
    435     postcomputes = [x.__dask_postcompute__() for x in collections]
--> 436     results = schedule(dsk, keys, **kwargs)
    437     return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)])
    438 

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in get(self, dsk, keys, restrictions, loose_restrictions, resources, sync, asynchronous, direct, retries, priority, fifo_timeout, actors, **kwargs)
   2585                     should_rejoin = False
   2586             try:
-> 2587                 results = self.gather(packed, asynchronous=asynchronous, direct=direct)
   2588             finally:
   2589                 for f in futures.values():

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in gather(self, futures, errors, direct, asynchronous)
   1883                 direct=direct,
   1884                 local_worker=local_worker,
-> 1885                 asynchronous=asynchronous,
   1886             )
   1887 

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in sync(self, func, asynchronous, callback_timeout, *args, **kwargs)
    765         else:
    766             return sync(
--> 767                 self.loop, func, *args, callback_timeout=callback_timeout, **kwargs
    768             )
    769 

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/utils.py in sync(loop, func, callback_timeout, *args, **kwargs)
    343     if error[0]:
    344         typ, exc, tb = error[0]
--> 345         raise exc.with_traceback(tb)
    346     else:
    347         return result[0]

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/utils.py in f()
    327             if callback_timeout is not None:
    328                 future = asyncio.wait_for(future, callback_timeout)
--> 329             result[0] = yield future
    330         except Exception as exc:
    331             error[0] = sys.exc_info()

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/tornado/gen.py in run(self)
    733 
    734                     try:
--> 735                         value = future.result()
    736                     except Exception:
    737                         exc_info = sys.exc_info()

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in _gather(self, futures, errors, direct, local_worker)
   1739                             exc = CancelledError(key)
   1740                         else:
-> 1741                             raise exception.with_traceback(traceback)
   1742                         raise exc
   1743                     if errors == "skip":

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/utils.py in apply()
     27 def apply(func, args, kwargs=None):
     28     if kwargs:
---> 29         return func(*args, **kwargs)
     30     else:
     31         return func(*args)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/io/sql.py in _read_sql_chunk()
    211         return meta
    212     else:
--> 213         return df.astype(meta.dtypes.to_dict(), copy=False)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/generic.py in astype()
   5681                 if col_name in dtype:
   5682                     results.append(
-> 5683                         col.astype(dtype=dtype[col_name], copy=copy, errors=errors)
   5684                     )
   5685                 else:

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/generic.py in astype()
   5696         else:
   5697             # else, only a single dtype is given
-> 5698             new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors)
   5699             return self._constructor(new_data).__finalize__(self)
   5700 

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/internals/managers.py in astype()
    580 
    581     def astype(self, dtype, copy: bool = False, errors: str = "raise"):
--> 582         return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
    583 
    584     def convert(self, **kwargs):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/internals/managers.py in apply()
    440                 applied = b.apply(f, **kwargs)
    441             else:
--> 442                 applied = getattr(b, f)(**kwargs)
    443             result_blocks = _extend_blocks(applied, result_blocks)
    444 

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/internals/blocks.py in astype()
    623             vals1d = values.ravel()
    624             try:
--> 625                 values = astype_nansafe(vals1d, dtype, copy=True)
    626             except (ValueError, TypeError):
    627                 # e.g. astype_nansafe can fail on object-dtype of strings

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/dtypes/cast.py in astype_nansafe()
    866 
    867         if not np.isfinite(arr).all():
--> 868             raise ValueError("Cannot convert non-finite values (NA or inf) to integer")
    869 
    870     elif is_object_dtype(arr):

ValueError: Cannot convert non-finite values (NA or inf) to integer

ks233ever avatar May 01 '20 19:05 ks233ever

Interesting, it seems to be failing in the fit call. Or perhaps even earlier. Notice the line ~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/io/sql.py in _read_sql_chunk() in the middle of the stack trace.

Does len(X_pread) work for you? If that fails it will isolate the problem to dd.read_sql at least.

TomAugspurger avatar May 01 '20 19:05 TomAugspurger

ahh you're right! failing on len(X_pred)


ValueError Traceback (most recent call last) in () ----> 1 len(X_pred)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/core.py in len(self) 3316 return super().len() 3317 else: -> 3318 return len(s) 3319 3320 def getitem(self, key):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/core.py in len(self) 525 def len(self): 526 return self.reduction( --> 527 len, np.sum, token="len", meta=int, split_every=False 528 ).compute() 529

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/base.py in compute(self, **kwargs) 163 dask.base.compute 164 """ --> 165 (result,) = compute(self, traverse=False, **kwargs) 166 return result 167

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/base.py in compute(*args, **kwargs) 434 keys = [x.dask_keys() for x in collections] 435 postcomputes = [x.dask_postcompute() for x in collections] --> 436 results = schedule(dsk, keys, **kwargs) 437 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)]) 438

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in get(self, dsk, keys, restrictions, loose_restrictions, resources, sync, asynchronous, direct, retries, priority, fifo_timeout, actors, **kwargs) 2585 should_rejoin = False 2586 try: -> 2587 results = self.gather(packed, asynchronous=asynchronous, direct=direct) 2588 finally: 2589 for f in futures.values():

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in gather(self, futures, errors, direct, asynchronous) 1883 direct=direct, 1884 local_worker=local_worker, -> 1885 asynchronous=asynchronous, 1886 ) 1887

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in sync(self, func, asynchronous, callback_timeout, *args, **kwargs) 765 else: 766 return sync( --> 767 self.loop, func, *args, callback_timeout=callback_timeout, **kwargs 768 ) 769

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/utils.py in sync(loop, func, callback_timeout, *args, **kwargs) 343 if error[0]: 344 typ, exc, tb = error[0] --> 345 raise exc.with_traceback(tb) 346 else: 347 return result[0]

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/utils.py in f() 327 if callback_timeout is not None: 328 future = asyncio.wait_for(future, callback_timeout) --> 329 result[0] = yield future 330 except Exception as exc: 331 error[0] = sys.exc_info()

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/tornado/gen.py in run(self) 733 734 try: --> 735 value = future.result() 736 except Exception: 737 exc_info = sys.exc_info()

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in _gather(self, futures, errors, direct, local_worker) 1739 exc = CancelledError(key) 1740 else: -> 1741 raise exception.with_traceback(traceback) 1742 raise exc 1743 if errors == "skip":

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/optimization.py in call() 980 if not len(args) == len(self.inkeys): 981 raise ValueError("Expected %d args, got %d" % (len(self.inkeys), len(args))) --> 982 return core.get(self.dsk, self.outkey, dict(zip(self.inkeys, args))) 983 984 def reduce(self):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/core.py in get() 147 for key in toposort(dsk): 148 task = dsk[key] --> 149 result = _execute_task(task, cache) 150 cache[key] = result 151 result = _execute_task(out, cache)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/core.py in _execute_task() 116 elif istask(arg): 117 func, args = arg[0], arg[1:] --> 118 args2 = [_execute_task(a, cache) for a in args] 119 return func(*args2) 120 elif not ishashable(arg):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/core.py in () 116 elif istask(arg): 117 func, args = arg[0], arg[1:] --> 118 args2 = [_execute_task(a, cache) for a in args] 119 return func(*args2) 120 elif not ishashable(arg):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/core.py in _execute_task() 117 func, args = arg[0], arg[1:] 118 args2 = [_execute_task(a, cache) for a in args] --> 119 return func(*args2) 120 elif not ishashable(arg): 121 return arg

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/utils.py in apply() 27 def apply(func, args, kwargs=None): 28 if kwargs: ---> 29 return func(*args, **kwargs) 30 else: 31 return func(*args)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/io/sql.py in _read_sql_chunk() 211 return meta 212 else: --> 213 return df.astype(meta.dtypes.to_dict(), copy=False)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/generic.py in astype() 5681 if col_name in dtype: 5682 results.append( -> 5683 col.astype(dtype=dtype[col_name], copy=copy, errors=errors) 5684 ) 5685 else:

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/generic.py in astype() 5696 else: 5697 # else, only a single dtype is given -> 5698 new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors) 5699 return self._constructor(new_data).finalize(self) 5700

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/internals/managers.py in astype() 580 581 def astype(self, dtype, copy: bool = False, errors: str = "raise"): --> 582 return self.apply("astype", dtype=dtype, copy=copy, errors=errors) 583 584 def convert(self, **kwargs):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/internals/managers.py in apply() 440 applied = b.apply(f, **kwargs) 441 else: --> 442 applied = getattr(b, f)(**kwargs) 443 result_blocks = _extend_blocks(applied, result_blocks) 444

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/internals/blocks.py in astype() 623 vals1d = values.ravel() 624 try: --> 625 values = astype_nansafe(vals1d, dtype, copy=True) 626 except (ValueError, TypeError): 627 # e.g. astype_nansafe can fail on object-dtype of strings

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/dtypes/cast.py in astype_nansafe() 866 867 if not np.isfinite(arr).all(): --> 868 raise ValueError("Cannot convert non-finite values (NA or inf) to integer") 869 870 elif is_object_dtype(arr):

ValueError: Cannot convert non-finite values (NA or inf) to integer

ks233ever avatar May 01 '20 20:05 ks233ever

OK. So the next place I would look is your call to read_sql_table. Something strange is going on there with the dtypes. I think read_sql_table infers the dtypes by looking at a sample 5 rows from the table

head_rows : int
    How many rows to load for inferring the data-types, unless passing meta
meta : empty DataFrame or None
    If provided, do not attempt to infer dtypes, but use these, coercing
    all chunks on load

If possible, can you provide a meta that's an empty pandas DataFrame with the actual dtypes you expect? I suspect that there's one or more columns where the first 5 rows are all integers, but there are some missing values later on.

TomAugspurger avatar May 01 '20 20:05 TomAugspurger

Thanks sorry I don't have a ton of experience with dask's read_sql_table

I created an empty meta dataframe like so--

meta = pd.DataFrame(columns = list(col['column_names']), dtype='float')

-- it now requires npartitions df = dd.read_sql_table(table='XXXX', uri=uri, index_col='rownumber', schema='XXXX', meta = meta, npartitions = 1000)

all the column names appear to align;

dask_cols = list(df.columns) meta_cols = list(col['column_names'])

len(meta_cols) == len(dask_cols) True

for a in meta_cols: try: a in dask_cols except a not in dask_cols: print(a)

for a in dask_cols: try: a in meta_cols except a not in meta_cols: print(a)

everything appears to match up but when i run len(df) it returns:


KeyError Traceback (most recent call last) in () ----> 1 len(df) 2 #

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/core.py in len(self) 3316 return super().len() 3317 else: -> 3318 return len(s) 3319 3320 def getitem(self, key):

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/core.py in len(self) 525 def len(self): 526 return self.reduction( --> 527 len, np.sum, token="len", meta=int, split_every=False 528 ).compute() 529

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/base.py in compute(self, **kwargs) 163 dask.base.compute 164 """ --> 165 (result,) = compute(self, traverse=False, **kwargs) 166 return result 167

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/base.py in compute(*args, **kwargs) 434 keys = [x.dask_keys() for x in collections] 435 postcomputes = [x.dask_postcompute() for x in collections] --> 436 results = schedule(dsk, keys, **kwargs) 437 return repack([f(r, *a) for r, (f, a) in zip(results, postcomputes)]) 438

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in get(self, dsk, keys, restrictions, loose_restrictions, resources, sync, asynchronous, direct, retries, priority, fifo_timeout, actors, **kwargs) 2585 should_rejoin = False 2586 try: -> 2587 results = self.gather(packed, asynchronous=asynchronous, direct=direct) 2588 finally: 2589 for f in futures.values():

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in gather(self, futures, errors, direct, asynchronous) 1883 direct=direct, 1884 local_worker=local_worker, -> 1885 asynchronous=asynchronous, 1886 ) 1887

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in sync(self, func, asynchronous, callback_timeout, *args, **kwargs) 765 else: 766 return sync( --> 767 self.loop, func, *args, callback_timeout=callback_timeout, **kwargs 768 ) 769

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/utils.py in sync(loop, func, callback_timeout, *args, **kwargs) 343 if error[0]: 344 typ, exc, tb = error[0] --> 345 raise exc.with_traceback(tb) 346 else: 347 return result[0]

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/utils.py in f() 327 if callback_timeout is not None: 328 future = asyncio.wait_for(future, callback_timeout) --> 329 result[0] = yield future 330 except Exception as exc: 331 error[0] = sys.exc_info()

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/tornado/gen.py in run(self) 733 734 try: --> 735 value = future.result() 736 except Exception: 737 exc_info = sys.exc_info()

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/distributed/client.py in _gather(self, futures, errors, direct, local_worker) 1739 exc = CancelledError(key) 1740 else: -> 1741 raise exception.with_traceback(traceback) 1742 raise exc 1743 if errors == "skip":

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/utils.py in apply() 27 def apply(func, args, kwargs=None): 28 if kwargs: ---> 29 return func(*args, **kwargs) 30 else: 31 return func(*args)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/dask/dataframe/io/sql.py in _read_sql_chunk() 211 return meta 212 else: --> 213 return df.astype(meta.dtypes.to_dict(), copy=False)

~/opt/anaconda3/envs/dask-cluster/lib/python3.6/site-packages/pandas/core/generic.py in astype() 5674 if col_name not in self: 5675 raise KeyError( -> 5676 "Only a column name can be used for the " 5677 "key in a dtype mappings argument." 5678 )

KeyError: 'Only a column name can be used for the key in a dtype mappings argument.'

ks233ever avatar May 01 '20 21:05 ks233ever

Hmm I'm not entirely sure. Possibly the index_col? Is that in your meta columns, or in the index? I'm not sure which is correct (or if it's some other issue entirely).

TomAugspurger avatar May 01 '20 21:05 TomAugspurger

Noting here that the index was the problem. Still running into issues afterwards with dtypes, seems to be a bit buggy. Ended up reading in pandas dataframe chunks which worked with no issues.

ks233ever avatar May 08 '20 01:05 ks233ever

OK, thanks. I'm going to close this issue since it doesn't seem to be related to SimpleImputer. LMK if you keep running into issues though.

TomAugspurger avatar May 08 '20 20:05 TomAugspurger