一、软件安装
1、查看当前计算机是否具有cuda
nvidia-smi # 去检查当前设备是否有cuda

当CUDA存在时,则显示有cuda,可以安装cuda版本的pytorch
2、在pytorch官网下载pytorch
https://pytorch.org/get-started/previous-versions/
查找对应版本的pytorch

二、基础语法
1. 创建tensor
import torch
torch.Tensor(5) # 创建size[5]的随机张量
torch.Tensor((3,4)) # 创建指定形状的张量
1.1传入不同的数据(数字,列表,数组)
torch.tensor(5)
torch.tensor([1,2,3])
torch.tensor(np.array([1,2,3]))
1.2创建指定张量中的数据的类型
torch.tensor(5,dtype = torch.int8)
torch.IntTensor(5)
tensor.FloatTensor(5)
Double / LongTensor / ShortTensor == 64 32 16
1.2指定设备
torch.tensor(device = 'cuda)
data = torch.tensor(5)
data = data.to("cuda") # 返回一个数据
data.to("cuda" if torch.cuda.is_avaliable() else "cpu") # cuda 判断函数
2.创建指定张量
2.1全01单位矩阵张量
torch.ones((3,4))
torch.zeros((3,4))
torch.full((3,4),4) # 创建3*4 的张量 填充按4进行数据填充
2.2随机
torch.rand() # 创建随机形状的张量
torch.randn() # 创建标准类型的方差张量
torch.normalize(mean=,std = )
2.3线性
torch.linspace(start,stop,number)
torch.range(start,stop,step)
torch.logspace(start,stop,number,base)
3.根据别的张量创建张量
data = torch.ones(3,4)
data1 = torch.zeros_like(data)
data2 = torch.zeros_like(data1)
data3 = torch.full_like(data2)
4.张量转化设备
data = torch.tensor([1,2,3],device = 'cuda')
data = torch.tensor([1,2,3],dedvice = 'cpu')
# 运行设备的转换
data = data.to("cuda") # 会返回一个新的张量
# 判断函数
data.to("cuda" if torch.cuda.is_available() else "cpu")
5.numpy与张量
arr = np.array([1,2,3])
data = torch.tensor(arr) # 将arr转换为张量 == 数据内存不公用
arr[1] = 222
print(data) # [1,2,3]
data = torch.tensor([1,2,3]) # 数据结构公用
arr = data.numpy()
arr[1] = 55
print(arr)
print(data)
numpy 与 tensor 数据结构的公用
arr = np.array([1,2,3,4,5])
data = torch.from_numpy(arr) # tensor 数据来源为 numpy 数据结构公用
arr[1] = 55
print(data)
6.PIL图像对象
from PIL import Image
from torchvision import transforms
# 创建转换工具
trans = transforms.ToTensor() # 将numpy 图像 转换为 tensor数据
data = trans(image)
trans = transforms.ToPILImage() # 将tensor张量转换为image图像 进行
image = trans(data)
# opencv 读取图像为BGR图像数据 (h,w,c)
# PIL 读取图像 # 读取的图像数据为 RGB图像 (c,h,w)
path = r'path'
image = Image.open(path)
image.show()
image.save('path')

3729

被折叠的 条评论
为什么被折叠?



