vs做网站怎样加数据库,旅游网站建设的组织性,福州企业网站建设专业服务,现在做什么网站好在Pytorch中#xff0c;reshape是Tensor的一个重要方法#xff0c;它与Numpy中的reshape类似#xff0c;用于返回一个改变了形状但数据和数据顺序和原来一致的新Tensor对象。注意#xff1a;此时返回的数据对象并不一定是新的#xff0c;这取决于应用此方法的Tensor是否是… 在Pytorch中reshape是Tensor的一个重要方法它与Numpy中的reshape类似用于返回一个改变了形状但数据和数据顺序和原来一致的新Tensor对象。注意此时返回的数据对象并不一定是新的这取决于应用此方法的Tensor是否是连续的。 reshape方法的语法如下所示
Tensor.reshape(*shape) → Tensor
shape (tuple of ints or int...) - the desired shape reshape的用法如下所示
import torch
# 创建一个张量
x torch.randn(3, 4)
tensor([[ 0.1961, -0.9038, 0.9196, -1.1851],[ 1.1321, 0.3153, 0.3485, 0.7977],[-0.5279, 0.2062, -0.4224, -0.3993]])# 使用reshape方法将其重新塑造为2行6列的形状
y x.reshape(2, 6)
y x.reshape((2,6)) #两种形式均可y x.reshape([2,6])也可
tensor([[ 0.1961, -0.9038, 0.9196, -1.1851, 1.1321, 0.3153],[ 0.3485, 0.7977, -0.5279, 0.2062, -0.4224, -0.3993]]) 可以看到给出的参数既可以是多个整数其中每个整数代表一个维度的大小而整数的数量代表维度的数量也可以是一个元组或是列表其中每个元素代表一个维度的大小而元素数量代表维度的数量。而且reshape不改变Tensor中数据的排列顺序指的是从上到下从左到右遍历的顺序只改变形状这也就对reshape各维度大小的乘积有要求要与原Tensor一致。在上例中即3*42*6。 另外reshape还有一个trick即某一维的实参可以是-1此时会自动根据原Tensor大小和给出的其他维度参数的大小推断出这一维度的大小举例如下
import torch
# 创建一个张量
x torch.randn(3, 4)
tensor([[ 0.1961, -0.9038, 0.9196, -1.1851],[ 1.1321, 0.3153, 0.3485, 0.7977],[-0.5279, 0.2062, -0.4224, -0.3993]])# 使用reshape方法将其重新塑造为6行n列的形状n为自动推断出的值
y x.reshape(6, -1)
tensor([[ 0.1961, -0.9038],[ 0.9196, -1.1851],[ 1.1321, 0.3153],[ 0.3485, 0.7977],[-0.5279, 0.2062],[-0.4224, -0.3993]])# 使用reshape方法将其重新塑造为(2,2,n)的形状n为自动推断出的值
y x.reshape(2, 2, -1)
tensor([[[ 0.1961, -0.9038, 0.9196],[-1.1851, 1.1321, 0.3153]],[[ 0.3485, 0.7977, -0.5279],[ 0.2062, -0.4224, -0.3993]]])# 不能在两个维度都指定-1这时无法推断出唯一结果
y x.reshape(2, -1, -1)
Traceback (most recent call last):File stdin, line 1, in module
RuntimeError: only one dimension can be inferred 除此之外还可以使用torch.reshape()函数这与使用reshape方式效果一致torch.reshape()的语法如下所示。
torch.reshape(input, shape) → Tensor
input (Tensor) – the tensor to be reshaped
shape (tuple of python:int) – the new shapeimport torch
# 创建一个张量
x torch.randn(3, 4)
tensor([[ 0.1961, -0.9038, 0.9196, -1.1851],[ 1.1321, 0.3153, 0.3485, 0.7977],[-0.5279, 0.2062, -0.4224, -0.3993]])# 使用reshape函数将其重新塑造为6行n列的形状n为自动推断出的值
y torch.reshape(x, (6, -1))
tensor([[ 0.1961, -0.9038],[ 0.9196, -1.1851],[ 1.1321, 0.3153],[ 0.3485, 0.7977],[-0.5279, 0.2062],[-0.4224, -0.3993]])