0

I have a pytorch tensor and want to mask part of it and put the masked section in an if statement. This is my tensor:

import torch
all_data = torch.tensor([[1.1, 0.4],
                         [1.7, 2.7],
                         [0.9, 0.7],
                         [0.9, 3.5],
                         [0.1, 0.5]])
if [(all_data[:,0]<1) & (all_data[:,1]<1)]: # I have two conditions
    print ('Masked')
else:
    print('Not_Masked')

this piece of code is not working correctly because it prints the whole tensor while I want to check the tensor row by row: the first and second rows do not fulfill the condition and I want to print Not_Masked. The third row fulfills and I wan to have Masked printed. It should go so on and so forth. I appreciate any help.

Ali_d
  • 1,089
  • 9
  • 24

1 Answers1

1

In Python, you should not place something in an if-statement unless you know how the expression evaluates in terms of truthiness. This is discussed e.g. here: https://stackoverflow.com/a/39984051/21012339

In this example, [(all_data[:,0]<1) & (all_data[:,1]<1)] is always truthy, because it is a list of non-zero length.

While I don't understand much about tensors and these conditions, hopefully the following edit shows how you can get the correct result using Python:

import torch

all_data = torch.tensor([[1.1, 0.4],
                         [1.7, 2.7],
                         [0.9, 0.7],
                         [0.9, 3.5],
                         [0.1, 0.5]])
conditionTensor = (all_data[:,0]<1) & (all_data[:,1]<1) # I have two conditions

print(conditionTensor)

for i,c in enumerate(conditionTensor):
    maskedstr = "Masked" if c else "Not_Masked"
    print(f"{i}: {maskedstr}")

enumerate is a kind of shortcut. You can view any list (and similar structure) and have both its indices and its elements at hand.

format strings are available in Python v3.6 and later. They let you embed expressions in strings.

Chr L
  • 89
  • 4