In Dask, can tensors be reshaped to 2D matrices in Dask without precomputing the size?










1














While trying to create a python base class capable of vectorizing scalar functions on Dask, I encountered a problem reshaping tensors to 2D matrices. Solving this issue would facilitate the creation of sklearn pipelines that operate interchangeably on Numpy, Pandas and Dask datatypes.



The following code works on Dask 0.18.2 but fails on Dask 0.19.4 and 0.20.0:



import dask
import dask.array
import dask.dataframe
import numpy
import pandas

def and1(x): return numpy.array([x, x+1], dtype=numpy.float32)

expected = numpy.array([[10, 11, 20, 21],
[30, 31, 40, 41]],
dtype=numpy.float32)

df = pandas.DataFrame.from_dict(
'c1': [10, 30], 'c2': [20, 40]
)

ddf = dask.dataframe.from_pandas(df, npartitions=2)

# Dask generalized universal function that outputs 2 values per input value
guf = dask.array.gufunc(
pyfunc=and1,
signature='()->(n)',
output_dtypes=numpy.float32,
output_sizes='n': 2,
vectorize=True,
allow_rechunk = False
)

da = guf(ddf)
da_reshaped = da.reshape((-1, numpy.prod(da.shape[1:])))
npa = da_reshaped.compute()

assert da.shape == (2, 2, 2) # (input rows, input cols, outputs per cols)
numpy.testing.assert_array_equal(expected, npa)


In Dask 0.19.4 and 0.20.0 reshape raises a ValueError since the first element of das shape is NaN (see the stack trace for details).



ValueErrorTraceback (most recent call last)
<ipython-input-847-ad2c41e1d88c> in <module>
24
25 da = guf(ddf)
---> 26 da_r = da.reshape((-1, numpy.prod(da.shape[1:])))
27 npa = da_r.compute()
28

/opt/conda/lib/python3.6/site-packages/dask/array/core.py in reshape(self, *shape)
1398 if len(shape) == 1 and not isinstance(shape[0], Number):
1399 shape = shape[0]
-> 1400 return reshape(self, shape)
1401
1402 def topk(self, k, axis=-1, split_every=None):

/opt/conda/lib/python3.6/site-packages/dask/array/reshape.py in reshape(x, shape)
160 if len(shape) == 1 and x.ndim == 1:
161 return x
--> 162 missing_size = sanitize_index(x.size / reduce(mul, known_sizes, 1))
163 shape = tuple(missing_size if s == -1 else s for s in shape)
164

/opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in sanitize_index(ind)
58 _sanitize_index_element(ind.step))
59 elif isinstance(ind, Number):
---> 60 return _sanitize_index_element(ind)
61 elif is_dask_collection(ind):
62 return ind

/opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in _sanitize_index_element(ind)
20 """Sanitize a one-element index."""
21 if isinstance(ind, Number):
---> 22 ind2 = int(ind)
23 if ind2 != ind:
24 raise IndexError("Bad index. Must be integer-like: %s" % ind)

ValueError: cannot convert float NaN to integer


Is there another way to reshape Dask Arrays in Dask 0.20.0+ without precomputing the size?
If so, is the reshaping a constant time operation as it appears to be in Numpy?



I want to create a matrix (shape = (R, C)) such that the first axis is not changed but all subsequent axes are merged in "C" order (the default in both Dask and Numpy).



(BTW, I already saw: Reshape a dask array (obtained from a dask dataframe column))










share|improve this question


























    1














    While trying to create a python base class capable of vectorizing scalar functions on Dask, I encountered a problem reshaping tensors to 2D matrices. Solving this issue would facilitate the creation of sklearn pipelines that operate interchangeably on Numpy, Pandas and Dask datatypes.



    The following code works on Dask 0.18.2 but fails on Dask 0.19.4 and 0.20.0:



    import dask
    import dask.array
    import dask.dataframe
    import numpy
    import pandas

    def and1(x): return numpy.array([x, x+1], dtype=numpy.float32)

    expected = numpy.array([[10, 11, 20, 21],
    [30, 31, 40, 41]],
    dtype=numpy.float32)

    df = pandas.DataFrame.from_dict(
    'c1': [10, 30], 'c2': [20, 40]
    )

    ddf = dask.dataframe.from_pandas(df, npartitions=2)

    # Dask generalized universal function that outputs 2 values per input value
    guf = dask.array.gufunc(
    pyfunc=and1,
    signature='()->(n)',
    output_dtypes=numpy.float32,
    output_sizes='n': 2,
    vectorize=True,
    allow_rechunk = False
    )

    da = guf(ddf)
    da_reshaped = da.reshape((-1, numpy.prod(da.shape[1:])))
    npa = da_reshaped.compute()

    assert da.shape == (2, 2, 2) # (input rows, input cols, outputs per cols)
    numpy.testing.assert_array_equal(expected, npa)


    In Dask 0.19.4 and 0.20.0 reshape raises a ValueError since the first element of das shape is NaN (see the stack trace for details).



    ValueErrorTraceback (most recent call last)
    <ipython-input-847-ad2c41e1d88c> in <module>
    24
    25 da = guf(ddf)
    ---> 26 da_r = da.reshape((-1, numpy.prod(da.shape[1:])))
    27 npa = da_r.compute()
    28

    /opt/conda/lib/python3.6/site-packages/dask/array/core.py in reshape(self, *shape)
    1398 if len(shape) == 1 and not isinstance(shape[0], Number):
    1399 shape = shape[0]
    -> 1400 return reshape(self, shape)
    1401
    1402 def topk(self, k, axis=-1, split_every=None):

    /opt/conda/lib/python3.6/site-packages/dask/array/reshape.py in reshape(x, shape)
    160 if len(shape) == 1 and x.ndim == 1:
    161 return x
    --> 162 missing_size = sanitize_index(x.size / reduce(mul, known_sizes, 1))
    163 shape = tuple(missing_size if s == -1 else s for s in shape)
    164

    /opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in sanitize_index(ind)
    58 _sanitize_index_element(ind.step))
    59 elif isinstance(ind, Number):
    ---> 60 return _sanitize_index_element(ind)
    61 elif is_dask_collection(ind):
    62 return ind

    /opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in _sanitize_index_element(ind)
    20 """Sanitize a one-element index."""
    21 if isinstance(ind, Number):
    ---> 22 ind2 = int(ind)
    23 if ind2 != ind:
    24 raise IndexError("Bad index. Must be integer-like: %s" % ind)

    ValueError: cannot convert float NaN to integer


    Is there another way to reshape Dask Arrays in Dask 0.20.0+ without precomputing the size?
    If so, is the reshaping a constant time operation as it appears to be in Numpy?



    I want to create a matrix (shape = (R, C)) such that the first axis is not changed but all subsequent axes are merged in "C" order (the default in both Dask and Numpy).



    (BTW, I already saw: Reshape a dask array (obtained from a dask dataframe column))










    share|improve this question
























      1












      1








      1


      1





      While trying to create a python base class capable of vectorizing scalar functions on Dask, I encountered a problem reshaping tensors to 2D matrices. Solving this issue would facilitate the creation of sklearn pipelines that operate interchangeably on Numpy, Pandas and Dask datatypes.



      The following code works on Dask 0.18.2 but fails on Dask 0.19.4 and 0.20.0:



      import dask
      import dask.array
      import dask.dataframe
      import numpy
      import pandas

      def and1(x): return numpy.array([x, x+1], dtype=numpy.float32)

      expected = numpy.array([[10, 11, 20, 21],
      [30, 31, 40, 41]],
      dtype=numpy.float32)

      df = pandas.DataFrame.from_dict(
      'c1': [10, 30], 'c2': [20, 40]
      )

      ddf = dask.dataframe.from_pandas(df, npartitions=2)

      # Dask generalized universal function that outputs 2 values per input value
      guf = dask.array.gufunc(
      pyfunc=and1,
      signature='()->(n)',
      output_dtypes=numpy.float32,
      output_sizes='n': 2,
      vectorize=True,
      allow_rechunk = False
      )

      da = guf(ddf)
      da_reshaped = da.reshape((-1, numpy.prod(da.shape[1:])))
      npa = da_reshaped.compute()

      assert da.shape == (2, 2, 2) # (input rows, input cols, outputs per cols)
      numpy.testing.assert_array_equal(expected, npa)


      In Dask 0.19.4 and 0.20.0 reshape raises a ValueError since the first element of das shape is NaN (see the stack trace for details).



      ValueErrorTraceback (most recent call last)
      <ipython-input-847-ad2c41e1d88c> in <module>
      24
      25 da = guf(ddf)
      ---> 26 da_r = da.reshape((-1, numpy.prod(da.shape[1:])))
      27 npa = da_r.compute()
      28

      /opt/conda/lib/python3.6/site-packages/dask/array/core.py in reshape(self, *shape)
      1398 if len(shape) == 1 and not isinstance(shape[0], Number):
      1399 shape = shape[0]
      -> 1400 return reshape(self, shape)
      1401
      1402 def topk(self, k, axis=-1, split_every=None):

      /opt/conda/lib/python3.6/site-packages/dask/array/reshape.py in reshape(x, shape)
      160 if len(shape) == 1 and x.ndim == 1:
      161 return x
      --> 162 missing_size = sanitize_index(x.size / reduce(mul, known_sizes, 1))
      163 shape = tuple(missing_size if s == -1 else s for s in shape)
      164

      /opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in sanitize_index(ind)
      58 _sanitize_index_element(ind.step))
      59 elif isinstance(ind, Number):
      ---> 60 return _sanitize_index_element(ind)
      61 elif is_dask_collection(ind):
      62 return ind

      /opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in _sanitize_index_element(ind)
      20 """Sanitize a one-element index."""
      21 if isinstance(ind, Number):
      ---> 22 ind2 = int(ind)
      23 if ind2 != ind:
      24 raise IndexError("Bad index. Must be integer-like: %s" % ind)

      ValueError: cannot convert float NaN to integer


      Is there another way to reshape Dask Arrays in Dask 0.20.0+ without precomputing the size?
      If so, is the reshaping a constant time operation as it appears to be in Numpy?



      I want to create a matrix (shape = (R, C)) such that the first axis is not changed but all subsequent axes are merged in "C" order (the default in both Dask and Numpy).



      (BTW, I already saw: Reshape a dask array (obtained from a dask dataframe column))










      share|improve this question













      While trying to create a python base class capable of vectorizing scalar functions on Dask, I encountered a problem reshaping tensors to 2D matrices. Solving this issue would facilitate the creation of sklearn pipelines that operate interchangeably on Numpy, Pandas and Dask datatypes.



      The following code works on Dask 0.18.2 but fails on Dask 0.19.4 and 0.20.0:



      import dask
      import dask.array
      import dask.dataframe
      import numpy
      import pandas

      def and1(x): return numpy.array([x, x+1], dtype=numpy.float32)

      expected = numpy.array([[10, 11, 20, 21],
      [30, 31, 40, 41]],
      dtype=numpy.float32)

      df = pandas.DataFrame.from_dict(
      'c1': [10, 30], 'c2': [20, 40]
      )

      ddf = dask.dataframe.from_pandas(df, npartitions=2)

      # Dask generalized universal function that outputs 2 values per input value
      guf = dask.array.gufunc(
      pyfunc=and1,
      signature='()->(n)',
      output_dtypes=numpy.float32,
      output_sizes='n': 2,
      vectorize=True,
      allow_rechunk = False
      )

      da = guf(ddf)
      da_reshaped = da.reshape((-1, numpy.prod(da.shape[1:])))
      npa = da_reshaped.compute()

      assert da.shape == (2, 2, 2) # (input rows, input cols, outputs per cols)
      numpy.testing.assert_array_equal(expected, npa)


      In Dask 0.19.4 and 0.20.0 reshape raises a ValueError since the first element of das shape is NaN (see the stack trace for details).



      ValueErrorTraceback (most recent call last)
      <ipython-input-847-ad2c41e1d88c> in <module>
      24
      25 da = guf(ddf)
      ---> 26 da_r = da.reshape((-1, numpy.prod(da.shape[1:])))
      27 npa = da_r.compute()
      28

      /opt/conda/lib/python3.6/site-packages/dask/array/core.py in reshape(self, *shape)
      1398 if len(shape) == 1 and not isinstance(shape[0], Number):
      1399 shape = shape[0]
      -> 1400 return reshape(self, shape)
      1401
      1402 def topk(self, k, axis=-1, split_every=None):

      /opt/conda/lib/python3.6/site-packages/dask/array/reshape.py in reshape(x, shape)
      160 if len(shape) == 1 and x.ndim == 1:
      161 return x
      --> 162 missing_size = sanitize_index(x.size / reduce(mul, known_sizes, 1))
      163 shape = tuple(missing_size if s == -1 else s for s in shape)
      164

      /opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in sanitize_index(ind)
      58 _sanitize_index_element(ind.step))
      59 elif isinstance(ind, Number):
      ---> 60 return _sanitize_index_element(ind)
      61 elif is_dask_collection(ind):
      62 return ind

      /opt/conda/lib/python3.6/site-packages/dask/array/slicing.py in _sanitize_index_element(ind)
      20 """Sanitize a one-element index."""
      21 if isinstance(ind, Number):
      ---> 22 ind2 = int(ind)
      23 if ind2 != ind:
      24 raise IndexError("Bad index. Must be integer-like: %s" % ind)

      ValueError: cannot convert float NaN to integer


      Is there another way to reshape Dask Arrays in Dask 0.20.0+ without precomputing the size?
      If so, is the reshaping a constant time operation as it appears to be in Numpy?



      I want to create a matrix (shape = (R, C)) such that the first axis is not changed but all subsequent axes are merged in "C" order (the default in both Dask and Numpy).



      (BTW, I already saw: Reshape a dask array (obtained from a dask dataframe column))







      python pandas numpy dask






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 1:42









      deaktator

      163




      163



























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235320%2fin-dask-can-tensors-be-reshaped-to-2d-matrices-in-dask-without-precomputing-the%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53235320%2fin-dask-can-tensors-be-reshaped-to-2d-matrices-in-dask-without-precomputing-the%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

          Crossroads (UK TV series)

          ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế