PyTorch基础与认识

一、软件安装

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.101单位矩阵张量
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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值