1

I have created a code that generates a matrix with shape (12,12) for color image analyzes using convolutional neural network. The input of my script is a tensor of shape (5,3,12,12). I took off the values 5 and 3 using detach().numpy().

The script :

    for k in range(5):
            for l in range(3):
                y=x[k][l].detach().numpy()
                m,n= y.shape
                im=np.pad(y,((1,1),(1,1)),'constant')
                Enhanced = np.zeros((m,n))
                for i in range(1,m+1):
                    for j in range(1,n+1):
                        ...      
                z.append(Enhanced)

... represents a simple function which I don't want to bother you with.

z is a list of the Enhanced which are arrays. so my goal is to create a torch tensor from the Enhanced numpy arrays with shape (5,3,12,12).

I added this line to my code inside the for loop and i get:

 r=torch.Tensor(z)
 print(r.shape) 

and then print the r.shape and i get that :

 torch.Size([3, 12, 12])
 torch.Size([6, 12, 12])
 torch.Size([9, 12, 12])
 torch.Size([12, 12, 12])
 torch.Size([15, 12, 12]) 

So what I understand is that I need to stack those r tensors. I used the function t=np.stack(r) but what I get is the shape of the last execution which is torch.Size([15, 12, 12]) so how can I modify that to get shape of (5, 3, 12, 12)

1 Answer 1

3

You have to:

  • stack list of np.array together (Enhanced ones)
  • convert it to PyTorch tensors via torch.from_numpy function

For example:

import numpy as np

some_data = [np.random.randn(3, 12, 12) for _ in range(5)]

stacked = np.stack(some_data)
tensor = torch.from_numpy(stacked)

Please note that each np.array in the list has to be of the same shape

For different shapes one could do that:

import numpy as np
import torch

some_data = [np.random.randn(3, 12, 12) for _ in range(5)] + [
    np.random.randn(6, 12, 12)
]

stacked = np.concatenate(some_data).reshape(-1, 3, 12, 12)
tensor = torch.from_numpy(stacked)

print(tensor.shape)

In your case:

r = torch.from_numpy(np.concatenate(z).reshape(-1, 3, 12, 12))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.