[英]Pytorch: Extract value from tensor if it's a tensor
I have a variable initialized at eg var = 0, the algorithm changes this variable to a tensor type Int if some conditions are met, otherwise it will stay at zero.我有一个变量初始化为例如 var = 0,如果满足某些条件,算法会将此变量更改为张量类型 Int,否则它将保持为零。 I want to just print the variable without the tensor wrapping, however, if I use:
我只想打印没有张量包装的变量,但是,如果我使用:
var = 0
if random.uniform(0, 1) < 0.5:
var = torch.IntTensor(1)
print (f' var: {var.item()}')
It will throw an error that 'var' doesn't have function item() when the if condition is > 0.5 as it's just a zero.当 if 条件 > 0.5 因为它只是一个零时,它将抛出一个错误,'var' 没有 function item()。 Is there a way to print the 'var' variable without any checking conditions?
有没有办法在没有任何检查条件的情况下打印“var”变量?
I'm looking to do this without an else statement and with the print function outside the condition.我希望在没有 else 语句的情况下执行此操作,并且在条件之外打印 function 。
Does a PyTorch function, similar to item(), that can automatically detect whether its a tensor or not and deal with the condition exist? PyTorch function,类似于 item(),是否可以自动检测其是否为张量并处理条件存在?
A very obvious solution would be to use try
一个非常明显的解决方案是使用
try
as in如在
var = 0
if random.uniform(0, 1) < 0.5:
try:
var = torch.IntTensor(1)
except:
pass # Or Throw and exception or whatever your use case migth be
print (f' var: {var.item()}')
This will try to run the IntTensor function, which if it gives an exception, it will handle.这将尝试运行 IntTensor function,如果它给出异常,它将处理。
You can also get the type of a variable by running type( variable ) which in case of 0
will return <class 'int'>, so you can add that to the if as well.您还可以通过运行 type( variable ) 来获取变量的类型,如果为
0
,则返回 <class 'int'>,因此您也可以将其添加到 if 中。
Python has a builtin method to get the type of a variable type()
Python 有一个内置方法来获取变量的
type()
type( 0 ) == int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.