python tensor 维度 复制 python 数据复制

【pytorch】(一)张量(tensor)


三阶多项式拟合正弦函数(numpy, ndarray)

Numpy是科学计算的框架,不是专门用于计算图、深度学习或梯度的。但我们可以使用numpy实现网络的正向和反向传播。例如,用三阶多项式拟合正弦函数:

# -*- coding: utf-8 -*-
import numpy as np
import math
import time

time_start = time.time()
# 随机初始化输入和输出数据
x = np.linspace(-math.pi, math.pi, )
y = np.sin(x)

# 随机初始化权重
a = np.random.randn()
b = np.random.randn()
c = np.random.randn()
d = np.random.randn()

learning_rate = 1e-6
for t in range):
    # 前向传播:计算预测值 y
    # y = a + b x + c x^2 + d x^3
    y_pred = a + b * x + c * x ** 2 + d * x ** 3

    # 计算损失
    loss = np.square(y_pred - y).sum()
    if t %  == :
        print(f'迭代次数:{t+1},损失值:{loss}')

    # 反向传播:计算损失关于a, b, c, d 的梯度
    grad_y_pred =  * (y_pred - y)
    grad_a = grad_y_pred.sum()
    grad_b = (grad_y_pred * x).sum()
    grad_c = (grad_y_pred * x ** 2).sum()
    grad_d = (grad_y_pred * x ** 3).sum()

    # 梯度下降更新权重
    a -= learning_rate * grad_a
    b -= learning_rate * grad_b
    c -= learning_rate * grad_c
    d -= learning_rate * grad_d
time_end = time.time()
print('消耗时间:', time_end - time_start, 's')
print(f'结果: y = {a} + {b} x + {c} x^2 + {d} x^3')

输出:

...
...
迭代次数:,损失值:
消耗时间:  s
结果: y = - +  x + 0. x^2 + - x^3

既然numpy也可以实现网络的正向和反向传播,那为什么还要pytorch呢?

Numpy是一个很棒的框架,但它不能利用GPU来加速计算,这使得它不适用于大计算量的深度学习。而pytorch的一种数据结构——张量(tensor)则可以在GPU或其他硬件加速器上运行。另外,pytorch的自动求导机制,能自动的帮我们把反向传播全部计算好。

下面,我们将进入本文的主题:张量(tensor)。

张量

张量(tensor)是一种特殊的数据结构,与数组和矩阵非常相似。在pytorch中,我们使用张量对模型的输入和输出以及模型的参数进行编码。张量与NumPy的数组很相似,只是它可以在GPU或其他硬件加速器上运行。

In[2]: import torch
In[3]: import numpy as np

直接由数据得到

使用torch.tensor()

In[4]: data = [[1, 2],[3, 4]]
In[5]: x_data = torch.tensor(data)
In[6]: x_data
Out[6]: 
tensor([[1, 2],
        [3, 4]])

由NumPy array得到

使用torch.from_numpy()

np_array = np.array(data)
x_np = torch.from_numpy(np_array)
x_np
Out[9]: 
tensor([[1, 2],
        [3, 4]], dtype=torch.int32)

由另一个张量得到

除非显式重写,否则新的张量将保留参数张量的属性(形状、数据类型)。

In[]: x_ones = torch.ones_like(x_data)
In[]: x_ones
Out[]: 
tensor([[1, 1],
        [1, 1]])
In[]: x_rand = torch.rand_like(x_data, dtype=torch.float)  # 类型重写
In[]: x_rand
Out[]: 
tensor([[, ],
        [, ]])
In[]: x_rand.dtype
Out[]: torch.float32

初始化随机或常量值张量

shape是表示张量维度的元组。在下面的函数中,它决定了输出张量的维数。

In[]: shape = (2,3,)
   ...: rand_tensor = torch.rand(shape)
   ...: ones_tensor = torch.ones(shape)
   ...: zeros_tensor = torch.zeros(shape)
In[]: rand_tensor 
Out[]: 
tensor([[, , ],
        [, , ]])
In[]: ones_tensor
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.]])
In[]: zeros_tensor
Out[]: 
tensor([[0., 0., 0.],
        [0., 0., 0.]])

张量的属性

张量属性描述它们的形状(shape)、数据类型(dtype)和存储它们的设备(device)。

In[]: tensor = torch.rand(3,4)
In[]: tensor.shape
Out[]: torch.Size([3, 4])
In[]: tensor.dtype
Out[]: torch.float32
In[]: tensor.device
Out[]: device(type='cpu')

张量运算

pytorch对张量有超过种运算操作(传送门)。每个操作都可以在GPU上运算(速度通常高于CPU)。

默认情况下,创建张量都是在CPU上运算。我们需要使用.to显式地将张量移动到GPU中(在GPU可用的前提下)。但请记住,跨设备复制大量张量需要耗费许多时间和内存!

In[]: tensor
Out[]: 
tensor([[, , , ],
        [, , , ],
        [, , , ]])
In[]: # 如果GPU可用,将张量移动到GPU
   ...: if torch.cuda.is_available():
   ...:     tensor = tensor.to('cuda')
In[]: tensor
Out[]: 
tensor([[, , , ],
        [, , , ],
        [, , , ]], device='cuda:0')

下面列举一些简单的操作。如果你熟悉NumPy API,您会发现Tensor API很容易使用。

标准numpy式的索引和切片


In[]: tensor = torch.rand(4, 4)
In[]: tensor
Out[]: 
tensor([[, , , ],
        [, , , ],
        [, , , ],
        [, , , ]])
In[]: tensor[0] # 第一行
Out[]: tensor([, , , ])
In[]: tensor[:, 0] #第一列
Out[]: tensor([, , , ])
In[]: tensor[..., -1] # 最后一列
Out[]: tensor([, , , ])

连接张量[2]

连接张量有两种方法:torch.cat()或torch.stack()

In[]: tensor = torch.ones(2, 3)
In[]: tensor
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.]])

首先看一下torch.cat():

dim=1时,形状变为[2, 6]

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

dim=0时,形状变为[6, 2]

In[]: t0 = torch.cat([tensor, tensor, tensor], dim=0)
In[]: t0
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

与torch.cat()不同,torch.stack()是沿着一个新维度对输入张量序列进行连接。 序列中所有的张量都应该为相同形状。

浅显说法:就是把多个2维的张量凑成一个3维的张量;多个3维的凑成一个4维的张量……以此类推,也就是在增加新的维度进行堆叠。

例子: 准备2个[3,3]的张量数据。

In[]: T1 = torch.tensor([[1, 2, 3],
   ...:           [4, 5, 6],
   ...:           [7, 8, 9]])
   ...: T2 = torch.tensor([[, , ],
   ...:           [, , ],
   ...:           [, , ]])

dim=0时,形状变为[2, 3, 3]

In[]: stack_0=torch.stack((T1,T2),dim=0)
In[]: stack_0
Out[]: 
tensor([[[ 1,  2,  3],
         [ 4,  5,  6],
         [ 7,  8,  9]],

        [[, , ],
         [, , ],
         [, , ]]])
In[]: stack_0.shape
Out[]: torch.Size([2, 3, 3])

dim=1时,形状变为[3, 2, 3]

In[]: stack_1=torch.stack((T1,T2),dim=1)
In[]: stack_1
Out[]: 
tensor([[[ 1,  2,  3],
         [, , ]],

        [[ 4,  5,  6],
         [, , ]],

        [[ 7,  8,  9],
         [, , ]]])
In[]: stack_1.shape
Out[]: torch.Size([3, 2, 3])

dim=2时,形状变为[3, 3, 2]

In[]: stack_2=torch.stack((T1,T2),dim=2)
In[]: stack_2
Out[]: 
tensor([[[ 1, ],
         [ 2, ],
         [ 3, ]],

        [[ 4, ],
         [ 5, ],
         [ 6, ]],

        [[ 7, ],
         [ 8, ],
         [ 9, ]]])
In[]: stack_2.shape
Out[]: torch.Size([3, 3, 2])

算术运算

下面是计算两个张量之间的矩阵乘法的方法。y1、y2、y3将具有相同的值

In[]: tensor=torch.ones(3,3)
In[]: y1 = tensor @ tensor.t() #.t():矩阵转置
In[]: y2 = tensor.matmul(tensor.t())
In[]: y3 = torch.rand_like(tensor)
In[]: torch.matmul(tensor, tensor.t(), out=y3)
Out[]: 
tensor([[3., 3., 3.],
        [3., 3., 3.],
        [3., 3., 3.]])
In[]: y1
Out[]: 
tensor([[3., 3., 3.],
        [3., 3., 3.],
        [3., 3., 3.]])
In[]: y2
Out[]: 
tensor([[3., 3., 3.],
        [3., 3., 3.],
        [3., 3., 3.]])
In[]: y3
Out[]: 
tensor([[3., 3., 3.],
        [3., 3., 3.],
        [3., 3., 3.]])

下面将计算逐元素的乘积。z1、z2、z3将具有相同的值

In[]: z1 = tensor * tensor
In[]: z2 = tensor.mul(tensor)
In[]: z3 = torch.rand_like(tensor)
In[]: torch.mul(tensor, tensor, out=z3);
In[]: z1
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
In[]: z2
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
In[]: z3
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

单元素张量

如果有一个单元素张量,例如将张量的所有值加起来得到一个值,那么可以使用item()将其转换为Python数值:

In[]: agg = tensor.sum()
In[]: agg
Out[]: tensor(9.)
In[]: agg_item = agg.item()
In[]: agg_item
Out[]: 
In[]: type(agg_item)
Out[]: float
In[]: type(agg)
Out[]: torch.Tensor

就地(In-place)操作[3]

就地操作是直接更改给定张量的内容而不会为变量分配新的内存进行复制。

将结果存储到操作数中的操作称为就地调用。它们由一个后缀表示。例如:x.copy_(y), x.t_()。这种操作将更改x。

In[]: tensor
Out[]: 
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
In[]: tensor.add_(5)
Out[]: 
tensor([[6., 6., 6.],
        [6., 6., 6.],
        [6., 6., 6.]])
In[]: tensor
Out[]: 
tensor([[6., 6., 6.],
        [6., 6., 6.],
        [6., 6., 6.]])

注意: 就地操作可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。因此,不鼓励使用它们。

张量与Numpy 数组

在CPU的tensor和NumPy的array会共享其底层内存,即更改其中一个的同时另一个也会被更改。

张量 到 NumPy 数组

In[]: t = torch.ones(5)
In[]: n = t.numpy()
In[]: t
Out[]: tensor([1., 1., 1., 1., 1.])
In[]: n
Out[]: array([1., 1., 1., 1., 1.], dtype=float32)

张量的改变将导致对应NumPy数组的改变。


In[]: t.add_(1)
Out[]: tensor([2., 2., 2., 2., 2.])
In[]: t
Out[]: tensor([2., 2., 2., 2., 2.])
In[]: n
Out[]: array([2., 2., 2., 2., 2.], dtype=float32)

NumPy 数组 到 张量

In[]: n = np.ones(5)
In[]: t = torch.from_numpy(n)
In[]: np.add(n, 1, out=n)
Out[]: array([2., 2., 2., 2., 2.])
In[]: t
Out[]: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
In[]: n
Out[]: array([2., 2., 2., 2., 2.])

三阶多项式拟合正弦函数(pytorch,tensor)

下面我们基于PyTorch的张量,将三阶多项式拟合正弦函数。

# -*- coding: utf-8 -*-
import torch
import math
import time

time_start = time.time()
dtype = torch.float
device = torch.device("cpu")
#device = torch.device("cuda:0") # 取消这一行注释以在GPU上运行

# 随机初始化输入和输出数据
x = torch.linspace(-math.pi, math.pi, , device=device, dtype=dtype)
y = torch.sin(x)

# 随机初始化权重
a = torch.randn((), device=device, dtype=dtype)
b = torch.randn((), device=device, dtype=dtype)
c = torch.randn((), device=device, dtype=dtype)
d = torch.randn((), device=device, dtype=dtype)

learning_rate = 1e-6

for t in range):
    # 前向传播:计算预测值 y
    y_pred = a + b * x + c * x ** 2 + d * x ** 3

    # 计算损失
    loss = (y_pred - y).pow(2).sum().item()
    if t %  == :
        print(f'迭代次数:{t + 1},损失值:{loss}')

    # 反向传播:计算损失关于a, b, c, d 的梯度
    grad_y_pred =  * (y_pred - y)
    grad_a = grad_y_pred.sum()
    grad_b = (grad_y_pred * x).sum()
    grad_c = (grad_y_pred * x ** 2).sum()
    grad_d = (grad_y_pred * x ** 3).sum()

    # 梯度下降更新权重
    a -= learning_rate * grad_a
    b -= learning_rate * grad_b
    c -= learning_rate * grad_c
    d -= learning_rate * grad_d
time_end = time.time()
print('消耗时间:', time_end - time_start, 's')
print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')

使用CPU,输出:

...
...
迭代次数:,损失值:
消耗时间:  s
Result: y =  +  x + - x^2 + - x^3

使用GPU,输出:

...
...
迭代次数:,损失值:
消耗时间:  s
Result: y = -0. +  x + 2.19428966374835e- x^2 + - x^3

???说好的GPU加速呢?

用电锯切菜能快么,电锯是用来砍树的。同样道理,GPU在大规模网络才有明显的加速。

GPU比CPU慢的原因大致为[4]: 数据传输会有很大的开销,而GPU处理数据传输要比CPU慢,而GPU的专长矩阵计算在小规模神经网络中无法明显体现出来。

下面以单纯的矩阵乘法做对比:

import torch
import time

a = torch.ones, )
b = torch.ones, )

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print('CPU:', t1 - t0, 's')

device = torch.device('cuda')

a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print('GPU:', t1 - t0, 's')

输出:

CPU:  s
GPU:  s

这不,快了。

参考:

[1] https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html

[2] https://blog.csdn.net/xinjieyuan/article/details/

[3]https://zhuanlan.zhihu.com/p/

[4]https://blog.csdn.net/qq_43673118/article/details/

原文链接:,转发请注明来源!