Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从N维张量中过滤出NaN值_Python_Python 3.x_Pytorch_Filtering_Nan - Fatal编程技术网

Python 从N维张量中过滤出NaN值

Python 从N维张量中过滤出NaN值,python,python-3.x,pytorch,filtering,nan,Python,Python 3.x,Pytorch,Filtering,Nan,这个问题很相似。不同之处在于,我想将相同的概念应用于2维或更高维的张量 我有一个张量,看起来像这样: 导入火炬 张量( [[1, 1, 1, 1, 1], [浮点('nan')、浮点('nan')、浮点('nan')、浮点('nan')、浮点('nan')], [2, 2, 2, 2, 2]] ) >tensor.shape >>> [3, 5] 我想找到最具python/PyTorch风格的方法来过滤(删除)张量的行,这些行是nan。通过沿第一个轴(0th轴)过滤这个tensor,我想得到

这个问题很相似。不同之处在于,我想将相同的概念应用于2维或更高维的张量

我有一个张量,看起来像这样:

导入火炬
张量(
[[1, 1, 1, 1, 1],
[浮点('nan')、浮点('nan')、浮点('nan')、浮点('nan')、浮点('nan')],
[2, 2, 2, 2, 2]]
)
>tensor.shape
>>> [3, 5]
我想找到最具python/PyTorch风格的方法来过滤(删除)张量的行,这些行是
nan
。通过沿第一个轴(
0
th轴)过滤这个
tensor
,我想得到一个
filtered\u tensor
,它看起来像这样:

打印(过滤张量) >>>火炬张量( [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2]] ) >>>滤波张量形状 >>> [2, 5] 使用PyTorch的
isnan()
any()
使用获得的布尔掩码对
张量的行进行切片,如下所示:

filtered_tensor = tensor[~torch.any(tensor.isnan(),dim=1)]
请注意,这将删除其中包含
nan
值的任何行。如果只想删除所有值均为
nan
的行,请将
torch.any
替换为
torch.all

对于N维张量,您可以仅展平除第一个dim之外的所有dim,并应用与上面相同的步骤:

#Flatten:
shape = tensor.shape
tensor_reshaped = tensor.reshape(shape[0],-1)
#Drop all rows containing any nan:
tensor_reshaped = tensor_reshaped[~torch.any(tensor_reshaped.isnan(),dim=1)]
#Reshape back:
tensor = tensor_reshaped.reshape(tensor_reshaped.shape[0],*shape[1:])

美丽的。这正是我想要的。我应该检查一下
torch.any()
是否有
dim
参数。展示如何在展平的同时做同样的事情的额外点数!我接受这个答案,但你有一个小小的错误
Tensor
s没有
t.isnan()
函数,它只是一个顶级
torch.isnan(t)
函数。如果你不介意的话,请改变一下,我会接受你的回答:D.A
Tensor
有一个
isnan
方法,请访问。这就是代码完美工作的原因。你是对的,它确实在后台调用了
torch.isnan
。你是对的!我使用的是PyTorch的旧版本。再次感谢!我已经接受了答案,N维码对我不起作用;从
tensor=torch.arange(600,dtype=torch.float32)开始,重塑(1,3,20,10)
然后
tensor[0,2,0,0]=float('nan')
,结果是形状(0,3,20,10)