对于形状为 (15,10) 的布尔张量,我想沿轴 0 执行 bitwise_or
,以便生成的张量的形状为 10。torch.bitwise_or
不支持此操作。>
我知道它可以在 numpy
中使用 np.bitwise_or.reduce(x,axis=0)
完成。我在火炬中没有找到类似的东西。如何减少火炬张量?
答案 0 :(得分:0)
嗨,如果你查看reduce函数的文档字符串,你就会发现这里的问题,它本质上只是一个从0添加自己的for循环
# ufunc docstring
# op.identiy is 0
r = op.identity # op = ufunc
for i in range(len(A)):
r = op(r, A[i])
return r
为了解决和解决您的问题
import numpy as np
import torch
bool_arr = np.random.randint(0, 2, (15, 10), dtype=np.bool) # create a bool arr
tensor_bool_arr = torch.tensor(bool_arr) # Create torch version
output_np = np.bitwise_or.reduce(bool_arr, axis=0)
# array([ True, True, True, True, True, True, True, True, True,
True])
# Create a pytorch equivalent of bitwise reduce
r = torch.tensor(0)
for i in range(len(tensor_bool_arr)):
r = torch.bitwise_or(r, tensor_bool_arr[i])
torch_output = r.type(torch.bool)
# tensor([True, True, True, True, True, True, True, True, True, True])
assert torch_output.shape[0] == np_output.shape[0]