<jupyter_start><jupyter_text>Tensor Manipulation and slicing Pytorch Tensors behave in similar fashion as numpy arrays. Lets see how we can perform some basic operations of selection and filtering on them. First lets start with a 2D tensor (matrix) and see how we can select and filter this. Lets create a Double tensor with random initialization<jupyter_code>a = torch.randn(7, 7, dtype=torch.double)
a
a[:, :] = 0   # Assign zeros everywhere in the matrix.
a[3, 3] = 1   # Assign one in position 3, 3
a
def showTensor(tmp):
    plt.figure()
    plt.imshow(tmp.numpy(),cmap = 'gray')
    plt.colorbar()
    plt.show()
showTensor(a)<jupyter_output><empty_output><jupyter_text>Here 1 corresponds to white color and 0 is black color. Since we have assigned only element (3rd Row , 3rd column) as 1, and other as 0 we have only white for middle of matrix.Similar to assigning 1 element we can slice and assign values to a subset of matrix also<jupyter_code>a[:, :] = 0   # Assign zeros everywhere in the matrix.
a[:2, :] = 1   # Assign ones on the top 2 rows.
a[-2:, :] = 1    # Assign ones on the bottom 2 rows.
a
showTensor(a)<jupyter_output><empty_output><jupyter_text>Now lets see how we can manipulate higher order (3D and more) tensors. Lets start with<jupyter_code># Get the CIFAR10 train images , download if necessary
cifar_dt = torchvision.datasets.CIFAR10 ('data/', train = True , download = True )
cifar_dt.train_data.shape<jupyter_output><empty_output><jupyter_text>This code has 50000 images of shape 32*32 size. The images present are in RGB format. The images are present as a numpy array. Lets take one image and perform selection and filtering on it<jupyter_code>b = torch.from_numpy(cifar_dt.train_data[4])
b
plt.imshow(b)<jupyter_output><empty_output><jupyter_text>This is a 3D tensor/image whose size is 32 x 32 x 3.In this tensor there are 3 values corresponding to Red,Green,Blue channel for 32 x 32 grid corresponding to width and hieght of the image.Now lets perform some selection and filtering operations<jupyter_code>c = b.clone()
c[:10,:,:] = 0 # Assign 0 or black to the first 10 rows and all columns and all channels of the image
plt.imshow(c)
c[:,:10,:]  =  0
c
plt.imshow(c)<jupyter_output><empty_output><jupyter_text>Lets perform a transpose operation and see the transposed image<jupyter_code>plt.imshow(c.t())<jupyter_output><empty_output><jupyter_text>Now if i want to extract only the upper right hand corner 5 grid pixel from the image which is sky of the image. We can do it as below<jupyter_code>d = c[0:5,25:,:]
d
d.shape
plt.imshow(d)<jupyter_output><empty_output><jupyter_text>Now lets perform the same operations on 4D tensor. In our case the 4D tensor corresponds to multiple images in a single tensor<jupyter_code>b = cifar_dt.train_data[:2]
b = torch.from_numpy(b)
b.shape
def showimgSideBySide(b):
    fig,ax = plt.subplots(nrows  = 1,ncols=2)
    ax[0].imshow(b[0])
    ax[1].imshow(b[1])
showimgSideBySide(b)<jupyter_output><empty_output><jupyter_text>Now lets transpose the entrire 4D tensor. We will use the built in Pytorch transpose function to do that. We want to transpose the height and width of the image so we will provide 1 and 2 as dimension axes<jupyter_code>tt =b.transpose(1, 2)
showimgSideBySide(tt)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08778857837181045, 'fraction_numerical': 0.02339003645200486, 'mean_word_length': 5.109461966604823, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '403473', 'license': 'MIT', 'n_tokens_mistral': 1167, 'n_tokens_neox': 1088, 'n_words': 414, 'path': 'Pytorch_tensor_manipulation.ipynb', 'repo_name': 'deepSattva/PyTorch_Basics', 'size': '3292'}