PyTorch安装与Tensor基本语法

本文详细介绍了PyTorch的安装步骤,包括在虚拟环境中安装,并提供了Linux和Mac的安装命令。接着,文章阐述了张量(Tensor)的概念,从标量到多维数组,并展示了创建不同类型的张量的方法。此外,还涵盖了张量的算术运算,如加减乘除、取整取余,以及变形和排序操作。文章深入浅出,适合PyTorch初学者。

        2017年1月,由Facebook人工智能研究院(FAIR)基于Torch推出了PyTorch,它是一个开源的Python机器学习库,用于NLP、CV等应用程序。

优点:

1. 相当简洁且高效快速的框架,入门简单;

2. 动态计算图:提供了一个可以在运行时构建计算图(甚至在运行时可更改)的一个框架;

3. 多gpu支持,自定义数据加载器和简化的预处理器。

1. 安装pyTorch

1.1 使用pip安装虚拟环境

# 安装pip
sudo apt install python3-pip

# 安装虚拟环境(新建一个myTorch的目录,安装在此目录下)
pip3 install virtualenv
# sudo apt install virtualenv

# 创建虚拟环境,并命名为DL
mkdir myTorch
cd myTorch
virtualenv  --no-site-packages DL

# 进入虚拟环境
source DL/bin/activate
# 退出虚拟环境
deactivate

1.2 在虚拟环境内安装pytorch

安装地址:https://pytorch.org

进入官网安装页面选择系统、平台等,生成安装命令:

# Linux 安装
pip install torch==1.5.1+cpu torchvision==0.6.1+cpu -f https://download.pytorch.org/whl/torch_stable.html
# Mac 安装
pip install torch torchvision
conda install pytorch torchvision torchaudio -c pytorch
# 加入清华源
-i https://pypi.tuna.tsinghua.edu.cn/simple

2. Tensor的概念及创建

scalar 标量: 一个数值

vector 向量: 一维数组

matrix 矩阵: 二维数组

tensor 张量: 大于二维的数组(多维数组)

# 标量
torch.tensor(4.0)
# tensor(4.)

# 向量
torch.tensor([1.5, 0, 3])
# tensor([1.5000, 0.0000, 3.0000])

# 矩阵
torch.tensor([[1, 2], [3, 4]])
# tensor([[1, 2],
#         [3, 4]])

# 多维矩阵 
torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# tensor([[[1, 2],
#          [3, 4]],
#         [[5, 6],
#          [7, 8]]])

9种数据类型

numpy.float64     numpy.float32       numpy.float16

numpy.int64        numpy.int32          numpy.int16

numpy.int8          numpy.uint8          numpy.bool

tensor创建

import torch

# 创建一个空的tensor
torch.empty(2, 3)
# tensor([[ 2.6427e-29,  4.5800e-41, -1.5012e+10],
#        [ 4.5799e-41,  2.6473e-29,  4.5800e-41]])

# 设置随机种子
torch.manual_seed(123)
# 产生一个1行2列,数值在0-1之间的张量
torch.rand(1, 2)
# tensor([[0.2763, 0.8152]])

# 创建一个全为0的张量(3行3列)
torch.zeros(3, 3)
torch.zeros(2, 2, dtype=torch.long)

# 创建一个全1的矩阵
torch.ones(2, 2)

# 创建对角线为1的tensor
torch.eye(3, 3)
# tensor([[1., 0., 0.],
#         [0., 1., 0.],
#         [0., 0., 1.]])

# 创建一个产生随机元素的矩阵,其shape与另一个矩阵的shape一致
x = torch.empty(2, 3)
x1 = torch.rand_like(x, dtype=torch.float)

其他方法创建

# 将numpy转换为tensor
x = np.array([3, 4, 5, 6, 7])
# y = torch.from_numpy(x)
y = torch.as_tensor(x)  # 一般用这个,使用范围更广,可以是list等各种类型 
# tensor转numpy
print(x.numpy())
# [3 4 5 6 7]

# 将2-10之间的数,切分为5个
torch.linspace(2, 10, steps=5)
# tensor([ 2.,  4.,  6.,  8., 10.])

3. Tensor的算术运算

3.1 基本操作

# 判断是否为张量
torch.is_tensor(x)

# 输出张量中元素的个数
torch.numel(x)
# 2

x = torch.tensor([1, torch.nan, 6, torch.inf])
# 是否是空值
print(torch.isnan(x))
# tensor([False,  True, False, False])
# 是否是无穷大
print(torch.isinf(x))
# tensor([False, False, False,  True])
# 是否是有效数字(或可转化为有效数字)
print(torch.isfinite(x))
# tensor([ True, False,  True, False])

3.2 加减乘除、取整取余

加法

x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])

# tensor中每个元素加1
torch.add(x, 1)

# 两个tensor相加
print(x + y)
print(torch.add(x, y))
print(x.add(y))
# tensor([5, 7, 9])
x.add_(y)  # x 自身累加  

 乘法

x = torch.tensor([[1, 2], [3, 4]])
y = torch.tensor([[1, 2], [1, 1]])

# tensor中每个元素乘2
z = torch.mul(x, 2)

print(torch.mm(x, y))
print(torch.matmul(x, y))
print(x@y)
print(x.mm(y))
# tensor([[ 3,  4],
#         [ 7, 10]])

 除法

x = torch.tensor([1, 2, 3.7])
y = torch.tensor([4, 5, 6.2])
print(torch.true_divide(y, x))
print(torch.div(y, x))
# tensor([4.0000, 2.5000, 1.6757])

 取整

x = torch.tensor([2.31, 9.9874, 4.501])

# 向下取整,只保留整数部分
print(x.floor())
print(x.trunc())
# tensor([2., 9., 4.])

# 向上取整,整数部分+1
print(x.ceil())
# tensor([ 3., 10.,  5.])

# 四舍五入
print(x.round())
# tensor([ 2., 10.,  5.])

# 只取小数部分
print(x.frac())
# tensor([0.3100, 0.9874, 0.5010])

取余

x1 = torch.tensor([2.31, 9.23, 3.501])
x2 = torch.tensor([2, 9, 35])
print(x1 % 2)
# tensor([0.3100, 1.2300, 1.5010])
print(x2 % 2)
# tensor([0, 1, 1])

3.3 乘方开方、对数运算

# 乘方运算(幂运算)
x = torch.tensor([2, 3])
print(torch.pow(x, 3))
print(x.__pow__(3))
print(x**3)
# tensor([ 8, 27])

# 开方运算
print(x.sqrt())
print(torch.sqrt(x))
# tensor([1.4142, 1.7321])

 对数运算

x = torch.tensor([2, 3])
print(torch.log2(x))
print(torch.log10(x))
print(torch.log(x))   # e

4. Tensor的变形与排序

4.1 变形(resize|reshape|view)

x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x.shape)
# torch.Size([2, 3])

print(x.resize(3, 2))
print(x.reshape(3, 2))
torch.reshape(x, (3, 2))
print(x.view(3, 2))
# tensor([[1, 2],
#         [3, 4],
#         [5, 6]])

print(x.shape)
# torch.Size([2, 3])

4.2 排序

# 获取单值tensor的值
x = torch.tensor([3.14])
print(x.item())
# 3.140000104904175

x = torch.tensor([[1, 5, 6], [4, 3, 2]])
# 默认升序
y = torch.sort(x, descending=True)
print(y.values)
# tensor([[6, 5, 1],
#         [4, 3, 2]])
# 返回排序后的值在原tensor中的索引
print(y.indices)
# tensor([[2, 1, 0],
#         [0, 1, 2]])

topK

x = torch.tensor([[1, 5, 6], [4, 3, 2], [8, 1, 9]])
# 沿着指定维度返回返回topK个数值及其索引, dim=0为列维度
y = torch.topk(x, k=2, dim=0, largest=True, sorted=True, out=None)
# 第一列最大为8,次大为4
print(y.values)
# tensor([[8, 5, 9],
#         [4, 3, 6]])
print(y.indices)
# tensor([[2, 0, 2],
#         [1, 1, 0]])

# 行维度升序top2
y = torch.topk(x, k=2, dim=1, largest=False, sorted=True, out=None)
print(y.values)
# tensor([[1, 5],
#         [2, 3],
#         [1, 8]])
print(y.indices)
# tensor([[0, 1],
#         [2, 1],
#         [1, 0]])

# 获取行维度,第k个最小值
print(y.values[:, 1])
# tensor([5, 3, 8])
y = torch.kthvalue(x, 1, dim=1)
print(y.values)
# tensor([5, 3, 8])
print(y.indices)
# tensor([1, 1, 0])

5. Tensor的X值

# 产生数值在1-99之间,3行3列的tensor
x = torch.randint(1, 99, (3, 3))
# tensor([[45, 59,  4],
#         [54, 68,  9],
#         [ 9, 11, 87]])

# 获取列最小值的索引
torch.argmin(x, dim=0)
# tensor([2, 2, 0])
# 获取行最大值的索引
torch.argmax(x, dim=1)
# tensor([1, 1, 2])

x = torch.tensor([1, 2, 3, 4], dtype=torch.float)
torch.mean(x)
torch.sum(x)
# 连乘
torch.prod(x)
# tensor(24.)
torch.max(x)

print(torch.std(x))
print(torch.var(x))
print(torch.median(x))   # 中位数
print(torch.mode(x))     # 众数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值