How to do a unravel_index in pytorch just like in numpy

username: tztztztztz
cooked: <p>how to converts a flat index or array of flat indices into a tuple of coordinate arrays.<br>
here is a example in numpy</p>
<pre><code class="lang-auto">np.unravel_index([22, 41, 37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
</code></pre>
<p>can anyone help me ? thank you !</p>

username: emanjavacas
cooked: <p>Continuing the discussion from <a href="https://discuss.pytorch.org/t/how-to-do-a-unravel-index-in-pytorch-just-like-in-numpy/12987">How to do a unravel_index in pytorch just like in numpy</a>:</p>
<p>AFAIK unravel_index is basically converting a 1D index into its corresponding 2D version.</p>
<p>The general formula for this is:</p>
<pre><code class="lang-auto">x = index / ncols # (integer division in pytorch tensors is just `/` not `//`)
y = index % ncols
</code></pre>
<p>So you can get what you want using this code:</p>
<pre><code class="lang-auto">index = torch.tensor([22, 41, 37])
rows = index / 6
cols = index % 6

print(rows)
print(cols)
tensor([ 3,  6,  6])
tensor([ 4,  5,  1])
</code></pre>

username: ModarTensai
cooked: <p>Here is a generalized solution for any number of dimensions:</p>
<pre><code class="lang-python">import torch


def unravel_index(index, shape):
    out = []
    for dim in reversed(shape):
        out.append(index % dim)
        index = index // dim
    return tuple(reversed(out))

x = torch.arange(30).view(10, 3)
for i in range(x.numel()):
    assert i == x[unravel_index(i, x.shape)]
</code></pre>

username: dmitryako
cooked: <p>So, what is the correct way to get torch’s np.unravel_index?</p>

username: francois-rozet
cooked: <p>I’ve written a more general (and efficient) <code>unravel_index</code> function, which I have posted here:<br>
</p><aside class="onebox githubissue">
  <header class="source">
      <a href="https://github.com/pytorch/pytorch/issues/35674#issuecomment-739492875" target="_blank" rel="noopener nofollow ugc">github.com/pytorch/pytorch</a>
  </header>
  <article class="onebox-body">
    <div class="github-row">
  <div class="github-icon-container" title="Issue">
	  <svg width="60" height="60" class="github-icon" viewBox="0 0 14 16" aria-hidden="true"><path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"></path></svg>
  </div>

  <div class="github-info-container">
    <h4>
      <a href="https://github.com/pytorch/pytorch/issues/35674#issuecomment-739492875" target="_blank" rel="noopener nofollow ugc">add torch.unravel_index</a>
    </h4>

    <div class="github-info">
      <div class="date">
        opened <span class="discourse-local-date" data-format="ll" data-date="2020-03-30" data-time="14:47:15" data-timezone="UTC">02:47PM - 30 Mar 20 UTC</span>
      </div>


      <div class="user">
        <a href="https://github.com/tycho01" target="_blank" rel="noopener nofollow ugc">
          <img alt="tycho01" src="https://avatars3.githubusercontent.com/u/3059397?v=4" class="onebox-avatar-inline" width="20" height="20">
          tycho01
        </a>
      </div>
    </div>
  </div>
</div>

<div class="github-row">
  <p class="github-content">🚀 Feature
This function would mirror np.unravel_index; a basic Torch implementation and todo to formally expose such an implementation were previously added...</p>
</div>

<div class="labels">
    <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">feature</span>
    <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">module: numpy</span>
    <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">triaged</span>
</div>

  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>

<p>I’m quite new to the PyTorch community so I don’t really know how I should (or even if I should) do a PR for that.</p>
<p>Since you are the <em>king</em> of this forum, <a class="mention" href="/u/ptrblck">@ptrblck</a>  maybe do you know ?</p>

username: ptrblck
cooked: <p>Thanks for sharing your approach! Let’s continue the discussion in the feature request.</p>
<aside class="quote no-group" data-username="francois-rozet" data-post="5" data-topic="12987">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/francois-rozet/48/29950_2.png" class="avatar"> francois-rozet:</div>
<blockquote>
<p>Since you are the <em>king</em> of this forum, <a class="mention" href="/u/ptrblck">@ptrblck</a> maybe do you know ?</p>
</blockquote>
</aside>
<p>Haha, history wasn’t always nice to monarchs, so I hope I’m more the first layer of defense against nasty bugs. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=12" title=":wink:" class="emoji" alt=":wink:" loading="lazy" width="20" height="20"></p>