创建张量:
torch.tensor(data)
: 从数据中创建张量。用列表创建,numpy创建- 维度只看[ ]
# 一维张量 一维张量是指只有一个轴的张量,没有行列之分 data_1d = [1, 2, 3] tensor_1d = torch.tensor(data_1d)
结果
tensor([1, 2, 3])
# 二维张量 data_2d = [[1, 2, 3], [4, 5, 6],[4, 5, 6]] tensor_2d = torch.tensor(data_2d)
结果
tensor([[1, 2, 3],
[4, 5, 6]
[4, 5, 6]])
但是形状是
torch.Size([3, 3])
是3行3列
# 三维张量,就是多个二维 tensor_3d = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]])
结果
tensor([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
torch.Size([2, 3, 4])
有 2 个元素(大小为 2)、3 行(大小为 3)和 4 列(大小为 4)。
torch.zeros(shape)
: 创建指定形状的全零张量。torch.ones(shape)
: 创建指定形状的全一张量。torch.randn(shape)
: 创建指定形状的随机张量。
创建有梯度的张量
x = torch.tensor([2.0], requires_grad=True)
设置requires_grad=True
,表示我们想要对这个张量进行梯度计算
查看维度:
dim()
方法用于获取张量的维度(即秩或阶)数量
查看尺寸
tensor.size()
: 返回张量的大小。形状的大小,几行几列
# 创建一个4x3的矩阵(2维tensor)
tensor_original = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print(tensor_original)
print(tensor_original.dim())
print(tensor_original.size())
tensor([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
2
torch.Size([4, 3])
改变形状
tensor.view(shape)
: 改变张量的形状。
# 创建一个4x3的矩阵(2维tensor) tensor_original = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) # 结果 tensor([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) # 使用view改变形状为3x4 tensor_reshaped = tensor_original.view(3, 4) # 结果 tensor([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]])
tensor.item()
: 获取张量中的单个元素的数值
转移设备
torch.Tensor.to(dtype=None, device=None, dtype2=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) → Tensor
# 创建一个CPU上的浮点型张量 x = torch.tensor([1.0, 2.0, 3.0]) # 将张量转移到CUDA设备上并转换为整型
将默认使用当前设备上的第一个可用的CUDA设备 y = x.to(dtype=torch.int, device='cuda')
y = x.to(dtype=torch.int, device='cuda:1') 就是第二块cuda
print(y)