英文:
How to set multi-conditions in an If statement for a pytorch 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)]: # 我有两个条件
print ('Masked')
else:
print('Not_Masked')
希望这有所帮助。
英文:
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.
答案1
得分: 1
在Python中,除非你知道表达式在truthiness
方面的评估,否则不应将内容放在if
语句中。这在此处讨论过:https://stackoverflow.com/a/39984051/21012339
在这个例子中,[(all_data[:,0]<1) & (all_data[:,1]<1)]
始终是truthy
,因为它是一个非零长度的列表。
虽然我对张量和这些条件不太了解,但希望以下编辑能展示如何使用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) # 我有两个条件
print(conditionTensor)
for i,c in enumerate(conditionTensor):
maskedstr = "Masked" if c else "Not_Masked"
print(f"{i}: {maskedstr}")
enumerate
是一种快捷方式。你可以查看任何列表(和类似的结构),并在手边有它的索引和元素。
format strings
在Python v3.6及更高版本可用。它们允许你在字符串中嵌入表达式。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论