Hi! I want to realize this operation:
Here is a 2D tensor:
[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
I want to set 1 to specific square blocks, such like this:
[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,0,0,0,0,1,1,1,0,0,0],
[0,0,1,1,1,0,0,0,0,1,1,1,0,0,0],
[0,0,1,1,1,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,1,1,1,0,0,0,0,1,1,1,0,0,0],
[0,0,1,1,1,0,0,0,0,1,1,1,0,0,0],
[0,0,1,1,1,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
I’ve tried this code before:
import torch
import numpy as np
import matplotlib.pyplot as plt
def random_patch_slice(h, w, p_size, sqrt_n):
i_h = np.random.choice(range(0,h-p_size),size=sqrt_n,replace=False)
i_w = np.random.choice(range(0,w-p_size),size=sqrt_n,replace=False)
i_h = np.linspace(i_h, i_h + p_size-1,p_size,dtype=int,axis=1).flatten()
i_w = np.linspace(i_w, i_w + p_size-1,p_size,dtype=int,axis=1).flatten()
return i_h, i_w
imgs = torch.zeros([10,10])
i_h,i_w = random_patch_slice(10, 10, 5, 2)
imgs[i_h,i_w] = 1
print(imgs)
plt.imshow(imgs)
plt.show()
But torch maps the indexes of the two dimensions one by one instead of the form of Cartesian product.
Then I tried this code:
import torch
import numpy as np
import matplotlib.pyplot as plt
def random_patch_slice(h, w, p_size, sqrt_n):
i_h = np.random.choice(range(0,h-p_size),size=sqrt_n,replace=False)
i_w = np.random.choice(range(0,w-p_size),size=sqrt_n,replace=False)
i_h = np.linspace(i_h, i_h + p_size-1,p_size,dtype=int,axis=1).flatten()
i_w = np.linspace(i_w, i_w + p_size-1,p_size,dtype=int,axis=1).flatten()
return i_h, i_w
imgs = torch.zeros([10,10])
i_h,i_w = random_patch_slice(10, 10, 5, 2)
imgs[i_h][:,i_w] = 1 # modify here
print(imgs)
plt.imshow(imgs)
plt.show()
The value was just not assigned to the tensor. How can I realize this operation?
I would appreciate it if you can help me.