首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Deep Learning with PyTorch: A 60 Minute Blitz > Tensors

Deep Learning with PyTorch: A 60 Minute Blitz > Tensors

原创
作者头像
望天
发布于 2024-06-06 13:36:31
发布于 2024-06-06 13:36:31
20300
代码可运行
举报
文章被收录于专栏:along的开发之旅along的开发之旅
运行总次数:0
代码可运行

主要是PyTorch官方原文,增加了Ascend npu的示例和实战。

Tensors

Tensors are a specialized data structure that are very similar to arrays and matrices. In PyTorch, we use tensors to encode the inputs and outputs of a model, as well as the model’s parameters.

Tensors are similar to NumPy’s ndarrays, except that tensors can run on GPUs or other specialized hardware to accelerate computing. If you’re familiar with ndarrays, you’ll be right at home with the Tensor API. If not, follow along in this quick API walkthrough.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
import torch
import numpy as np

Tensor Initialization

Tensors can be initialized in various ways. Take a look at the following examples:

Directly from data

Tensors can be created directly from data. The data type is automatically inferred.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

From a NumPy array

Tensors can be created from NumPy arrays (and vice versa - see Bridge with NumPy).

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
np_array = np.array(data)
x_np = torch.from_numpy(np_array)

From another tensor:

The new tensor retains the properties (shape, datatype) of the argument tensor, unless explicitly overridden.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

Ones Tensor: tensor([1, 1, 1, 1])

Random Tensor: tensor([0.8823, 0.9150, 0.3829, 0.9593])

With random or constant values:

shape is a tuple of tensor dimensions. In the functions below, it determines the dimensionality of the output tensor.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
shape = (2, 3, )
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
代码语言:log
AI代码解释
复制
Random Tensor:
 tensor([[0.3904, 0.6009, 0.2566],
        [0.7936, 0.9408, 0.1332]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

Tensor Attributes

Tensor attributes describe their shape, datatype, and the device on which they are stored.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
tensor = torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

Tensor Operations

Over 100 tensor operations, including transposing, indexing, slicing, mathematical operations, linear algebra, random sampling, and more are comprehensively described here.

Each of them can be run on the GPU (at typically higher speeds than on a CPU). If you’re using Colab, allocate a GPU by going to Edit > Notebook Settings.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')
  print(f"Device tensor is stored on: {tensor.device}")

Device tensor is stored on: cuda:0

Try out some of the operations from the list. If you’re familiar with the NumPy API, you’ll find the Tensor API a breeze to use.

Ascend NPU

如果在Ascend NPU上使用,简单可以使用from torch_npu.contrib import transfer_to_npu自动迁移

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
>>> torch.cuda.is_available()
False
>>> import torch_npu
>>> from torch_npu.contrib import transfer_to_npu
>>> torch.cuda.is_available()
True
>>> tensor = tensor.to('cuda')
>>> print(f"Device tensor is stored on: {tensor.device}")
Device tensor is stored on: npu:0

可以看到,当调用了transfer_to_npu后,cuda相关的调用被自动转到npu了,相关的判断也通过了。

或者直接使用npu相关的API,例如:

代码语言:shell
AI代码解释
复制
>>> import torch_npu
>>> torch.npu.is_available()
True
>>> tensor = tensor.npu()
>>> print(f"Device tensor is stored on: {tensor.device}")
Device tensor is stored on: npu:0

Standard numpy-like indexing and slicing:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)
代码语言:out
AI代码解释
复制
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

Joining tensors

You can use torch.cat to concatenate a sequence of tensors along a given dimension. See also torch.stack, another tensor joining op that is subtly different from torch.cat.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
代码语言:out
AI代码解释
复制
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

torch.cattorch.stack 的dim都稍显复杂,可以通过官网case来了解。

torch.cat dim=0时,就是说在torch.shape的第0维度上进行cat连接,所以也就是;dim=1时,就是在torch.shape的第1维度上进行cat拼接,所以也就是。当维度更高时,可能就不好类比长宽高了,这时候根据torch.shape的维度来判断就好。

代码语言:shell
AI代码解释
复制
>>> x = torch.randn(2, 3)
>>> x
tensor([[ 0.0679, -0.3655, -1.5670],
        [-0.6854,  0.1267, -0.8296]])
>>> x0 = torch.cat((x, x, x), 0)
>>> x0.shape
torch.Size([6, 3])
>>> x0
tensor([[ 0.0679, -0.3655, -1.5670],
        [-0.6854,  0.1267, -0.8296],
        [ 0.0679, -0.3655, -1.5670],
        [-0.6854,  0.1267, -0.8296],
        [ 0.0679, -0.3655, -1.5670],
        [-0.6854,  0.1267, -0.8296]])        

>>> x1 = torch.cat((x, x, x), 1)
>>> x1.shape
torch.Size([2, 9])
>>> x1
tensor([[ 0.0679, -0.3655, -1.5670,  0.0679, -0.3655, -1.5670,  0.0679, -0.3655,
         -1.5670],
        [-0.6854,  0.1267, -0.8296, -0.6854,  0.1267, -0.8296, -0.6854,  0.1267,
         -0.8296]])
代码语言:shell
AI代码解释
复制
>>> x_0_t
tensor([[1.1100, 1.1200, 1.1300, 1.1400],
        [1.2100, 1.2200, 1.2300, 1.2400],
        [1.3100, 1.3200, 1.3300, 1.3400]])

>>> x_1_t
tensor([[2.1100, 2.1200, 2.1300, 2.1400],
        [2.2100, 2.2200, 2.2300, 2.2400],
        [2.3100, 2.3200, 2.3300, 2.3400]])

>>> y0 = torch.stack((x_0_t, x_1_t),  dim=0)
>>> y0.shape
torch.Size([2, 3, 4])
>>> y0
tensor([[[1.1100, 1.1200, 1.1300, 1.1400],
         [1.2100, 1.2200, 1.2300, 1.2400],
         [1.3100, 1.3200, 1.3300, 1.3400]],

        [[2.1100, 2.1200, 2.1300, 2.1400],
         [2.2100, 2.2200, 2.2300, 2.2400],
         [2.3100, 2.3200, 2.3300, 2.3400]]])

>>> y1 = torch.stack((x_0_t, x_1_t),  dim=1)
>>> y1.shape
torch.Size([3, 2, 4])
>>> y1
tensor([[[1.1100, 1.1200, 1.1300, 1.1400],
         [2.1100, 2.1200, 2.1300, 2.1400]],

        [[1.2100, 1.2200, 1.2300, 1.2400],
         [2.2100, 2.2200, 2.2300, 2.2400]],

        [[1.3100, 1.3200, 1.3300, 1.3400],
         [2.3100, 2.3200, 2.3300, 2.3400]]])
>>> y2 = torch.stack((x_0_t, x_1_t),  dim=2)
>>> y2.shape
torch.Size([3, 4, 2])
>>> y2
tensor([[[1.1100, 2.1100],
         [1.1200, 2.1200],
         [1.1300, 2.1300],
         [1.1400, 2.1400]],

        [[1.2100, 2.2100],
         [1.2200, 2.2200],
         [1.2300, 2.2300],
         [1.2400, 2.2400]],

        [[1.3100, 2.3100],
         [1.3200, 2.3200],
         [1.3300, 2.3300],
         [1.3400, 2.3400]]])

Multiplying tensors

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
tensor = torch.ones(4, 4)
tensor[:,1] = 0
print(tensor)
# This computes the element-wise product
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# Alternative syntax:
print(f"tensor * tensor \n {tensor * tensor}")
代码语言:out
AI代码解释
复制
tensor.mul(tensor)
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor * tensor
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

This computes the matrix multiplication between two tensors

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")
代码语言:out
AI代码解释
复制
tensor.matmul(tensor.T)
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

tensor @ tensor.T
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])

In-place operations

Operations that have a suffix are in-place. For example: x.copy(y), x.t_(), will change x.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
print(tensor, "\n")
tensor.add_(5)
print(tensor)
代码语言:out
AI代码解释
复制
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

In-place operations save some memory, but can be problematic when computing derivatives because of an immediate loss of history. Hence, their use is discouraged.

Bridge with NumPy

Tensors on the CPU and NumPy arrays can share their underlying memory locations, and changing one will change the other.

Tensor to NumPy array

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
代码语言:out
AI代码解释
复制
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

A change in the tensor reflects in the NumPy array.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
代码语言:out
AI代码解释
复制
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

但是GPU上的数据,修改是不会联动的。

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
>>> t = torch.ones(5).npu()
>>> t
tensor([1., 1., 1., 1., 1.], device='npu:0')
>>> n = t.cpu().numpy()
>>> n
array([1., 1., 1., 1., 1.], dtype=float32)
>>> t.add_(1)
tensor([2., 2., 2., 2., 2.], device='npu:0')
>>> t
tensor([2., 2., 2., 2., 2.], device='npu:0')
>>> n
array([1., 1., 1., 1., 1.], dtype=float32)

NumPy array to Tensor

代码语言:out
AI代码解释
复制
n = np.ones(5)
t = torch.from_numpy(n)

Changes in the NumPy array reflects in the tensor.

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
代码语言:out
AI代码解释
复制
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

同样不会影响到GPU上的数据,因为GPU的数据和CPU是分离的,需要先从GPUcopy到CPU上。

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
>>> import numpy as np
>>> n = np.ones(5)
>>> t = torch.from_numpy(n).npu()
>>> n
array([1., 1., 1., 1., 1.])
>>> t
tensor([1., 1., 1., 1., 1.], device='npu:0', dtype=torch.float64)
>>> np.add(n, 1, out=n)
array([2., 2., 2., 2., 2.])
>>> n
array([2., 2., 2., 2., 2.])
>>> t
tensor([1., 1., 1., 1., 1.], device='npu:0', dtype=torch.float64)

主要翻译自

https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
实用 | 盘点几种解决 Chrome 占用内存大的实用方案!(文末送书)
Google Chrome 是笔者平时工作使用最多的浏览器,随着 Tab 窗口及插件的增多,内存占用几乎令人崩溃,甚者会出现页面卡死的状态
AirPython
2021/12/09
11.4K0
实用 | 盘点几种解决 Chrome 占用内存大的实用方案!(文末送书)
浏览器插件:一款解决谷歌浏览器吃内存神器插件,你值得试一试!
Chrome浏览器是大部分开发者必备的浏览器,它的主要有点有便于调试、启动快、无广告。但是谷歌浏览器也有自己的缺点,Chrome浏览器对系统内存的占用太大了,每打开一个页面都会占用系统内存。如果你的浏览器一下子打开几十个网页,不一会儿你就会发现Chrome浏览器已经将系统大部分内存给占用了!
小明互联网技术分享社区
2021/08/13
1.6K0
​现代浏览器内部揭秘(第一部分)
这一博客系列由四部分组成,将从高级体系结构到渲染流程的细节来窥探 Chrome 浏览器的内部。如果你曾对浏览器是如何将代码转化为具有功能的网站,或者你并不确定为何建议使用某一技术来提升性能,那么本系列就是为你准备的。
ConardLi
2020/07/02
7590
​现代浏览器内部揭秘(第一部分)
用好这 42 款 Chrome 插件,每年轻松省出一个年假(附下载)
相信很多人都在使用 Chrome 浏览器,其流畅的浏览体验得到了不少用户偏爱,但流畅只是一方面, Chrome 最大的优势还是其支持众多强大好用的扩展程序(Extensions)。
数据派THU
2019/09/17
19.7K0
用好这 42 款 Chrome 插件,每年轻松省出一个年假(附下载)
idea和谷歌浏览器占用内存过高的处理方法
最近家里电脑打开浏览器页面过多,内存占用严重,而且idea启动一个项目就会把内存占满,最后查了一些资料顺利解决了这个问题。这里记录一下,方便后面直接使用。
jiankang666
2022/05/12
9.7K0
idea和谷歌浏览器占用内存过高的处理方法
几款好用超赞的Google Chrome插件
Github一个不好的地方就是代码是不能相互跳转的,所以阅读起来很累,如果我要引入一个库,那么就必须clone下来然后通过idea打开才行。这样的流程对于库的前期调研来说成本很高,所以我希望利用SourceGraph让在线阅读代码的体验提升一个量级,就像在强大的IDE中一样。
小小詹同学
2019/07/19
1.3K0
Chrome终于上线这项重磅功能,中国用户苦等多年!
但在Chrome上,标签页增多后,每个标签的宽度会自动缩小,用户无法阅读标题,甚至无法查看网站小图标。
龙哥
2020/10/27
2.8K0
Chrome终于上线这项重磅功能,中国用户苦等多年!
8 款好用超赞的 Google Chrome 插件,一直用,一直爽
Github一个不好的地方就是代码是不能相互跳转的,所以阅读起来很累,如果我要引入一个库,那么就必须clone下来然后通过idea打开才行。这样的流程对于库的前期调研来说成本很高,所以我希望利用SourceGraph让在线阅读代码的体验提升一个量级,就像在强大的IDE中一样。
芋道源码
2019/07/30
8080
【Chrome】谷歌浏览器常用的flags配置与插件介绍
就在最近,7月24日,谷歌浏览器Chrome终于迎来了最近最大的一次更新,Chrome68。身为软件颜控的我对隔壁Edge随着更新越来越好看的界面已经眼红很久了,甚至几次想要抛弃Chrome换成Edge,还好在这次更新中 ,Chrome挽回了我的信任:可以丢掉那祖传的落后界面设计,全面换上好看的质感设计(Material Design)了(笑
ZifengHuang
2020/07/29
15.4K1
【Chrome】谷歌浏览器常用的flags配置与插件介绍
极力推荐的谷歌浏览器插件
今天有幸请教了 记得诚、小麦大叔、SoWhat、程序猿学社 等十位博客专家,给大家推荐一些谷歌浏览器插件,让你的谷歌浏览器更实用,成为真正的生活办公小助手!
Twcat_tree
2022/11/30
3.3K0
极力推荐的谷歌浏览器插件
请停用以开发者模式运行的扩展程序?搞定谷歌浏览器插件弹窗
为什么我一直推荐使用谷歌浏览器呢,某些浏览器会自作主张封杀某些域名,还经常弹各种广告,当然更主要的是方便我使用谷歌搜索。
苏生不惑
2020/06/01
1.9K1
请停用以开发者模式运行的扩展程序?搞定谷歌浏览器插件弹窗
有哪些实用且堪称神器的Chrome插件?吐血推荐!!!
相信很多人都在使用 Chrome 浏览器,其流畅的浏览体验得到了不少用户的偏爱,但流畅只是一方面, Chrome 最大的优势还是其支持众多强大好用的扩展程序(Extensions)。 最近为了更好的利用谷歌浏览器,我整理了一些常用的谷歌插件,分享给大家。
谭庆波
2018/08/10
9.6K0
有哪些实用且堪称神器的Chrome插件?吐血推荐!!!
超好用的谷歌浏览器、Sublime Text、Phpstorm、油猴插件合集
一、谷歌浏览器插件 二、Sublime Text 插件 三、Phpstorm 插件 四、油猴脚本 4.1 脚本网站 4.2 自用的脚本 五、相关链接 分享一些超好用的谷歌浏览器、Sublime Te
guanguans
2018/05/09
5.3K0
超好用的谷歌浏览器、Sublime Text、Phpstorm、油猴插件合集
你的浏览器,何必是浏览器
工欲善其事,必先利其器,作为大学生或者从业人员,如果能熟练地使用各种工具来提高自己的工作学习效率必然是一件好事!!!
小孙同学
2022/01/17
3.2K0
你的浏览器,何必是浏览器
Chrome快捷键整理
Ctrl+N 打开新窗口 Ctrl+T 打开新标签页 Ctrl+Shift+N 在隐身模式下打开新窗口 Ctrl+O,然后选择文件 在谷歌浏览器中打开计算机上的文件 按住 Ctrl 键,然后点击链接 从后台在新标签页中打开链接,但您仍停留在当前标签页中 按住 Ctrl+Shift 键,然后点击链接 在新标签页中打开链接,同时切换到新打开的标签页 按住 Shift 键,然后点击链接 在新窗口中打开链接 Alt+F4 关闭当前窗口 Ctrl+Shift+T 重新打开上次关闭的标签页。谷歌浏览器可记住最近关闭的 10 个标签页。 将链接拖动到标签页内 在指定标签页中打开链接 将链接拖动到两个标签页之间 在标签页横条的指定位置建立一个新标签页,在该标签页中打开链接 Ctrl+1 到 Ctrl+8 切换到指定位置编号的标签页。您按下的数字代表标签页横条上的相应标签位置。 Ctrl+9 切换到最后一个标签页 Ctrl+Tab 或 Ctrl+PgDown 切换到下一个标签页 Ctrl+Shift+Tab 或 Ctrl+PgUp 切换到上一个标签页 Ctrl+W 或 Ctrl+F4 关闭当前标签页或弹出式窗口 Alt+Home 打开主页
csxiaoyao
2019/02/18
6.9K0
精选10款谷歌浏览器插件武装你的浏览器
最近看到的一段话很有感触,日复一日的低效率工作只会消磨你的热情,而巨大的时间成本会让你错失很多机会。
王小婷
2020/10/23
6940
Google Chrome 插件,一直用,一直爽
C:\Users\Administrator\AppData\Local\Google\Chrome\Application\User Data\Default\Extensions
OwenZhang
2021/12/08
4580
Google Chrome 插件,一直用,一直爽
关于谷歌浏览器无法加载安全控件设置说明
当你安装完安全控件后谷歌无法加载,那是从Chrome 42+以后开始就不再支持安全控件了,使用Chrome浏览器正常安装安全控件后,重启浏览器进入登录页面,安全登录框仍然不能输入密码,提示"请点此安装控件"
小陈先生
2019/08/20
19.6K1
关于谷歌浏览器无法加载安全控件设置说明
我为NET狂群福利:逆天常用的一些谷歌浏览器插件
逆天书库:http://www.cnblogs.com/dunitian/p/5734677.html 常用工具:http://www.cnblogs.com/dunitian/p/5640147.h
逸鹏
2018/04/11
1.8K0
我为NET狂群福利:逆天常用的一些谷歌浏览器插件
程序猿的 Chrome 浏览器插件推荐
这是一款标签页插件,我使用 Chrome 浏览器的时候就开始使用这个插件,注册后可以使用 Pro 版本,它具有多种搜索引擎设计及类似书签页的功能,非常的实用,可以看一下我之前写的介绍 Infinity 插件的文章:
Meng小羽
2020/03/18
1.3K0
推荐阅读
相关推荐
实用 | 盘点几种解决 Chrome 占用内存大的实用方案!(文末送书)
更多 >
LV.0
这个人很懒,什么都没有留下~
目录
  • Tensors
    • Tensor Initialization
      • Directly from data
      • From a NumPy array
      • From another tensor:
      • With random or constant values:
    • Tensor Attributes
    • Tensor Operations
      • Ascend NPU
      • Standard numpy-like indexing and slicing:
      • Joining tensors
      • Multiplying tensors
      • In-place operations
    • Bridge with NumPy
      • Tensor to NumPy array
      • NumPy array to Tensor
    • 主要翻译自
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档