神经网络与深度学习(二) pytorch入门——张量

本文章通过参考飞桨AI Studio - 人工智能学习与实训社区  教程进行pytorch相关学习。

目录

一. 概念:张量、算子

二. 使用pytorch实现张量运算

1.2.1 创建张量

1.2.1.1 指定数据创建张量

1.2.1.2 指定形状创建

1.2.1.3 指定区间创建

1.2.2 张量的属性

1.2.2.1 张量的形状

1.2.2.2 形状的改变

1.2.2.3 张量的数据类型

1.2.2.4 张量的设备位置

1.2.3 张量与Numpy数组转换

1.2.4 张量的访问

1.2.4.1 索引和切片

1.2.4.2 访问张量

1.2.4.3 修改张量

1.2.5 张量的运算

1.2.5.1 数学运算

1.2.5.2 逻辑运算

1.2.5.3 矩阵运算

1.2.5.4 广播机制

三. 使用pytorch实现数据预处理


一. 概念:张量、算子


张量:张量为我们提供了描述具有任意数量轴的n维数组的通用方法,是矩阵的扩展与延伸。张量类似于Numpy的多维数组(ndarray)的概念,可以具有任意多的维度。
算子:算子是构建复杂机器学习模型的基础组件,包含一个函数f(x)的前向函数和反向函数。深度学习算法由一个个计算单元组成,我们称这些计算单元为算子。

二. 使用pytorch实现张量运算


1.2.1 创建张量

创建一个张量可以有多种方式,如:指定数据创建、指定形状创建、指定区间创建等。

1.2.1.1 指定数据创建张量

通过给定Python列表数据,可以创建任意维度的张量。

(1)通过指定的Python列表数据[2.0, 3.0, 4.0],创建一个一维张量。

import torch
X = torch.tensor([2.0, 3.0, 4.0])
print(X)

运行结果:

(2)通过指定的Python列表数据来创建类似矩阵(matrix)的二维张量。 

import torch
X = torch.tensor([[1.0, 2.0, 3.0],
                 [4.0, 5.0, 6.0]])
print(X)

运行结果:

 (3)同样地,还可以创建维度为3、4...N等更复杂的多维张量。

import torch
X = torch.tensor([[[1, 2, 3, 4, 5],
                   [6, 7, 8, 9, 10]],
                  [[11, 12, 13, 14, 15],
                   [16, 17, 18, 19, 20]]])
print(X)

运行结果:

(注:需要注意的是,张量在任何一个维度上的元素数量必须相等。下面尝试定义一个在同一维度上元素数量不等的张量。 )

1.2.1.2 指定形状创建

如果要创建一个指定形状、元素数据相同的张量,可以使用torch.zeros、torch.onestorch.full等。

import torch
m, n = 2, 3
zeros_tensor = torch.zeros([m, n])
ones_tensor = torch.ones([m, n])
full_tensor = torch.full([m, n], 10)
print('zeros Tensor:\n', zeros_tensor)
print('ones Tensor:\n', ones_tensor)
print('full Tensor:\n', full_tensor)

运行结果:
 

1.2.1.3 指定区间创建

如果要在指定区间内创建张量,可以使用torch.arangetorch.linspace等。

import torch
arange_tensor = torch.arange(start=1, end=5, step=1)
linspace_tensor = torch.linspace(start=1, end=5, steps=5)
print('arange Tensor:\n', arange_tensor)
print('linspace Tensor:\n', linspace_tensor)

运行结果:

1.2.2 张量的属性

1.2.2.1 张量的形状

张量具有如下形状属性:

  • Tensor.ndim:张量的维度,例如向量的维度为1,矩阵的维度为2。
  • Tensor.shape: 张量每个维度上元素的数量。
  • Tensor.shape[n]:张量第n维的大小。第n维也称为轴。
  • Tensor.numel():张量中全部元素的个数。
import torch
X = torch.ones([2, 3, 4, 5])
print("Number of dimensions:", X.ndim)
print("Shape of Tensor:", X.shape)
print("Elements number along axis 0 of Tensor:", X.shape[0])
print("Elements number along the last axis of Tensor:", X.shape[-1])
print('Number of elements in Tensor: ', X.numel())

运行结果:

(注:pytorch中Tensor.size()显示的是矩阵的规模)

1.2.2.2 形状的改变

除了查看张量的形状外,重新设置张量的在实际编程中也具有重要意义。

import torch
X = 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('the shape of X:', X.shape)
print('after reshape:\n', X.view([2, 5, 3]))

运行结果:

 

(注:张量数据形状发生改变,而张量内的数据和元素顺序则没有发生改变)

分别对上文定义的X进行reshape为[-1]操作和reshape为[1, 5, 6]两种操作,观察新张量的形状。

import torch
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]]])

new_Tensor1 = ndim_3_Tensor.reshape([-1])
print('new Tensor 1 shape: ', new_Tensor1.shape)
new_Tensor2 = ndim_3_Tensor.reshape([1, 5, 6])
print('new Tensor 2 shape: ', new_Tensor2.shape)

运行结果:

从输出结果看,第一行代码中的第一个reshape操作将张量reshape为元素数量为30的一维向量;第四行代码中的第二个reshape操作中,0对应的维度的元素个数与原张量在该维度上的元素个数相同。

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

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

运行结果:

(注:torch.unsqueeze()中,dim表示插入维度的索引,即在哪里插入)

1.2.2.3 张量的数据类型

pytorch中可以通过Tensor.dtype来查看数据类型。

Tensor的最基本数据类型有:

  • 32位浮点型:torch.float32 (最常用)
  • 64位浮点型:torch.float64 (最常用)
  • 32位整型:torch.int32
  • 16位整型:torch.int16
  • 64位整型:torch.int64

1)通过Python元素创建的张量,如果未指定:

  • 对于Python整型数据,则会创建int64型张量。
  • 对于Python浮点型数据,默认会创建float32型张量。

2)通过Numpy数组创建的张量,则与其原来的数据类型保持相同。通过torch.tensor()函数可以将Numpy数组转化为张量。

import torch
print('Tensor dtype from python integers:', torch.tensor(1).dtype)
print('Tensor dtype from python floating point:', torch.tensor(1.0).dtype)

运行结果:

 如果想改变张量的数据类型,可以通过调用Tensor.type来实现。

import torch
float32_tensor = torch.tensor(1.0)
int64_tensor = float32_tensor.type(torch.int64)
print('Tensor after cast to int64:', int64_tensor.dtype)

运行结果:

1.2.2.4 张量的设备位置

初始

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值