国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

PyTorch讀取Cifar數據集并顯示圖片的實例講解

2020-02-15 22:33:45
字體:
來源:轉載
供稿:網友

首先了解一下需要的幾個類所在的package

from torchvision import transforms, datasets as dsfrom torch.utils.data import DataLoaderimport matplotlib.pyplot as pltimport numpy as np#transform = transforms.Compose是把一系列圖片操作組合起來,比如減去像素均值等。#DataLoader讀入的數據類型是PIL.Image#這里對圖片不做任何處理,僅僅是把PIL.Image轉換為torch.FloatTensor,從而可以被pytorch計算transform = transforms.Compose( [ transforms.ToTensor() ])

Step 1,得到torch.utils.data.Dataset實例。

torch.utils.data.Dataset是一個抽象類,CIFAR100是它的一個實例化子類

train=True,讀取訓練集;train=False,讀取測試集

download=False,不下載。如果為True,則先檢查root下有無該數據集,如果沒有就先下載。

train_set = ds.CIFAR100(root='.', train=True, transform=transform, target_transform=None, download=True)

Step 2,把Dataset封裝成torch.utils.data.DataLoader

data_loader = DataLoader(dataset=train_set,  batch_size=1,  shuffle=False,  num_workers=2)# # 生成torch.utils.data.DataLoaderIter# # 不過DataLoaderIter它會被DataLoader自動創建并且調用,我們用不到# data_iter = iter(data_loader)# images, labels = next(data_iter)

step 3,從DataLoader里讀取數據,并將圖片顯示出來。

注意:

1)使用for...in...循環讀取數據的時候,會自動調用DataLoader里的__next__()函數

而且只能對Tensor實例進行迭代,所以之前的transforms必須最后加一個transforms.ToTensor()

2)顯示圖片有兩種方式:Image.show()和plt.imshow(ndarray)

Image.show():

通過transforms.ToPILImage()把FloatTensor轉化為Image

plt.imshow(ndarray):

通過FloatTensor.numpy()轉化為ndarray,再調用plt.imshow()

to_pil_image = transforms.ToPILImage()cnt = 0for image,label in data_loader: if cnt>=3: # 只顯示3張圖片 break print(label) # 顯示label # 方法1:Image.show() # transforms.ToPILImage()中有一句 # npimg = np.transpose(pic.numpy(), (1, 2, 0)) # 因此pic只能是3-D Tensor,所以要用image[0]消去batch那一維 img = to_pil_image(image[0]) img.show() # 方法2:plt.imshow(ndarray) img = image[0] # plt.imshow()只能接受3-D Tensor,所以也要用image[0]消去batch那一維 img = img.numpy() # FloatTensor轉為ndarray img = np.transpose(img, (1,2,0)) # 把channel那一維放到最后 # 顯示圖片 plt.imshow(img) plt.show() cnt += 1

另外補一句np.transpose()的用法。

第一個參數是要transpose的圖片;

第二個是shape。比如一個ndarray是(channel, height, width),如果給第二個參數(height, width,channel),就會把第0維channel整個搬到最后。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新建县| 大城县| 台州市| 滨海县| 淮北市| 财经| 洛川县| 滕州市| 洪江市| 游戏| 遂溪县| 革吉县| 志丹县| 高要市| 乌拉特前旗| 密山市| 冀州市| 永平县| 苍山县| 丰原市| 新建县| 增城市| 河源市| 遂溪县| 昌邑市| 抚远县| 盐山县| 庄河市| 志丹县| 沅陵县| 保德县| 东宁县| 蓬溪县| 永安市| 波密县| 花莲市| 潼关县| 承德县| 五寨县| 黔西县| 昭苏县|