Element-wise operations

An element-wise operation operates on corresponding elements between tensors.

Two tensors must have the same shape in order to perform element-wise operations on them.

Suppose we have the following two tensors(Both of these tensors are rank-2 tensors with a shape of 2 \(\times\) 2):

t1 = torch.tensor([
[1, 2],
[3, 4]
], dtype=torch.float32) t2 = torch.tensor([
[9, 8],
[7, 6]
], dtype=torch.float32)

The elements of the first axis are arrays and the elements of the second axis are numbers.

# Example of the first axis
> print(t1[0])
tensor([1., 2.]) # Example of the second axis
> print(t1[0][0])
tensor(1.)

Addition is an element-wise operation.

> t1 + t2
tensor([[10., 10.],
[10., 10.]])

In fact, all the arithmetic operations, add, subtract, multiply, and divide are element-wise operations. There are two ways we can do this:

  1. Using these symbolic operations:
> t + 2
tensor([[3., 4.],
[5., 6.]]) > t - 2
tensor([[-1., 0.],
[1., 2.]]) > t * 2
tensor([[2., 4.],
[6., 8.]]) > t / 2
tensor([[0.5000, 1.0000],
[1.5000, 2.0000]])
  1. Or equivalently, these built-in tensor methods:
> t.add(2)
tensor([[3., 4.],
[5., 6.]]) > t.sub(2)
tensor([[-1., 0.],
[1., 2.]]) > t.mul(2)
tensor([[2., 4.],
[6., 8.]]) > t.div(2)
tensor([[0.5000, 1.0000],
[1.5000, 2.0000]])

Broadcasting tensors

Broadcasting is the concept whose implementation allows us to add scalars to higher dimensional tensors.

We can see what the broadcasted scalar value looks like using the broadcast_to()Numpy function:

> np.broadcast_to(2, t.shape)
array([[2, 2],
[2, 2]])
//This means the scalar value is transformed into a rank-2 tensor just like t, and //just like that, the shapes match and the element-wise rule of having the same //shape is back in play.

Trickier example of broadcasting

t1 = torch.tensor([
[1, 1],
[1, 1]
], dtype=torch.float32) t2 = torch.tensor([2, 4], dtype=torch.float32)

Even through these two tensors have differing shapes, the element-wise operation is possible, and broadcasting is what makes the operation possible.

> np.broadcast_to(t2.numpy(), t1.shape)
array([[2., 4.],
[2., 4.]], dtype=float32) >t1 + t2
tensor([[3., 5.],
[3., 5.]])

When do we actually use broadcasting? We often need to use broadcasting when we are preprocessing our data, and especially during normalization routines.


Comparison operations are element-wise. For a given comparison operation between tensors, a new tensor of the same shape is returned with each element containing either a 0 or a 1.

> t = torch.tensor([
[0, 5, 0],
[6, 0, 7],
[0, 8, 0]
], dtype=torch.float32)

Let's check out some of the comparison operations.

> t.eq(0)
tensor([[1, 0, 1],
[0, 1, 0],
[1, 0, 1]], dtype=torch.uint8) > t.ge(0)
tensor([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=torch.uint8) > t.gt(0)
tensor([[0, 1, 0],
[1, 0, 1],
[0, 1, 0]], dtype=torch.uint8) > t.lt(0)
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=torch.uint8) > t.le(7)
tensor([[1, 1, 1],
[1, 1, 1],
[1, 0, 1]], dtype=torch.uint8)

Element-wise operations using functions

Here are some examples:

> t.abs()
tensor([[0., 5., 0.],
[6., 0., 7.],
[0., 8., 0.]]) > t.sqrt()
tensor([[0.0000, 2.2361, 0.0000],
[2.4495, 0.0000, 2.6458],
[0.0000, 2.8284, 0.0000]]) > t.neg()
tensor([[-0., -5., -0.],
[-6., -0., -7.],
[-0., -8., -0.]]) > t.neg().abs()
tensor([[0., 5., 0.],
[6., 0., 7.],
[0., 8., 0.]])

Element-wise operations的更多相关文章

  1. 向量的一种特殊乘法 element wise multiplication

    向量的一种特殊乘法 element wise multiplication 物体反射颜色的计算采用这样的模型: vec3 reflectionColor = objColor * lightColor ...

  2. [C2P1] Andrew Ng - Machine Learning

    About this Course Machine learning is the science of getting computers to act without being explicit ...

  3. TensorRT 3:更快的TensorFlow推理和Volta支持

    TensorRT 3:更快的TensorFlow推理和Volta支持 TensorRT 3: Faster TensorFlow Inference and Volta Support 英伟达Tens ...

  4. (转)A Beginner's Guide To Understanding Convolutional Neural Networks Part 2

    Adit Deshpande CS Undergrad at UCLA ('19) Blog About A Beginner's Guide To Understanding Convolution ...

  5. Understanding Convolution in Deep Learning

    Understanding Convolution in Deep Learning Convolution is probably the most important concept in dee ...

  6. Must Know Tips/Tricks in Deep Neural Networks

    Must Know Tips/Tricks in Deep Neural Networks (by Xiu-Shen Wei)   Deep Neural Networks, especially C ...

  7. [Tensorflow] Cookbook - Neural Network

    In this chapter, we'll cover the following recipes: Implementing Operational Gates Working with Gate ...

  8. [Tensorflow] Cookbook - Object Classification based on CIFAR-10

    Convolutional Neural Networks (CNNs) are responsible for the major breakthroughs in image recognitio ...

  9. Must Know Tips/Tricks in Deep Neural Networks (by Xiu-Shen Wei)

    http://lamda.nju.edu.cn/weixs/project/CNNTricks/CNNTricks.html Deep Neural Networks, especially Conv ...

  10. [转]An Intuitive Explanation of Convolutional Neural Networks

    An Intuitive Explanation of Convolutional Neural Networks https://ujjwalkarn.me/2016/08/11/intuitive ...

随机推荐

  1. bzoj4161 (k^2logn求线性递推式)

    分析: 我们可以写把转移矩阵A写出来,然后求一下它的特征多项式,经过手动计算应该是这样的p(x)=$x^k-\sum\limits_{i=1}^ka_i*x^{k-i}$ 根据Cayley-Hamil ...

  2. 51nod 1907(多项式乘法启发式合并)

    题目: 分析: 对于一个确定的生成子图,很明显是在一个连通块上走,走完了再跳到另一个连通块上,假设连通块个数为cnt,那么答案一定是$min(a_{cnt-1},a_cnt,..,a_{n-1})$ ...

  3. Java实现拖拽上传

    原文:http://www.open-open.com/code/view/1437358795584 在项目开发中由于实际需求,需要开发拖拽上传的功能,ok! 先看效果图: jsp上传前端代码: & ...

  4. 新手玩个人server(阿里云)续二

    小二班一番厮杀:那英四强诞生:大家闺秀,小家碧玉.窈窕淑女,妍姿俊俏 .不解释! ?不行! 陈冰,李嘉格,刘明湘.张碧晨.大多数的时候,仅仅要脸好看,一切都那么自热而然的顺理成章. 尽管网上骂声四起, ...

  5. socket的bind函数是不是只能绑定本地IP,不能绑定外网IP么?

    参考: https://bbs.csdn.net/topics/391024376 别瞎猜测. 所谓bind,就是指绑定本地接受端口. 指定ip,是为了分辨多ip主机. --------------- ...

  6. [wxWidgets]_[0基础]_[不常见但有用的类wxCmdLineParser]

    场景: 1. 有时候须要构造命令行字符串传递給函数调用,比方CreateProcess,假设參数是动态的,那么就得使用类似std::vector<string>加入单个參数,之后拼接为一个 ...

  7. 百度接口通过ip获取用户所在地

    /** * 百度接口      * 通过用户ip获取用户所在地      * @param userIp      * @return      */ public static String get ...

  8. Windows下安装MySQL5.6绿色版

    建议安装MySQL绿色版的,什么是绿色版的?就是免安装,下载下来的截图是这样的 在该目录下创建一个文件夹/data用于存放数据, 新建一个my.ini文件,my.ini里面最基本的配置如下,my.in ...

  9. 2016/3/26 连接数据库 网页中数据的增删改 add delete update addchuli updateChuLi test8 DBDA

    主页面 test8.php <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...

  10. NYOJ110 剑客决斗

    剑客决斗 来源:Polish Olympiad in Informatics(波兰信息学奥林匹克竞赛) 时间限制:5000 ms  |  内存限制:65535 KB 难度:5   描述 在路易十三和红 ...