Patch Making Does Pytorch have Anything to Offer?

Thomas_Poulsen: <p>I am in the process of making my first CNN challenge and so far what has amazed me is that Pytorch offers almost an easy fix to anything needed. Except for patch making.</p>
<p>I have 3 dimensional data samples ranging in the 500x500x500. Such huge piece of data ofcourse can’t be fed to the network in one piece and therefore Patching is required. In my case the dimensions are not consistent and I do not allow for padding hence some fairly complex coding is required from me to create and reassemble these patches.</p>
<p>Say you want to create 64x64x64 patches out of the 500x500x500 data sample what do you guys do ?</p>
<p>Pytorch solves batch making for you with the dataloader but what about patch making? does Pytorch really not have anything to offer in that regard?</p>

chenglu: <p>Just use indexing</p>
<pre><code class="lang-auto">image[64:128, :, :]
</code></pre>
<p>And, I don’t think patching is a very general need.</p>

Thomas_Poulsen: <p>I am sorry that i pissed you off. Was not my intend</p>

Thomas_Poulsen: <p>Well the suggestion you made is something I am already doing. In my case that is a solution with hundreds of lines of code. It i will involve atleast 3 nested for loops.</p>
<p>and when you do not allow for padding  and you wish overlapping of the data instead it becomes even more complex.</p>
<p>I don’t now if it is not general. I can tell by now that it must be needed in almost any project that involves medical imaging.</p>

chenglu: <p>Sorry for making you think I’m pissed off.  English is not my first language I’m just making suggestions <img src="https://discuss.pytorch.org/images/emoji/apple/crazy_face.png?v=6" title=":crazy_face:" class="emoji" alt=":crazy_face:"></p>

Thomas_Poulsen: <p>sorry your english is fine. It was me who misread. English is not my first language either. It will not remove that comment before 24 hours <img src="https://discuss.pytorch.org/images/emoji/apple/confused.png?v=6" title=":confused:" class="emoji" alt=":confused:"></p>
<p>Sorry for the misunderstanding</p>

chenglu: <p>I think pathing is something belongs to data pre processing or data argumentation like random 5 or 10 crop?</p>

ptrblck: <p>I think <code>.unfold</code> would work in this case.<br>
Have a look at this code:</p>
<pre><code class="lang-python">x = torch.randn(1, 500, 500, 500)  # batch, c, h, w
kc, kh, kw = 64, 64, 64  # kernel size
dc, dh, dw = 64, 64, 64  # stride
patches = x.unfold(1, kc, dc).unfold(2, kh, dh).unfold(3, kw, dw)
patches = patches.contiguous().view(patches.size(0), -1, kc, kh, kw)
print(patches.shape)
&gt; torch.Size([1, 343, 64, 64, 64])
</code></pre>
<p>As you can see <code>patches</code> will give you <code>7*7*7=343</code> patches each of shape <code>[64, 64, 64]</code>.<br>
If you would like to overlap the patches, you should change the stride for each dimension.<br>
Let me know, if that works for you.</p>

Thomas_Poulsen: <p>Can you reassemble them using a similar approach?</p>

Thomas_Poulsen: <p>500 % 64 is not zero so ofcourse you cannot make the orignal 500x500x500 again but can you reassemble the 343 patches back into something that makes sense?</p>
<p>Imagine 500x500x500 being a ct screening</p>

ptrblck: <p>Yes, this would be possible with come permutations and reshaping.<br>
Here is the corresponding code:</p>
<pre><code class="lang-python">x = torch.randn(1, 500, 500, 500)  # batch, c, h, w
kc, kh, kw = 64, 64, 64  # kernel size
dc, dh, dw = 64, 64, 64  # stride
patches = x.unfold(1, kc, dc).unfold(2, kh, dh).unfold(3, kw, dw)
unfold_shape = patches.size()
patches = patches.contiguous().view(patches.size(0), -1, kc, kh, kw)
print(patches.shape)

# Reshape back
patches_orig = patches.view(unfold_shape)
output_c = unfold_shape[1] * unfold_shape[4]
output_h = unfold_shape[2] * unfold_shape[5]
output_w = unfold_shape[3] * unfold_shape[6]
patches_orig = patches_orig.permute(0, 1, 4, 2, 5, 3, 6).contiguous()
patches_orig = patches_orig.view(1, output_c, output_h, output_w)

# Check for equality
print((patches_orig == x[:, :output_c, :output_h, :output_w]).all())
</code></pre>

Thomas_Poulsen: <p>Thank you. You have made my day!</p>

Thomas_Poulsen: <p>I have been playing around with your fine example.</p>
<p>Im not sure it works correctly when it comes to changing the stride.</p>
<p>consider the dimensions 407x301x360 and you define a stride of 20 and kernel of 64<br>
According to my calculation that should yield 20x15x18 = 5400 patches. Alas your code only yields 3240 patches.</p>
<p>I might be calculating it wrong.</p>
<p>In my project I create 64x dim patches and when processed through the network they yield 24x dim result patches. These patches needs needs to be created with enough overlapping to capture the entire screening and they need to be put back together in the same order the patches were extracted from the original screening.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/4/4e8169934c059c797a6dfb24072ae426a36fca50.png" data-download-href="https://discuss.pytorch.org/uploads/default/4e8169934c059c797a6dfb24072ae426a36fca50" title="patchIllu"><img src="https://discuss.pytorch.org/uploads/default/optimized/2X/4/4e8169934c059c797a6dfb24072ae426a36fca50_2_690x425.png" alt="patchIllu" data-base62-sha1="bcuvsNqIddw00sgqCpXIyfx0u0E" width="690" height="425" srcset="https://discuss.pytorch.org/uploads/default/optimized/2X/4/4e8169934c059c797a6dfb24072ae426a36fca50_2_690x425.png, https://discuss.pytorch.org/uploads/default/optimized/2X/4/4e8169934c059c797a6dfb24072ae426a36fca50_2_1035x637.png 1.5x, https://discuss.pytorch.org/uploads/default/original/2X/4/4e8169934c059c797a6dfb24072ae426a36fca50.png 2x" data-dominant-color="A22223"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">patchIllu</span><span class="informations">1189×734 34.5 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div><br>
This is a little illustration i made.<br>
The black box is the original screening<br>
the small red boxes are result 24x dim patches<br>
the gray box is a 64x patch.<br>
the different color boxes is an illustration on how the stride has to work</p>

ptrblck: <p>How did you calculate the number of patches?<br>
According to the <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d" rel="nofollow noopener">nn.Conv2d docs</a> you should get <code>18*12*15=3240</code> patches:</p>
<pre><code class="lang-python">c = 407
h = 301
w = 360
dilation = 1
padding = 0
kernel_size = 64
stride = 20

print((c + 2*padding - dilation * (kernel_size - 1) - 1) / stride + 1)
print((h + 2*padding - dilation * (kernel_size - 1) - 1) / stride + 1)
print((w + 2*padding - dilation * (kernel_size - 1) - 1) / stride + 1)
</code></pre>

Thomas_Poulsen: <p>407/20 = 20<br>
301/20 = 15<br>
360/20 = 18</p>
<p>20x15x18 = 5400</p>
<p>I am using conv3d. a ct screening is not a 2 dimensional image it is a 3 dimensional voxel space. (nifti/dicom)</p>
<p>But as far as i can see x in your example is 3 dimensional(technically 4). So the problem is perhaps that you are only striding along 2 axis and not 3 ?</p>
<p>Only guessing and perhaps I am the one miss calculating.</p>

ptrblck: <p>Yeah, I assumed you are using a 3-dim medical image. That’s why I also used the “channel” dimension to create the patches. Otherwise the complete channels would be used in each 2-dim patch.</p>
<p>The size calculation would be the same for <code>nn.Conv3d</code>, but apparently I posted the definition for <code>nn.Conv2d</code> <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=6" title=":wink:" class="emoji" alt=":wink:"><br>
Your calculations e.g. ignore the kernel size and assume some padding. Note that the “last” kernel might not fit into your input for a certain stride.</p>

Oliver: <p>Hi ptrblck, I’ve been trying unfold, how would I get the batch size right? should I just feed the reshaped tensor with (num_patches_in_y *num_patches_in_x * batch_size, height, width, channel) shape?</p>

ptrblck: <p>Assuming you are using <a href="https://discuss.pytorch.org/t/patch-making-does-pytorch-have-anything-to-offer/33850/11">this code snippet</a>, then you wouldn’t have to change anything besides assigning a different batch size to the input and <code>view</code> operation:</p>
<pre><code class="lang-python"># changes needed
batch_size = 16
x = torch.randn(batch_size, 500, 500, 500)  # batch, c, h, w
...
patches_orig = patches_orig.view(batch_size, output_c, output_h, output_w)
</code></pre>
<p>since the code is not applying any operation on the batch dimension and thus keeps it equal.</p>