Element-wise operation
Element-wise 也称为 Componet-wise 或者 Point-wise
这种操作在匹配的元素间起作用,“匹配”的含义是:
- 张量有同样的shape
- 元素的“位置”相同
t1 = torch.tensor([
[1, 2],
[3, 4]
])
t2 = torch.tensor([
[9, 8],
[7, 6]
])
#t1[0][0]与t2[0][0]是一对corresponding elements
####例:element-wise 加法
t3 = t1 + t2
然而,以下情况下,shape不匹配,也能进行element-wise操作,
t1 + 2 -> tensor([
[3, 4],
[5, 6]
])
这是因为**广播机制(Broadcast)**的存在
t1 + 2 -> t1 + torch.tensor(np.broadcast_to(2, t1.shape))
t.abs(),对所有元素求绝对值
t.sqrt(),对所有元素求平方幂
t.neg(),对所有元素求相反数
叠加使用的例子:t.neg().abs
Element-wise comparison
以下函数中均可用Broadcast思想来实现。
eq(),判断相等
判断元素与参数是否相等,相等处返回1,其他为0。
以下其他函数逻辑类似。
t2.eq(9) ->tensor([
[1, 0],
[0, 0]
])