|
| 1 | +--- |
| 2 | +Title: '.randint()' |
| 3 | +Description: 'Returns a tensor filled with random integers generated uniformly between specified bounds.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Machine Learning' |
| 7 | +Tags: |
| 8 | + - 'Functions' |
| 9 | + - 'PyTorch' |
| 10 | + - 'Tensor' |
| 11 | + - 'Random' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/machine-learning' |
| 15 | +--- |
| 16 | + |
| 17 | +**`.randint()`** is a function in [PyTorch](https://www.codecademy.com/resources/docs/pytorch) that generates [tensors](https://www.codecademy.com/resources/docs/pytorch/tensors) filled with random integers. It creates a tensor filled with random integers generated uniformly between a lower bound (inclusive) and an upper bound (exclusive). This function is particularly useful when you need tensors with random integer values within a specific range for various machine learning tasks. |
| 18 | + |
| 19 | +`.randint()` is commonly used in deep learning workflows for tasks such as creating random masks, generating synthetic datasets, initializing tensor values with random integers, and implementing various randomized algorithms. It provides a convenient way to introduce controlled randomness into tensor operations. |
| 20 | + |
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +torch.randint(low=0, high, size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `low`(Optional): The inclusive lower bound of the random integers. Defaults to `0`. |
| 30 | +- `high`: The exclusive upper bound of the random integers. |
| 31 | +- `size`: A tuple defining the shape of the output tensor. |
| 32 | +- `generator`(Optional): A pseudorandom number generator for sampling. |
| 33 | +- `out`(Optional): The output tensor to fill with random integers. |
| 34 | +- `dtype`(Optional): The data type of the returned tensor. Default: `torch.int64`. |
| 35 | +- `layout`(Optional): The desired layout of returned tensor. Default: `torch.strided`. |
| 36 | +- `device`(Optional): The desired device of returned tensor. Default: Uses current device for the default tensor type. |
| 37 | +- `requires_grad`(Optional): If autograd should record operations on the returned tensor. Default: `False`. |
| 38 | + |
| 39 | +**Return value:** |
| 40 | + |
| 41 | +Returns a tensor filled with random integers generated uniformly between `low` (inclusive) and `high` (exclusive). |
| 42 | + |
| 43 | +> **Note:** If there is a need to generate a random integer tensor with the same shape as an existing tensor, use `torch.randint_like()`. It works similarly to `torch.randint()` but automatically inherits the shape and device of the given tensor. |
| 44 | +
|
| 45 | +## Example 1: Creating basic random integer tensors |
| 46 | + |
| 47 | +This example demonstrates how to generate basic tensors with random integer values within specified ranges: |
| 48 | + |
| 49 | +```py |
| 50 | +import torch |
| 51 | + |
| 52 | +# Create a 2x3 tensor with random integers between 0 and 10 |
| 53 | +basic_tensor = torch.randint(0, 10, (2, 3)) |
| 54 | +print("Random tensor with values between 0 and 10:") |
| 55 | +print(basic_tensor) |
| 56 | + |
| 57 | +# Create a 3x4 tensor with random integers between 5 and 15 |
| 58 | +larger_range = torch.randint(5, 15, (3, 4)) |
| 59 | +print("\nRandom tensor with values between 5 and 15:") |
| 60 | +print(larger_range) |
| 61 | + |
| 62 | +# Create a 2x2x2 3D tensor with random integers between -5 and 5 |
| 63 | +three_d_tensor = torch.randint(-5, 5, (2, 2, 2)) |
| 64 | +print("\nRandom 3D tensor with values between -5 and 5:") |
| 65 | +print(three_d_tensor) |
| 66 | +``` |
| 67 | + |
| 68 | +This example results in the following output: |
| 69 | + |
| 70 | +```shell |
| 71 | +Random tensor with values between 0 and 10: |
| 72 | +tensor([[7, 9, 2], |
| 73 | + [3, 6, 8]]) |
| 74 | + |
| 75 | +Random tensor with values between 5 and 15: |
| 76 | +tensor([[10, 13, 8, 14], |
| 77 | + [ 7, 5, 11, 9], |
| 78 | + [14, 12, 7, 6]]) |
| 79 | + |
| 80 | +Random 3D tensor with values between -5 and 5: |
| 81 | +tensor([[[ 2, -2], |
| 82 | + [-3, 4]], |
| 83 | + |
| 84 | + [[ 0, 3], |
| 85 | + [-4, -1]]]) |
| 86 | +``` |
| 87 | + |
| 88 | +## Example 2: Generating random binary masks |
| 89 | + |
| 90 | +This example shows how to create simple random binary masks (containing only 0s and 1s) using `.randint()`: |
| 91 | + |
| 92 | +```py |
| 93 | +import torch |
| 94 | + |
| 95 | +# Set a seed for reproducibility |
| 96 | +torch.manual_seed(42) |
| 97 | + |
| 98 | +# Create a random binary mask (0 or 1) with shape 5x5 |
| 99 | +mask = torch.randint(0, 2, (5, 5)) |
| 100 | +print("Random binary mask:") |
| 101 | +print(mask) |
| 102 | + |
| 103 | +# Count how many 1s are in the mask |
| 104 | +num_ones = mask.sum().item() |
| 105 | +print(f"Number of 1s in the mask: {num_ones}") |
| 106 | +print(f"Number of 0s in the mask: {mask.numel() - num_ones}") |
| 107 | + |
| 108 | +# Apply the mask to a tensor of ones |
| 109 | +data = torch.ones(5, 5) |
| 110 | +masked_data = data * mask |
| 111 | +print("\nData after applying the mask:") |
| 112 | +print(masked_data) |
| 113 | +``` |
| 114 | + |
| 115 | +This example results in the following output: |
| 116 | + |
| 117 | +```shell |
| 118 | +Random binary mask: |
| 119 | +tensor([[1, 1, 0, 0, 0], |
| 120 | + [0, 0, 1, 1, 1], |
| 121 | + [0, 0, 0, 1, 0], |
| 122 | + [1, 1, 0, 1, 1], |
| 123 | + [1, 0, 0, 0, 0]]) |
| 124 | +Number of 1s in the mask: 10 |
| 125 | +Number of 0s in the mask: 15 |
| 126 | + |
| 127 | +Data after applying the mask: |
| 128 | +tensor([[1., 1., 0., 0., 0.], |
| 129 | + [0., 0., 1., 1., 1.], |
| 130 | + [0., 0., 0., 1., 0.], |
| 131 | + [1., 1., 0., 1., 1.], |
| 132 | + [1., 0., 0., 0., 0.]]) |
| 133 | +``` |
| 134 | + |
| 135 | +## Example 3: Creating random dice rolls |
| 136 | + |
| 137 | +This example demonstrates how to simulate dice rolls using `.randint()` to generate random integers between 1 and 6: |
| 138 | + |
| 139 | +```py |
| 140 | +import torch |
| 141 | + |
| 142 | +# Set seed for reproducibility |
| 143 | +torch.manual_seed(123) |
| 144 | + |
| 145 | +# Simulate rolling a single die 10 times |
| 146 | +single_die = torch.randint(1, 7, (10,)) |
| 147 | +print("10 dice rolls:") |
| 148 | +print(single_die) |
| 149 | + |
| 150 | +# Count the frequency of each number |
| 151 | +for i in range(1, 7): |
| 152 | + count = (single_die == i).sum().item() |
| 153 | + print(f"Number {i} appeared {count} times") |
| 154 | + |
| 155 | +# Simulate rolling 5 dice at once |
| 156 | +dice_rolls = torch.randint(1, 7, (5,)) |
| 157 | +print("\n5 dice rolled simultaneously:") |
| 158 | +print(dice_rolls) |
| 159 | + |
| 160 | +# Calculate the sum of the dice |
| 161 | +total = dice_rolls.sum().item() |
| 162 | +print(f"Sum of all dice: {total}") |
| 163 | +``` |
| 164 | + |
| 165 | +This example results in the following output: |
| 166 | + |
| 167 | +```shell |
| 168 | +10 dice rolls: |
| 169 | +tensor([4, 2, 6, 1, 2, 6, 5, 2, 2, 5]) |
| 170 | +Number 1 appeared 1 times |
| 171 | +Number 2 appeared 4 times |
| 172 | +Number 3 appeared 0 times |
| 173 | +Number 4 appeared 1 times |
| 174 | +Number 5 appeared 2 times |
| 175 | +Number 6 appeared 2 times |
| 176 | + |
| 177 | +5 dice rolled simultaneously: |
| 178 | +tensor([1, 3, 4, 6, 3]) |
| 179 | +Sum of all dice: 17 |
| 180 | +``` |
| 181 | + |
| 182 | +To learn more about other tensor operations, visit the [PyTorch Tensor Operations](https://www.codecademy.com/resources/docs/pytorch/tensor-operations) documentation. |
0 commit comments