import torch
a=torch.randn((2,3))
print(a)
'''
tensor([[-0.4695, 0.0949, -0.7063],
[-0.2190, 0.7319, -0.6530]])
'''
b=torch.where(a>0,torch.tensor(10.),a)
print(b)
'''
tensor([[-0.4695, 10.0000, -0.7063],
[-0.2190, 10.0000, -0.6530]])
'''
'''
torch.where需要将所输入的3个参数都转换成torch.tensor类型
实现功能,对于输入的第一个参数torch.tensor进行element wise if判断
torch.where(tensor1 satisfy condition,tensor2,tensor3)
实现以下逻辑功能:
for element in tensor1:
if element satisfy condition:
tensor1[i,j]=tensor2[i,j]
else:
tensor1[i,j]=tensor3[i,j]
其中[i,j]表示element在tensor1中的索引位置下标
其实numpy中也有类似的操作
numpy where
numpy where 与 torch where的区别
两者都是三个输入参数,第一个是判断条件,第二个是符合条件的设置值,第三个是不满足条件的设置值。
区别在于,torch要将设置值全部改为Tensor类型的
https://blog.csdn.net/xijuezhu8128/article/details/86590562
'''
import numpy as np
a=np.random.randint(-10,10,(3,4))
print(a)
'''
[[ -3 8 -1 0]
[ 6 -8 3 9]
[-10 4 -9 8]]
'''
b=np.where(a>0,1,-1)
print(b)
'''
[[-1 1 -1 -1]
[ 1 -1 1 1]
[-1 1 -1 1]]
'''
torch.where和numpy.where faster element wise operation build-in implement
最新推荐文章于 2024-06-02 10:39:13 发布