torch.where和numpy.where faster element wise operation build-in implement

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]]
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值