在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行编码。
张量初始化
import torch
import numpy as np
#初始化
#直接数据转张量
data=[[1,2],[3,4]]
x_data=torch.tensor(data)
#numpy数组转张量
np_array=np.array(data)
x_np=torch.from_numpy(np_array)
#从另一个张量中来
x_ones=torch.ones_like(x_data)#根据给定张量生成与其形状相同的全1张量,x_ones=tensor([[1, 1],[1, 1]])
print(f"Ones Tensor:\n{x_ones}\n")
x_rand=torch.rand_like(x_data,dtype=torch.float)#根据给定张量生成与其形状相同的随机张量,x_ones= tensor([[0.4621, 0.1440],[0.6105, 0.6398]])
print(f"Random Tensor:\n{x_rand}\n")
#使用随机或恒定值
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}")
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.7534, 0.7931],
[0.6865, 0.4835]])
Random Tensor:
tensor([[0.9617, 0.6932, 0.2289],
[0.1303, 0.1489, 0.2075]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
Process finished with exit code 0
张量属性
#张量属性,包括形状,数据类型和存储设备
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}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
与numpy的连接
#torch与numpy的桥接,torch和numpy共享底层内存位置,改变一个会改变另一个
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
n = np.ones(5)
t = torch.from_numpy(n)
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]