pytorch入门基础(一)背景和tensor用法

pytorch入门基础(一)背景和tensor用法

一.背景

人工智能、机器学习、神经网络、深度学习之间的关系为:
pytorch入门基础(一)背景和tensor用法_第1张图片
其中机器学习又细分为:
pytorch入门基础(一)背景和tensor用法_第2张图片
一些常用的深度学习框架:
pytorch入门基础(一)背景和tensor用法_第3张图片

二.pytorch及tensor

1.pytorch:
pytorch是一个开源的python机器学习库,基于torch,用于自然语言处理,计算机视觉等应用程序。它的好处在于它是相当简洁且高效快速的框架,入门简单;可以在运行时构建计算图,甚至在运行时更改他们;多gpu支持,自定义数据加载器和简化的预处理器。
2.tensor:
tensor张量
scalar(标量):一个数值
vector(向量):一维数组
matrix(矩阵):二维数组
tensor(张量):大于二维的数组,即多维数组
以下介绍一些用法:

  1. 验证变量是否为tensor
x = [2,9,5,16,23,35]
b = torch.is_tensor(x)
y = torch.rand(1,2)
print(b)  # False
print(y)  # tensor([[0.6934, 0.4522]])
print(torch.is_tensor(y))  # True
  1. 基本语法
torch.numel(y)  #  统计tensor中元素个数
torch.zeros(3,3)  # 创建全0的tensor
torch.eye(3,3)  # 创建对角线为1的tensor
torch.rand(10)  # 创建均匀分布,10个数都在0-1之间,输出为tensor格式
torch.randn(10)  # 创建正态分布,均值为0,方差为1,输出为tensor格式
torch.randperm(10) # 将0-9共10个数字随机打乱,然后以tensor形式输出
torch.randint(1,99,(3,3))  # 在1-99之间随机选取整数,组成3*3的tensor
torch.arange(10,30,5)  # 从10到30,以5分割取值,不包括30,tensor([10,15,20,25]
  1. 将numpy转换为tensor
x = np.array([3,4,5,6,7])
print(torch.from_numpy(x))  # tensor([3, 4, 5, 6, 7], dtype=torch.int32)
  1. 切分
# 2-10切成10,2和10分别作为第一个和最后一个数字,包含10
print(torch.linspace(2,10,steps=10))  # tensor([2.0000,2.8889,3.7778,4.6667,5.5556,6.4444,7.3333,8.2222,9.1111,10.0000])
  1. 获取行或列的最小值和最大值的索引
# 注意dim=0表示列,dim=1表示行
x = torch.randint(1,99,(3,3))
print(x)  # tensor([[98, 37, 23],
                  # [61, 35, 20],
                  # [14, 64, 94]])
print(torch.argmin(x,dim=0))  # 每列最小的索引tensor([2, 1, 1])
print(torch.argmax(x,dim=0))  # 每列最大的索引tensor([0, 2, 2])
  1. 连接
x = torch.randint(1,9,(2,3))
print(torch.cat((x,x)))  # tensor([[6, 8, 8],
                                # [6, 1, 5],
                                # [6, 8, 8],
                                # [6, 1, 5]])
print(torch.cat((x,x),dim=1))  # tensor([[6, 8, 8, 6, 8, 8],  
                                   #    [6, 1, 5, 6, 1, 5]])
  1. chunk切块
torch.chunk(a,2,0)  # 横向索引切片
torch.chunk(a,2,1)  # 纵向索引切片
  1. index_select根据索引选择
    pytorch入门基础(一)背景和tensor用法_第4张图片
  2. 分割
x = torch.tensor([1,2,3,4,5,6,7])
print(torch.split(x,3))  # (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7]))
  1. 转置 x.t()
    pytorch入门基础(一)背景和tensor用法_第5张图片
  2. tensor加法和乘法
    pytorch入门基础(一)背景和tensor用法_第6张图片

你可能感兴趣的:(pytorch基础学习,人工智能,python,机器学习,深度学习,pytorch)