3-exercises

文章介绍了如何在PyTorch中创建张量并转换其形状。view函数用于改变张量的视图而不复制数据,共享相同的存储。修改通过view创建的张量会影响到原始张量。同时,详细解释了张量的size(形状)、offset(存储偏移)和stride(步长)属性,以及切片操作对内存地址的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

解:
(1)Create a tensor a from list(range(9)). Predict and then check the size, offset, and stride.

创建列表a

在这里插入图片描述
将其转化为张量

在这里插入图片描述

a.size:The size (or shape, in NumPy parlance) is a tuple indicating how many elements across each dimension the tensor represents.

在这里插入图片描述

a.offset:The storage offset is the index in the storage corresponding to the first element in the tensor.

在这里插入图片描述

a.stride:The stride is the number of elements in the storage that need to be skipped over to obtain the next element along each dimension.

在这里插入图片描述

回顾:

在这里插入图片描述

(2)Create a new tensor using b = a.view(3, 3). What does view do? Check that a and b share the same storage.

A PyTorch Tensor instance is a view of such a Storage instance that is capable of indexing into that storage using an offset and per-dimension strides.

在这里插入图片描述

a.storage()与b.storage()均为

在这里插入图片描述

id(a.storage())==id(b.storage())

在这里插入图片描述

因此对b的修改也会影响a
例如:
在这里插入图片描述
(下文中a和b的值不修改,仍为0~8)

回顾:

在这里插入图片描述

(3)Create a tensor c = b[1:,1:]. Predict and then check the size, offset, and stride.

c取第1行及以后得行,和第1列及以后得列

在这里插入图片描述

c.size

在这里插入图片描述

c.storage()

在这里插入图片描述

c.offset
c的第一个元素4存储在内存地址4的位置

在这里插入图片描述

c.stride
因此从4到7需要3
从4到5需要1

在这里插入图片描述

注:
切片可以看成是指向内存地址的指针,对c的修改也会影响b

在这里插入图片描述
2.
在这里插入图片描述

解:
在这里插入图片描述
在这里插入图片描述

若出现报错可尝试将a整型改为浮点型,再进行数学运算

在这里插入图片描述

cos官网
sqrt官网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡__卡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值