pytorch基础
‘nvidia-smi’ 不是內部或外部命令,也不是可運行的程序
參考博客
https://blog.csdn.net/shuiyixin/article/details/99897640
cuda9.2只支持driver version396.26以上的 如果不夠取升級驅動
pytorch的安裝
04學習法寶(package)
dir 和help可以幫助你看看package里面有什么
創建項目時選擇已有的環境 選擇基于conda下的pytorch虛擬環境 而不是新建虛擬環境
05 pycharm和jupyter book的對比
這三個運行區域的理解
06加載數據 dataset和dataloader
dataset是從數據海洋中獲取數據和其label
dataloader是把想要的數據打包
07dataset代碼實戰
如何獲取圖片:opencv獲取圖片的地址
將數據集放到pycharm的項目下 并復制圖片的路徑可以選擇絕對還是相對路徑 記得在windows下加\做完轉義符
在python console中這樣方便看img有什么屬性 from PIL import Image img_path='F:\\pythonProject1\\learn_pytorch\\dataset\\val\\ants\\800px-Meat_eater_ant_qeen_excavating_hole.jpg' img=Image.open(img_path) img.size Out[5]: (800, 534) img.show()#會彈窗展示圖片在python console控制臺 通過文件夾獲得文件夾下面所有的圖片 先獲得dir_path文件總路徑 再os.listdir(dir_path)獲得所有圖片的名稱
from PIL import Image img_path='F:\\pythonProject1\\learn_pytorch\\dataset\\val\\ants\\800px-Meat_eater_ant_qeen_excavating_hole.jpg' img=Image.open(img_path) img.size Out[5]: (800, 534) img.show() dir_path='dataset/val/ants' import os img_path_list=os.listdir(dir_path)#可以獲得每張圖片的名稱 img_path_list[0] Out[10]: '10308379_1b6c72e180.jpg' python consoleroot_dir='dataset/train' label_dir='ants' path=os.path.join(root_dir,label_dir)#因為/在不同系統下有不同的含義 所以就根據不同的系統自動把路徑用\\連接起來 path Out[14]: 'dataset/train\\ants' from torch.utils.data import Dataset from PIL import Image#使用這個方法讀取圖片 import os #self 相當于定義了全局變量 class MyData(Dataset):#繼承Dataset類 一般要重寫getitem和len函數def __init__(self,root_dir,label_dir):#初始化 一般定義一些全局變量self.root_dir=root_dir#相當指定一個全局變量self.label=label_dirself.path=os.path.join(self.root_dir,self.label)self.img_path=os.listdir(self.path)#讀取每個圖片def __getitem__(self,idx):#想獲得圖片地址 通過索引idx去獲取 就要先獲取所有圖片的一個list 所以通過idx就可以獲得相應圖片的地址 要用到os庫#img_path='dataset/val/ants/8124241_36b290d372.jpg'img_name=self.img_path[idx]img_item_path=os.path.join(self.root_dir,self.label,img_name)#每個圖片的地址都是這樣root_dir+label_dir+img_nameimg=Image.open(img_item_path)label=self.label_dir#label就是ants 里面放著都是螞蟻的圖片return img,labeldef __len__(self):return len(self.img_path)root_dir='dataset/train' ants_label_dir='ants' ants_dataset=MyData(root_dir,ants_label_dir)https://my.oschina.net/u/4392911/blog/4480137
安裝pytorch
https://blog.csdn.net/ljlchrr/article/details/84000908
python在指定文件夾下新建txt
07tensorboard的使用1
transform 對圖像數據進行統一的轉換或者類的轉化
SummaryWriter的使用 在pycharm按住ctrl 之后SummaryWriter變藍色 點擊即可
add_scalar用法 :
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):"""Add scalar data to summary. #添加一個標量數據到summaryArgs:tag (string): Data identifier#圖標標題scalar_value (float or string/blobname): Value to save#圖標數值 y軸global_step (int): Global step value to record#訓練到多少步的時候 對應的數值是多少 x軸walltime (float): Optional override default walltime (time.time())with seconds after epoch of eventExamples::from torch.utils.tensorboard import SummaryWriterwriter = SummaryWriter()x = range(100)for i in x:writer.add_scalar('y=2x', i * 2, i)writer.close()Expected result:.. image:: _static/img/tensorboard/add_scalar.png:scale: 50 %"""實例:
from torch.utils.tensorboard import SummaryWriterwriter=SummaryWriter('logs')#初始化實例 將創建的事件文件存在logs文件夾下#writer.add_image()for i in range(100):writer.add_scalar('y=2x',2*i,i)#分別是tag標題 y軸 x軸#在終端輸入tensorboard --logdir=logs --port=6007 打開這個event 可以指定端口號portwriter.close()當代碼改成writer.add_scalar(‘y=2x’,3*i,i) 會在y=2x下面產生如下情形,解決方法:刪除logs下的所有event重新執行
08tensorboard的使用2
add_image的使用:def add_image(self, tag, img_tensor, global_step=None, walltime=None, dataformats='CHW'):"""Add image data to summary.Note that this requires the ``pillow`` package.Args:tag (string): Data identifierimg_tensor (torch.Tensor, numpy.array, or string/blobname): Image data#注意這個類型是需要torch.Tensor, numpy.array, or string/blobname類型的global_step (int): Global step value to recordwalltime (float): Optional override default walltime (time.time())seconds after epoch of event將PIL 轉換成numpy類型的image
image_path='dataset/train/ants/0013035.jpg' from PIL import Image img=Image.open(image_path) print(type(img)) <class 'PIL.JpegImagePlugin.JpegImageFile'>import numpy as np img_array=np.array(img) print(type(img_array)) <class 'numpy.ndarray'>
效果如下
作用是訓練的時候可以看給模型提供了哪些數據,或者可以看出每個階段的訓練結果
09transforms的使用
transforms的結構和用法
給定特定格式的圖片經過一系列類轉換成要的圖片
ctrl+p可以看函數需要什么參數
from PIL import Image from torch.utils.tensorboard import SummaryWriter from torchvision import transforms#input img_path='dataset/train/ants/5650366_e22b7e1065.jpg' img=Image.open(img_path)writer=SummaryWriter('logs')#1transforms如何用 tensor_trans=transforms.ToTensor()#創建實例 tensor_img=tensor_trans(img)#PIL變tensorwriter.add_image('Tensor_img',tensor_img) writer.close()#2為什么需要tensor這個數據類型效果
常見的transforms
transforms的compose類 每次經過中心的裁剪 最后再ToTensor
totensor的使用
1打開圖片 2創建writer寫入事件 3創建實例調用totensor 4add_image
Normalize的使用
class Normalize(torch.nn.Module):"""Normalize a tensor image with mean and standard deviation.Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``channels, this transform will normalize each channel of the input``torch.*Tensor`` i.e.,``output[channel] = (input[channel] - mean[channel]) / std[channel]``.. note::This transform acts out of place, i.e., it does not mutate the input tensor.Args:mean (sequence): Sequence of means for each channel.std (sequence): Sequence of standard deviations for each channel.inplace(bool,optional): Bool to make this operation in-place."""def __init__(self, mean, std, inplace=False):super().__init__()self.mean = meanself.std = stdself.inplace = inplace
totensor和normalize的效果
resize的使用
class Resize(torch.nn.Module):"""Resize the input image to the given size.The image can be a PIL Image or a torch Tensor, in which case it is expectedto have [..., H, W] shape, where ... means an arbitrary number of leading dimensionsArgs:size (sequence or int): Desired output size. If size is a sequence like(h, w), output size will be matched to this. If size is an int,smaller edge of the image will be matched to this number.#如果只給一個數就是只有等比的縮放i.e, if height > width, then image will be rescaled to(size * height / width, size).In torchscript mode padding as single int is not supported, use a tuple orlist of length 1: ``[size, ]``.interpolation (int, optional): Desired interpolation enum defined by `filters`_.Default is ``PIL.Image.BILINEAR``. If input is Tensor, only ``PIL.Image.NEAREST``, ``PIL.Image.BILINEAR``and ``PIL.Image.BICUBIC`` are supported.""" #resize print(img.size) trans_reszie=transforms.Resize((512,512)) #img PIL ->resize ->img_resize PIL img_resize=trans_reszie(img) #img resize PIL ->totensor ->img_resize tensor img_resize=tensor_trans(img_resize) writer.add_image('Resize',img_resize,0) print(img_resize)compose用法
#randomcrop trans_random=transforms.Resize((500,1000))#指定hw 裁剪成500*1000 trans_compose_2=transforms.Compose([trans_random,tensor_trans]) for i in range(10):img_crop=trans_compose_2(img)writer.add_image('RandomCropHW',img_crop,i)#隨機裁剪0-9張方法總結
關注官方文檔,輸入輸出類型,關注方法需要什么參數
不知道返回值的時候print/print(type())/debug
總結
- 上一篇: 毕设资料整理
- 下一篇: Multimedia Event Ext