I want to create a binary tensor with 0 and 1s only, but the number of 1s should be n%.
I am using this code, but it takes 7+ seconds and has 19926MB of memory.
Is there any faster way to do that?
import torch
import time
start_time = time.time()
def create_random_binary_tensor(shape, percentage, device):
size = shape[0] * shape[1]
num_ones = int(size * (percentage / 100.0))
# Create a tensor filled with zeros
tensor = torch.zeros(size, dtype=torch.float32, device=device)
# Set random indices to ones until the desired number of ones is reached
indices = torch.randperm(size, device=device)[:num_ones]
tensor[indices] = 1
# Reshape the tensor to the desired shape
tensor = tensor.view(shape)
return tensor
# Set the shape and percentage of ones
shape = (19000, 19000)
percentage = 0.5
# Check if CUDA is available and use it if possible
device = torch.device("cuda:2" if torch.cuda.is_available() else "cpu")
# Create the random binary tensor
tensor = create_random_binary_tensor(shape, percentage, device)
# Print the tensor
execution_time = time.time() - start_time
print("Execution Time: {:.4f} seconds".format(execution_time))
This snippet should take less on the ground that it does fewer operations.
As D increases, the mean approaches p.