Python 深度学习 PyTorch Tensors新手入门必备教程

**

深度学习Pytorch Tensors部分讲解

**

# 导入库
import torch
import numpy as np

1.创建Tensor

1.1 直接从数据创建

# 可以直接利用数据创建tensor,数据类型会被自动推断出
data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)
print(x_data)
tensor([[1, 2],
        [3, 4]])

1.2 从Numpy创建

# Tensor 可以直接从numpy的array创建
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
print(x_np)
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)

1.3 从其他tensor创建

# 新的tensor保留了参数tensor的一些属性(形状,数据类型),除非显式覆盖
x_ones = torch.ones_like(x_data)  # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float)  # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.9728, 0.3274],
        [0.4597, 0.2323]]) 

1.4 从常数或者随机数创建

# shape是关于tensor维度的一个元组,在下面的函数中,它决定了输出tensor的维数
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}")
Random Tensor: 
 tensor([[0.3600, 0.8294, 0.9304],
        [0.4292, 0.9384, 0.1833]]) 

Ones Tensor: 
 tensor([[1., 1., 1.],
        [1., 1., 1.]]) 

Zeros Tensor: 
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

2.Tensor的属性

# Tensor的属性包括形状,数据类型以及存储的设备
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

3.Tensor的操作

if torch.cuda.is_available():
    tensor = tensor.to('cuda')

3.1索引和切片

tensor2 = torch.ones(4,4)
tensor2[:,1] = 0
print(tensor2)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

3.2合并tensors

# 可以使用torch.cat来沿着特定维数连接一系列张量
# torch.stack另一个加入op的张量与torch.cat有细微的不同
t1 = torch.cat([tensor, tensor, tensor], dim=1)  # 横着拼
print(t1)
t2 = torch.cat([tensor, tensor, tensor], dim=0)  # 竖着拼
print(t2)
tensor([[0.2744, 0.7630, 0.7336, 0.6286, 0.2744, 0.7630, 0.7336, 0.6286, 0.2744,
         0.7630, 0.7336, 0.6286],
        [0.0764, 0.5366, 0.3712, 0.1719, 0.0764, 0.5366, 0.3712, 0.1719, 0.0764,
         0.5366, 0.3712, 0.1719],
        [0.1072, 0.6136, 0.1888, 0.8031, 0.1072, 0.6136, 0.1888, 0.8031, 0.1072,
         0.6136, 0.1888, 0.8031]])
tensor([[0.2744, 0.7630, 0.7336, 0.6286],
        [0.0764, 0.5366, 0.3712, 0.1719],
        [0.1072, 0.6136, 0.1888, 0.8031],
        [0.2744, 0.7630, 0.7336, 0.6286],
        [0.0764, 0.5366, 0.3712, 0.1719],
        [0.1072, 0.6136, 0.1888, 0.8031],
        [0.2744, 0.7630, 0.7336, 0.6286],
        [0.0764, 0.5366, 0.3712, 0.1719],
        [0.1072, 0.6136, 0.1888, 0.8031]])

3.3增加tensors

# This computes the element-wise product
print(f"tensor.mul(tensor) \n {tensor.mul(tensor)} \n")
# Alternative syntax:
print(f"tensor * tensor \n {tensor * tensor}")
tensor.mul(tensor) 
 tensor([[0.0753, 0.5821, 0.5381, 0.3951],
        [0.0058, 0.2879, 0.1378, 0.0295],
        [0.0115, 0.3765, 0.0357, 0.6449]]) 

tensor * tensor 
 tensor([[0.0753, 0.5821, 0.5381, 0.3951],
        [0.0058, 0.2879, 0.1378, 0.0295],
        [0.0115, 0.3765, 0.0357, 0.6449]])

3.4计算两个tensor之间的矩阵乘法

print(f"tensor.matmul(tensor.T) \n {tensor.matmul(tensor.T)} \n")
# Alternative syntax:
print(f"tensor @ tensor.T \n {tensor @ tensor.T}")
tensor.matmul(tensor.T) 
 tensor([[1.5906, 0.8106, 1.1409],
        [0.8106, 0.4611, 0.5455],
        [1.1409, 0.5455, 1.0686]]) 

tensor @ tensor.T 
 tensor([[1.5906, 0.8106, 1.1409],
        [0.8106, 0.4611, 0.5455],
        [1.1409, 0.5455, 1.0686]])

3.5原地操作

# 带有后缀``_``的操作表示的是原地操作,例如: ``x.copy_(y)``, ``x.t_()``将改变 ``x``
print(tensor, "\n")
tensor.add_(5)
print(tensor)
# 注意:原地操作虽然会节省许多空间,但是由于会立刻清除历史记录所以在计算导数时可能会有问题,因此不建议使用
tensor([[0.2744, 0.7630, 0.7336, 0.6286],
        [0.0764, 0.5366, 0.3712, 0.1719],
        [0.1072, 0.6136, 0.1888, 0.8031]]) 
tensor([[5.2744, 5.7630, 5.7336, 5.6286],
        [5.0764, 5.5366, 5.3712, 5.1719],
        [5.1072, 5.6136, 5.1888, 5.8031]])

3.6.1Tensor转换为Numpy数组

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")  # tensor的变化反映在NumPy数组中
t.add_(1)
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.]

3.6.2Numpy数组转换为Tensor

n = np.ones(5)
t = torch.from_numpy(n)  # NumPy数组的变化反映在tensor中
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

猜你喜欢

转载自blog.csdn.net/weixin_46087812/article/details/114108514
今日推荐