Skip to content

[MRG+1] Use astype(.., copy=False) when possible - #11973

Merged
GaelVaroquaux merged 14 commits into
scikit-learn:masterfrom
rth:use-asarray-copy-false
Mar 1, 2019
Merged

GaelVaroquaux merged 14 commits into
scikit-learn:masterfrom
rth:use-asarray-copy-false

Conversation

@rth

@rth rth commented Sep 2, 2018

Copy link
Copy Markdown
Member

This uses X.astype(..., copy=False) when possible to avoid memory copies.

Closes #11970

I have manually reviewed all cases of .astype and manually added copy=False when this makes sense (i.e. when the array can be of the same dtype as the target dtype)

To support the copy argument for both sparse and dense arrays, a new utils.fixes._astype_copy_false function is added. It can be used as,

X = X.astype('float32', **_astype_copy_false(X))

This is somewhat awkward, however it makes it explicit that this is a temporary fix that can be dropped once we only support scipy > 1.1 and IMO is better in this sense than,

if X.dtype != np.float32:
   X = X.astype('float32', copy=False)

as the latter essentially permanently re-implements some checks from numpy/scipy.

@rth rth changed the title Use astype(.., copy=False) when possible [MRG] Use astype(.., copy=False) when possible Sep 2, 2018
@rth

rth commented Sep 2, 2018

Copy link
Copy Markdown
Member Author

Circle CI python 2 build failed due to https://github.com/tomMoral/loky/issues/151 as it did in #11899 (comment) in the Circle CI running on my fork. Interestingly it didn't fail there when merged into master.

@rth
rth requested a review from glemaitre September 13, 2018 15:57
Comment thread sklearn/utils/fixes.py Outdated

# TODO: replace by copy=False, when only scipy > 1.1 is supported.
def _astype_copy_false(X):
"""Returns the copy=False parameter for {ndarray,csr_matrix,csc_matrix}.astype

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PEP8

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review! You are right, it's too long (although technically it passed flake8) -- Fixed.

Comment thread sklearn/impute.py Outdated

for i, (row, row_mask) in enumerate(zip(X[:], mask[:])):
row_mask = np.logical_not(row_mask).astype(np.bool)
row_mask = np.logical_not(row_mask).astype(np.bool, copy=False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PEP8

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code review capability of your editor must be adding extra spaces :)

This is 79 character long and valid according to PEP8.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ups got trapped by my own editor :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually we don't need astype here since row_mask will always be bool since mask is bool. However, there is a astype in fixes which might changed:

return np.frompyfunc(lambda x: x != x, 1, 1)(X).astype(bool)

Comment thread sklearn/preprocessing/imputation.py Outdated

for i, (row, row_mask) in enumerate(zip(X[:], mask[:])):
row_mask = np.logical_not(row_mask).astype(np.bool)
row_mask = np.logical_not(row_mask).astype(np.bool, copy=False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we change a deprecate file?

Comment thread sklearn/cluster/hierarchical.py Outdated
if affinity == 'precomputed':
distances = X[connectivity.row, connectivity.col].astype('float64')
distances = X[connectivity.row, connectivity.col].astype(
'float64', **_astype_copy_false(X))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flake8 tell me 4 spaces less ;)

@glemaitre

Copy link
Copy Markdown
Member

LGTM. if you could have a pass on the following occurences. I am not 100% sure that they should change.

  • test_hierarchical.py -> l. 302
  • test_k_means.py -> l. 806
  • test_svmlight_format.py -> l. 231 - 261 - 263 - 267 - 269
  • test_spectral_embedding.py -> l. 125
  • supervised.py -> l. 856
  • metrics/tests/test_classification -> l. 724 - 727

@jnothman jnothman left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is hard to review this very thoroughly, so I would be unsure if there are cases where a copy was intended. I would be happy to merge it into master (but not 0.20.X) and see if any users complain of breakage in 0.21dev.

@glemaitre

Copy link
Copy Markdown
Member

I think that @jnothman is right. Actually, we could merge it now without backport in 0.20.X.

@jnothman

Copy link
Copy Markdown
Member

Do you want to add a what's new?

@rth
rth force-pushed the use-asarray-copy-false branch from 1fd1ed5 to faa16a1 Compare September 26, 2018 21:02
@rth

rth commented Sep 26, 2018

Copy link
Copy Markdown
Member Author

Thanks for the review!

Addressed some of @glemaitre 's comments, rebased (to include the v0.21 what's new template) and added a what's new.

@jnothman

Copy link
Copy Markdown
Member

As I implied, I can't claim to thoroughly review this with confidence, but I'm okay to merge it on trust and the test of time, once we've dropped Py2 support.

@rth
rth force-pushed the use-asarray-copy-false branch from faa16a1 to 40f4e35 Compare October 14, 2018 13:16
@jnothman

jnothman commented Jan 6, 2019

Copy link
Copy Markdown
Member

CI failing, @rth

@rth
rth force-pushed the use-asarray-copy-false branch from b2db080 to 3d2cf40 Compare February 27, 2019 15:20
@rth

rth commented Feb 27, 2019

Copy link
Copy Markdown
Member Author

Rebased and fixed CI.

CI is in progress but it should pass (last commit only linting failed).

@agramfort agramfort changed the title [MRG] Use astype(.., copy=False) when possible [MRG+1] Use astype(.., copy=False) when possible Feb 28, 2019
Comment thread sklearn/cluster/hierarchical.py Outdated
# Convert edge list into standard hierarchical clustering format
single_linkage_tree = _hierarchical._single_linkage_label(mst_array)
children_ = single_linkage_tree[:, :2].astype(np.int)
children_ = single_linkage_tree[:, :2].astype(np.int, copy=False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, here I think that it's beneficial to have a copy. It's a somewhat subtle reason:

We are taking a view of the data that is smaller than the original data, via the slicing. This view references the original data. If no copy is made, the original data cannot be garbage collected, and memory is wasted.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to fix or not?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will fix tomorrow...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, removed the copy=False here.

Comment thread sklearn/cluster/hierarchical.py Outdated
X = np.require(X, requirements="W")
out = hierarchy.ward(X)
children_ = out[:, :2].astype(np.intp)
children_ = out[:, :2].astype(np.intp, copy=False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whether or not the argument about view not being released applies here or not depends on whether we have return_distance or not. I am not sure whether or not the copy should be kept or not.

This comment does not ask for a change in the diff. It's just a reflection as I pass by.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed copy=False here to use the defaults when in doubt.

@GaelVaroquaux GaelVaroquaux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

I did make a comment that I think would be an improvement. But if y'all think that it's a nitpick, I don't mind merging without taking in account my comment.

@GaelVaroquaux

Copy link
Copy Markdown
Member

Awesome. Merging!

@GaelVaroquaux
GaelVaroquaux merged commit cf9a740 into scikit-learn:master Mar 1, 2019
@rth
rth deleted the use-asarray-copy-false branch March 1, 2019 10:08
xhluca pushed a commit to xhluca/scikit-learn that referenced this pull request Apr 28, 2019
* Use astype(.., copy=False) when possible

* Use Use astype(.., copy=False) also in tests

* Fix CI

* Guillaume's comments

* Address review comments

* Add what's new

* Fix CI

* Lint

* Fix merge issues

* More merge conflict fixes

* Fix failing test

* Lint

* Use copy=True in cluster/hierarchical

* More fixes
xhluca pushed a commit to xhluca/scikit-learn that referenced this pull request Apr 28, 2019
xhluca pushed a commit to xhluca/scikit-learn that referenced this pull request Apr 28, 2019
koenvandevelde pushed a commit to koenvandevelde/scikit-learn that referenced this pull request Jul 12, 2019
* Use astype(.., copy=False) when possible

* Use Use astype(.., copy=False) also in tests

* Fix CI

* Guillaume's comments

* Address review comments

* Add what's new

* Fix CI

* Lint

* Fix merge issues

* More merge conflict fixes

* Fix failing test

* Lint

* Use copy=True in cluster/hierarchical

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Avoid copies in array.astype

5 participants