资源经验分享pytorch torch.expand和torch.repeat的区别

pytorch torch.expand和torch.repeat的区别

2019-11-05 | |  97 |   0

原标题:pytorch torch.expand和torch.repeat的区别

原文来自:CSDN      原文链接:https://blog.csdn.net/qq_36268040/article/details/102884744


1.torch.expand
  函数返回张量在某一个维度扩展之后的张量,就是将张量广播到新形状。函数对返回的张量不会分配新内存,即在原始张量上返回只读视图,返回的张量内存是不连续的。类似于numpy中的broadcast_to函数的作用。如果希望张量内存连续,可以调用contiguous函数。
例子:

import torch

x = torch.tensor([1, 2, 3, 4])
xnew = x.expand(2, 4)
print(xnew)

输出:

tensor([[1, 2, 3, 4],
        [1, 2, 3, 4]])

2.torch.repeat
  torch.repeat用法类似np.tile,就是将原矩阵横向、纵向地复制。与torch.expand不同的是torch.repeat返回的张量在内存中是连续的。
例子1:
将张量横向的复制

import torch

x = torch.tensor([1, 2, 3])
xnew = x.repeat(1,3)
print(xnew)

输出:

tensor([[1, 2, 3, 1, 2, 3, 1, 2, 3]])

例子2:
将张量纵向的复制

import torch

x = torch.tensor([1, 2, 3])
xnew = x.repeat(3,1)
print(xnew)

输出:

tensor([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]])

免责声明:本文来自互联网新闻客户端自媒体,不代表本网的观点和立场。

合作及投稿邮箱:E-mail:editor@tusaishared.com

上一篇:Python爬虫违法吗?如何判断爬虫采集内容是否违法?

下一篇:python后端开发学习重点

用户评价
全部评价

热门资源

  • Python 爬虫(二)...

    所谓爬虫就是模拟客户端发送网络请求,获取网络响...

  • TensorFlow从1到2...

    原文第四篇中,我们介绍了官方的入门案例MNIST,功...

  • TensorFlow从1到2...

    “回归”这个词,既是Regression算法的名称,也代表...

  • 机器学习中的熵、...

    熵 (entropy) 这一词最初来源于热力学。1948年,克...

  • TensorFlow2.0(10...

    前面的博客中我们说过,在加载数据和预处理数据时...