傳統(tǒng)方式需要10s,dat方式需要0.6s
import os
import time
import torch
import random
from common.coco_dataset import COCODataset
def gen_data(batch_size,data_path,target_path):
os.makedirs(target_path,exist_ok=True)
dataloader = torch.utils.data.DataLoader(COCODataset(data_path,
(352, 352),
is_training=False, is_scene=True),
batch_size=batch_size,
shuffle=False, num_workers=0, pin_memory=False,
drop_last=True) # DataLoader
start = time.time()
for step, samples in enumerate(dataloader):
images, labels, image_paths = samples["image"], samples["label"], samples["img_path"]
print("time", images.size(0), time.time() - start)
start = time.time()
# torch.save(samples,target_path+ '/' + str(step) + '.dat')
print(step)
def cat_100(target_path,batch_size=100):
paths = os.listdir(target_path)
li = [i for i in range(len(paths))]
random.shuffle(li)
images = []
labels = []
image_paths = []
start = time.time()
for i in range(len(paths)):
samples = torch.load(target_path + str(li[i]) + ".dat")
image, label, image_path = samples["image"], samples["label"], samples["img_path"]
images.append(image.cuda())
labels.append(label.cuda())
image_paths.append(image_path)
if i % batch_size == batch_size - 1:
images = torch.cat((images), 0)
print("time", images.size(0), time.time() - start)
images = []
labels = []
image_paths = []
start = time.time()
i += 1
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = '3'
batch_size=320
# target_path='d:/test_1000/'
target_path='d:\img_2/'
data_path = r'D:\dataset\origin_all_datas\_2train'
gen_data(batch_size,data_path,target_path)
# get_data(target_path,batch_size)
# cat_100(target_path,batch_size)
這個(gè)讀取數(shù)據(jù)也比較快:320 batch_size 450ms
def cat_100(target_path,batch_size=100):
paths = os.listdir(target_path)
li = [i for i in range(len(paths))]
random.shuffle(li)
images = []
labels = []
image_paths = []
start = time.time()
for i in range(len(paths)):
samples = torch.load(target_path + str(li[i]) + ".dat")
image, label, image_path = samples["image"], samples["label"], samples["img_path"]
images.append(image)#.cuda())
labels.append(label)#.cuda())
image_paths.append(image_path)
if i % batch_size batch_size - 1:
i += 1
continue
i += 1
images = torch.cat(([image.cuda() for image in images]), 0)
print("time", images.size(0), time.time() - start)
images = []
labels = []
image_paths = []
start = time.time()
補(bǔ)充:pytorch數(shù)據(jù)加載和處理問題解決方案
最近跟著pytorch中文文檔學(xué)習(xí)遇到一些小問題,已經(jīng)解決,在此對這些錯(cuò)誤進(jìn)行記錄:
在讀取數(shù)據(jù)集時(shí)報(bào)錯(cuò):
AttributeError: 'Series' object has no attribute 'as_matrix'
在顯示圖片是時(shí)報(bào)錯(cuò):
ValueError: Masked arrays must be 1-D
顯示單張圖片時(shí)figure一閃而過
在顯示多張散點(diǎn)圖的時(shí)候報(bào)錯(cuò):
TypeError: show_landmarks() got an unexpected keyword argument 'image'
解決方案
主要問題在這一行: 最終目的是將Series轉(zhuǎn)為Matrix,即調(diào)用np.mat即可完成。
修改前
landmarks =landmarks_frame.iloc[n, 1:].as_matrix()
修改后
landmarks =np.mat(landmarks_frame.iloc[n, 1:])
打散點(diǎn)的x和y坐標(biāo)應(yīng)該均為向量或列表,故將landmarks后使用tolist()方法即可
修改前
plt.scatter(landmarks[:,0],landmarks[:,1],s=10,marker='.',c='r')
修改后
plt.scatter(landmarks[:,0].tolist(),landmarks[:,1].tolist(),s=10,marker='.',c='r')
前面使用plt.ion()打開交互模式,則后面在plt.show()之前一定要加上plt.ioff()。這里直接加到函數(shù)里面,避免每次plt.show()之前都用plt.ioff()
修改前
def show_landmarks(imgs,landmarks):
'''顯示帶有地標(biāo)的圖片'''
plt.imshow(imgs)
plt.scatter(landmarks[:,0].tolist(),landmarks[:,1].tolist(),s=10,marker='.',c='r')#打上紅色散點(diǎn)
plt.pause(1)#繪圖窗口延時(shí)
修改后
def show_landmarks(imgs,landmarks):
'''顯示帶有地標(biāo)的圖片'''
plt.imshow(imgs)
plt.scatter(landmarks[:,0].tolist(),landmarks[:,1].tolist(),s=10,marker='.',c='r')#打上紅色散點(diǎn)
plt.pause(1)#繪圖窗口延時(shí)
plt.ioff()
網(wǎng)上說對于字典類型的sample可通過 **sample的方式獲取每個(gè)鍵下的值,但是會報(bào)錯(cuò),于是把輸入寫的詳細(xì)一點(diǎn),就成功了。
修改前
修改后
show_landmarks(sample['image'],sample['landmarks'])
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- pytorch加載語音類自定義數(shù)據(jù)集的方法教程
- pytorch加載自己的圖像數(shù)據(jù)集實(shí)例
- PyTorch加載自己的數(shù)據(jù)集實(shí)例詳解
- Pytorch自己加載單通道圖片用作數(shù)據(jù)集訓(xùn)練的實(shí)例
- Pytorch 數(shù)據(jù)加載與數(shù)據(jù)預(yù)處理方式
- pytorch 自定義數(shù)據(jù)集加載方法
- pytorch從csv加載自定義數(shù)據(jù)模板的操作