Ben Gorman

Ben Gorman

Life's a garden. Dig it.

Challenge

Create a 10x10 tensor of 32-bit integers filled with zeros. Then select a random 3x3 block inside the tensor and switch the values from 0 to 1.

Bonus
You can interpret this tensor as an image where 0s represent black pixels and 1s represent white pixels. Plot the image.


Solution

import torch
import random
 
random.seed(123)
 
foo = torch.zeros(size=(10,10), dtype=torch.int32)
i, j = random.randint(0, 7), random.randint(0, 7)
foo[i:(i+3), j:(j+3)] = 1

Explanation

  1. Instantiate a 10x10 tensor of 32-bit integer 0s.

    foo = torch.zeros(size=(10,10), dtype=torch.int32)
     
    print(foo)
    # 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]], dtype=torch.int32)

    By default, torch.zeros() creates floats, so we explicitly tell it to use 32-bit integers with dtype=torch.int32.

  2. Randomly choose the top-left cell of the 3x3 block.

    We choose random a random (i,j) element such that the entire 3x3 block will fit inside foo.

    import random
        
    random.seed(123)
    i, j = random.randint(0, 7), random.randint(0, 7)
    print(i)  # 0
    print(j)  # 4
  3. Select the 3x3 block and update 0s to 1s.

    foo[i:(i+3), j:(j+3)] = 1
     
    print(foo)
    # tensor([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    #         [0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
    #         [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, 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]], dtype=torch.int32)

Bonus
We can plot the array as an image using matplotlib.pyplot.imshow() with cmap='gray'.

import matplotlib.pyplot as plt
plt.imshow(foo, cmap='gray')