跳至主要內容

Pytorch的使用

牧歌...大约 4 分钟

Pytorch的使用

import torch
import numpy as np

tensors声明

data = [[1,2],[3,4]]
x_data = torch.tensor(data)
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
x_ones = torch.ones_like(x_data)
print(f"Ones Tensor: \n { x_ones } \n")
x_read = torch.rand_like(x_data, dtype = torch.float)
print(f"Random Tensor: \n {x_read} \n")
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.8995, 0.6255],
        [0.1218, 0.9577]]) 

torch.rand()、torch.randn()、torch.randint()、torch.randperm()、torch.ones()、torch.zeros()

torch.rand(*sizes, out=None) -> Tensor 返回的是一个张量(tensor),包含了从区间 [1,0)均匀分布中抽取的一组随机数,tensor的形状由参数sizes定义

torch.randn(*sizes, out=None) -> Tensor 返回的是一个张量(tensor),包含标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数,tensor的形状由参数sizes定义

torch.randint(low=0, high, size, out=None, dtype=None) 整数范围[low, high)

randint_like(input, low=0, high, dtype=None)

randperm(n, out=None, dtype=torch.int64)-> LongTensor 得到0~n-1的序列进行排列组合

shape = (2,5)

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.3933, 0.6725, 0.7713, 0.7880, 0.6753],
        [0.4222, 0.0401, 0.0159, 0.1446, 0.1736]]) 

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

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

tensors详情查看

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
# 如果 cuda 是可用的,则使用GPU加速

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

print(f"Device tensor is stored on: {tensor.device}")
Device tensor is stored on: cpu

tensors截取和拼接

# 上面 data = [[1,2],[3,4]]

tensor = torch.tensor(data)

  

print('First row:', tensor[0])

print('Fist column:', tensor[:, 0])

print('Last colum:', tensor[..., -1])

tensor[:, 1] = 0

print(tensor)

print(f"Device tensor is stored on: {tensor.device}")
First row: tensor([1, 2])
Fist column: tensor([1, 3])
Last colum: tensor([2, 4])
tensor([[1, 0],
        [3, 0]])
Device tensor is stored on: cpu

下面是torch.cat函数的用法和一个示例说明:

torch.cat(tensors, dim=0, out=None) -> Tensor

参数说明:

  • tensors:要拼接的张量序列,可以是一个张量列表或元组。
  • dim:指定拼接的维度。例如,dim=0表示在第一个维度上拼接,dim=1表示在第二个维度*上拼接,以此类推。
  • out:可选参数,用于指定输出张量的位置。如果未提供,将创建一个新的张量来保存结果。
# 它可以沿着指定的维度将多个张量连接在一起。

t1 = torch.cat([tensor, tensor, tensor], dim = 1)

print(t1)
tensor([[1, 0, 1, 0, 1, 0],
        [3, 0, 3, 0, 3, 0]])
c = torch.tensor(
          [
            [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]
          ],

          [
            [11, 12, 13],
            [14, 15, 16],
            [17, 18, 19]
          ]
         ])
print("c type:", c.shape)
d = torch.tensor([
            [
              [21, 22, 23],
              [24, 25, 26],
              [27, 28, 29]
            ],

            [
              [31, 32, 33],
              [34, 35, 36],
              [37, 38, 39]
            ]
          ])
print("d type:", d.shape)
result = torch.cat((c, d), dim=2)
print("result type:", result.shape)
result
c type: torch.Size([2, 3, 3])
d type: torch.Size([2, 3, 3])
result type: torch.Size([2, 3, 6])
tensor([[[ 1,  2,  3, 21, 22, 23],
         [ 4,  5,  6, 24, 25, 26],
         [ 7,  8,  9, 27, 28, 29]],

        [[11, 12, 13, 31, 32, 33],
         [14, 15, 16, 34, 35, 36],
         [17, 18, 19, 37, 38, 39]]])

tensors乘法计算

矩阵乘法 设A为 的矩阵,B为 的矩阵,那么称 的矩阵C为矩阵A与B的乘积,记作 ,其中矩阵C中的第 行第 列元素可以表示为:

(AB)ij=k=1paikbkj=ai1b1j+ai2b2j++aipbpj (AB)_{ij} = \sum_{k=1}^pa_{ik}b_{kj}= a_{i1}b_{1j}+a_{i2}b_{2j}+\cdots+a_{ip}b_{pj}

如下所示:

[a1,1a1,2a1,3a2,1a2,2a2,3]×[b1,1b1,2b2,1b2,2b3,1b3,2]=[a1,1b1,1+a1,2b2,1+a1,3b3,1a1,1b1,2+a1,2b2,2+a1,3b3,2a2,1b1,1+a2,2b2,1+a2,3b3,1a2,1b1,2+a2,2b2,2+a2,3b3,2] \begin{bmatrix} a_{1,1} & a_{1,2} & a_{1,3} \\ a_{2,1} & a_{2,2} & a_{2,3} \end{bmatrix} × \begin{bmatrix} b_{1,1} & b_{1,2} \\ b_{2,1} & b_{2,2} \\ b_{3,1} & b_{3,2} \end{bmatrix} = \begin{bmatrix} a_{1,1}b_{1,1} + a_{1,2}b_{2,1} + a_{1,3}b_{3,1} & a_{1,1}b_{1,2} + a_{1,2}b_{2,2} + a_{1,3}b_{3,2} \\ a_{2,1}b_{1,1} + a_{2,2}b_{2,1} + a_{2,3}b_{3,1} & a_{2,1}b_{1,2} + a_{2,2}b_{2,2} + a_{2,3}b_{3,2} \end{bmatrix}

tensor = torch.ones(4, 4)
tensor[:, 1] = 0
print(tensor)
# 转置
print(tensor.T)
# 矩阵乘法
y1 = tensor @ tensor.T
print(y1)
# 矩阵乘法
y2 = tensor.matmul(tensor.T)
print(y2)
# 矩阵乘法
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
tensor([[1., 1., 1., 1.],
        [0., 0., 0., 0.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
# 每个元素的乘积
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
# 得到求和,并使用item取出
agg = tensor.sum()
print(agg)
agg_item = agg.item()
print(agg_item, type(agg_item))
tensor(12.)
12.0 <class 'float'>
# 就地操作,可以用 x += 5; 理解
print(tensor)
tensor.add_(5)
print(tensor)
# 就地操作可以节省一些内存,但是在计算派生时可能会出现问题,因为会立即丢失历史记录。因此,不鼓励使用它们。
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])
tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

NumPy array 与 Tensor 互转

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}")
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.]
n = np.ones(5)
print(n)
t = torch.from_numpy(n)
print(t, "\n")
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
[1. 1. 1. 1. 1.]
tensor([1., 1., 1., 1., 1.], dtype=torch.float64) 

t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
上次编辑于:
贡献者: wenleiwang
评论
  • 按正序
  • 按倒序
  • 按热度