3-exercises

在这里插入图片描述

解:
(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官网

猜你喜欢

转载自blog.csdn.net/weixin_45825865/article/details/131621026