Pytorch中的Tensor张量,就是numpy中的多维数组,用于数据的存储和处理,是机器学习系统中的基本数据结构。一阶张量是矢量,二阶张量是矩阵,三阶或更高阶的张量叫做高阶张量。
Tensor:
# We can construct a tensor directly from some common python iterables,
# such as list and tuple nested iterables can also be handled as long as the
# dimensions are compatible
# tensor from a list
a = torch.tensor([0, 1, 2])
#tensor from a tuple of tuples
b = ((1.0, 1.1), (1.2, 1.3))
b = torch.tensor(b)
# tensor from a numpy array
c = np.ones([2, 3])
c = torch.tensor(c)
print(f"Tensor a: {a}")
print(f"Tensor b: {b}")
print(f"Tensor c: {c}")
Tensor a: tensor([0, 1, 2]) Tensor b: tensor([[1.0000, 1.1000],[1.2000, 1.3000]]) Tensor c: tensor([[1., 1., 1.], [1., 1., 1.]], dtype=torch.float64)
# The numerical arguments we pass to these constructors
# determine the shape of the output tensor
x = torch.ones(5, 3)
y = torch.zeros(2)
z = torch.empty(1, 1, 5)
print(f"Tensor x: {x}")
print(f"Tensor y: {y}")
print(f"Tensor z: {z}")
# There are also constructors for random numbers
# Uniform distribution
a = torch.rand(1, 3)
# Normal distribution
b = torch.randn(3, 4)
# There are also constructors that allow us to construct
# a tensor according to the above constructors, but with
# dimensions equal to another tensor.
c = torch.zeros_like(a)
d = torch.rand_like(c)
print(f"Tensor a: {a}")
print(f"Tensor b: {b}")
print(f"Tensor c: {c}")
print(f"Tensor d: {d}")
Tensor x: tensor([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]) Tensor y: tensor([0., 0.]) Tensor z: tensor([[[ 2.1688e+03, 4.5630e-41, -1.5099e+06, 3.2862e-41, 0.0000e+00]]])
Tensor a: tensor([[0.4525, 0.5828, 0.3691]]) Tensor b: tensor([[ 1.9941, 0.6448, 0.0507, -0.3071], [-1.5652, 0.9180, -1.0236, 0.3736], [-0.6538, -0.6242, -0.7344, 0.1406]]) Tensor c: tensor([[0., 0., 0.]]) Tensor d: tensor([[0.5285, 0.7772, 0.6072]])
a = torch.arange(0, 10, step=1)torch.tensor()
b = np.arange(0, 10, step=1)
c = torch.linspace(0, 5, steps=11)
d = np.linspace(0, 5, num=11)
print(f"Tensor a: {a}\\n")
print(f"Numpy a)
print(f"Tensor c: {c}\\n")
print(f"Numpy array d: {d}\\n")
Tensor a: tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Numpy array b: [0 1 2 3 4 5 6 7 8 9]
Tensor c: tensor([0.0000, 0.5000, 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000, 4.5000, 5.0000])
Numpy array d: [0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ]