pytorch
环境准备
# 我用的版本:python: 3.9.7, torch: v1.10.0, torchvision: 0.11.0
$ pip3 install torch,torchvision张量(Tensor)
常数是 0 阶张量。
向量 vevtor 是 1 阶张量。
矩阵 matrix 是 2 阶张量。
三维形状的就是 3 阶张量。
创建张量
import torch
import numpy as np
t1 = torch.tensor((1, 2, 3))
print(t1) # tensor([1., 2., 3.])
# 用 api 创建,每个数值都是0-10的随机整数,形状是3*4
t2 = torch.randint(low=0, high=10, size=(3, 4))
print(t2)
# tensor([[7, 0, 4, 0],
# [3, 7, 5, 9],
# [6, 9, 5, 0]])
# 可以把 torch 的 Tensor 转换成 numpy 的 Array
print(t2.numpy())
# [[7 0 4 0]
# [3 7 5 9]
# [6 9 5 0]]
array1 = np.arange(12).reshape(3, 4)
print(array1)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# 可以把 numpy 的 Array 转换成 torch 的 Tensor
print(torch.tensor(array1))
# tensor([[ 0., 1., 2., 3.],
# [ 4., 5., 6., 7.],
# [ 8., 9., 10., 11.]])常用API
torch.max(input, dim)
在分类问题中,通常需要使用max()函数对softmax函数的输出值进行操作,求出预测值索引,然后与标签进行比对,计算准确率。
输入:
input是softmax函数输出的一个tensordim是max函数索引的维度0/1,0是每列的最大值,1是每行的最大值。
输出:
函数会返回两个tensor,第0个tensor是每行的最大值(不用关心这个值);第1个tensor是每行最大值的索引,也就是预测的这组样本中每个样本最大概率的类别的索引,然后根据该索引即可取出对应的类别。
示例
训练
预测
Last updated
Was this helpful?