关于深度学习的基础的Python知识(PyTorch)

关于深度学习的基础的Python知识(PyTorch)


一、概念:张量

1、张量的定义:

张量是矩阵的扩展与延伸,可以认为是高阶的矩阵。1阶张量为向量,2阶张量为矩阵。张量是类似于Numpy的多维数组(ndarray)的概念,可以具有任意多的维度。

img

(图片来自邱锡鹏老师和飞桨的《神经网络与深度学习:案例与实践》)

2、个人理解:

张量是用向量组成的维度空间的实体,可以很方便地存放各式各样的信息。

二.、使用PyTorch实现张量运算

首先导入torch

import torch
1、创建张量
(1)以指定数据创建张量(以三阶张量为例)
# 创建一个三阶张量(指定数据创建张量)
ndim_1_Tensor = torch.tensor([[[1, 9], [6, 3]], [[0, 1], [2, 8]]])
print(ndim_1_Tensor)

运行结果:

在这里插入图片描述

(2)指定形状创建张量
# 指定形状创建
size = ndim_1_Tensor.size()
zero_Tensor = torch.zeros(size)  # 全零张量
print(zero_Tensor)
one_Tensor = torch.ones(size)  # 全一张量
print(one_Tensor)
full_Tensor = torch.full(size, 10)  #指定数据
print(full_Tensor)

运行结果:

在这里插入图片描述

2、张量的属性
(1)张量的形状属性

张量具有如下形状属性:

  • Tensor.ndim:张量的维度,例如向量的维度为1,矩阵的维度为2。
  • Tensor.shape: 张量每个维度上元素的数量。
  • Tensor.shape[n]:张量第n维的大小。第n维也称为轴(axis)。
  • Tensor.numel():张量中全部元素的个数。(paddle中为Tensor.size

img

(图片来自邱锡鹏老师和飞桨的《神经网络与深度学习:案例与实践》)

创建如图张量:

ndim_4_Tensor = torch.ones([2, 3, 4, 5])  # 创建一个每个维度的宽度分别为2,3,4,5的4维张量

打印出此向量的shapendimshape[n]numel()属性:

# 打印出此向量的`shape`、`ndim`、`shape[n]`、`numel()`属性
print("shape:", ndim_4_Tensor.shape)
print("ndim:", ndim_4_Tensor.ndim)
print("shape[2]:", ndim_4_Tensor.shape[1])
print("numel:", ndim_4_Tensor.numel())

运行结果:

在这里插入图片描述

(2)张量形状的改变

在实际使用中,还可以通过使用torch.reshape接口来改变张量的形状:

ndim_3_Tensor = torch.tensor([[[1, 2, 3, 4, 5],
                               [6, 7, 8, 9, 10]],
                              [[11, 12, 13, 14, 15],
                               [16, 17, 18, 19, 20]],
                              [[21, 22, 23, 24, 25],
                               [26, 27, 28, 29, 30]]])
print("shape:", ndim_3_Tensor.shape)
# 改变数据形状
reshape_Tensor = torch.reshape(ndim_3_Tensor, [2, 5, 3])
print("After reshape:", reshape_Tensor)

运行结果:
在这里插入图片描述

可以看到,通过此接口改变张量的形状后,张量内部的数据顺序是不变的。

除使用torch.reshape进行张量形状的改变外,还可以通过torch.unsqueeze将张量中的某一维度中插入尺寸为1的维度:

ones_Tensor = torch.ones([5, 10])
new_Tensor1 = torch.unsqueeze(ones_Tensor, dim=0)
print('new shape: ', new_Tensor1.shape)

运行结果

在这里插入图片描述

其他技巧:

reshape值设为-1,使张量变为一维:

new_Tensor1 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值