① Python3.6.3相当于一个package,package里面有不同的区域,不同的区域有不同的工具。
② Python语法有两大法宝:dir()、help() 函数。
import torch
print(torch.cuda.is_available())
help(torch.cuda.is_available) # 查看 torch.cuda.is_available 的用法
dir(torch) # 查看torch包中有哪些区、有哪些工具
True
Help on function is_available in module torch.cuda:
is_available() -> bool
Returns a bool indicating if CUDA is currently available.
Output exceeds the size limit. Open the full output data in a text editor
['AVG',
'AggregationType',
'AliasDb',
'AnyType',
'Argument',
'ArgumentSpec',
'BFloat16Storage',
'BFloat16Tensor',
'BenchmarkConfig',
'BenchmarkExecutionStats',
'Block',
'BoolStorage',
'BoolTensor',
'BoolType',
'BufferDict',
'ByteStorage',
'ByteTensor',
'CONV_BN_FUSION',
'CallStack',
'Capsule',
'CharStorage',
'CharTensor',
'ClassType',
'Code',
'CompilationUnit',
...
'rrelu',
'rrelu_',
'rsqrt',
'rsqrt_',
...]
① Pytorch中加载数据需要Dataset、Dataloader。
① 常用的第一种数据形式,文件夹的名称是它的label。
② 常用的第二种形式,lebel为文本格式,文本名称为图片名称,文本中的内容为对应的label。
from torch.utils.data import Dataset
help(Dataset)
from PIL import Image
img_path = "Data/FirstTypeData/train/ants/0013035.jpg"
img = Image.open(img_path)
img.show()
主要是封装成类,可以单独分离为文件,主要是集成Dataset类,注意__inint__(),getitem()和__len__()三个方法的实现,可作为自定义加载数据集的模板。
from torch.utils.data import Dataset
from PIL import Image
import os
class MyData(Dataset):
def __init__(self,root_dir,label_dir): # 该魔术方法当创建一个事例对象时,会自动调用该函数
self.root_dir = root_dir # self.root_dir 相当于类中的全局变量
self.label_dir = label_dir
self.path = os.path.join(self.root_dir,self.label_dir) # 字符串拼接,根据是Windows或Lixus系统情况进行拼接
self.img_path = os.listdir(self.path) # 获得路径下所有图片的地址
def __getitem__(self,idx):
img_name = self.img_path[idx]
img_item_path = os.path.join(self.root_dir,self.label_dir,img_name)
img = Image.open(img_item_path)
label = self.label_dir
return img, label
def __len__(self):
return len(self.img_path)
root_dir = "Data/FirstTypeData/train"
ants_label_dir = "ants"
bees_label_dir = "bees"
ants_dataset = MyData(root_dir, ants_label_dir)
bees_dataset = MyData(root_dir, bees_label_dir)
print(len(ants_dataset))
print(len(bees_dataset))
train_dataset = ants_dataset + bees_dataset # train_dataset 就是两个数据集的集合了
print(len(train_dataset))
img,label = train_dataset[200]
print("label:",label)
img.show()