python遍歷迭代器自動鏈?zhǔn)教幚頂?shù)據(jù)的實(shí)例代碼
python遍歷迭代器自動鏈?zhǔn)教幚頂?shù)據(jù)
pytorch.utils.data可兼容迭代數(shù)據(jù)訓(xùn)練處理,在dataloader中使用提高訓(xùn)練效率:借助迭代器避免內(nèi)存溢出不足的現(xiàn)象、借助鏈?zhǔn)教幚硎沟脭?shù)據(jù)讀取利用更高效(可類比操作系統(tǒng)的資源調(diào)控)
書接上文,使用迭代器鏈?zhǔn)教幚頂?shù)據(jù),在Process類的__iter__方法中執(zhí)行掛載的預(yù)處理方法,可以嵌套包裹多層處理方法,類似KoaJs洋蔥模型,在for循環(huán)時(shí),自動執(zhí)行預(yù)處理方法返回處理后的數(shù)據(jù)
分析下述示例中輸入數(shù)據(jù)依次執(zhí)行順序:travel -> deep -> shuffle -> sort -> batch,實(shí)際由于嵌套循環(huán)或設(shè)置緩存的存在,數(shù)據(jù)流式會有變化,具體如后圖分析
from torch.utils.data import IterableDataset
# ...
import random
class Process(IterableDataset):
def __init__(self, data, f):
self.data = data
# 綁定處理函數(shù)
self.f = f
def __iter__(self):
# for循環(huán)遍歷時(shí),返回一個(gè)當(dāng)前環(huán)節(jié)處理的迭代器對象
return self.f(iter(self.data))
a = ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9']
b = ['b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9']
c = ['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9']
# data = [[j + str(i) for i in range(10)] for j in ['a','b', 'c'] ]
data = [a, b, c]
def travel(d):
for i in d:
# print('travel ', i)
yield i
def deep(d):
for arr in d:
for item in arr:
yield item
def shuffle(d, sf_size=5):
buf = []
for i in d:
buf.append(i)
if len(buf) >= sf_size:
random.shuffle(buf)
for j in buf:
# print('shuffle', j)
yield j
buf = []
for k in buf:
yield k
def sort(d):
buf = []
for i in d:
buf.append(i)
if len(buf) >= 3:
for i in buf:
# print('sort', i)
yield i
buf = []
for k in buf:
yield k
def batch(d):
buf = []
for i in d:
buf.append(i)
if len(buf) >= 16:
for i in buf:
# print('batch', i)
yield i
buf = []
# 對訓(xùn)練數(shù)據(jù)進(jìn)行的多個(gè)預(yù)處理步驟
dataset = Process(data, travel)
dataset = Process(dataset , deep)
dataset = Process(dataset , shuffle)
dataset = Process(dataset , sort)
train_dataset = Process(p, batch)
# 可在此處斷點(diǎn)測試
for i in p:
print(i, 'train')
# train_data_loader = DataLoader(train_dataset,num_workers=args.num_workers,prefetch_factor=args.prefetch)
# train(model , train_data_loader)
由上可以構(gòu)造數(shù)據(jù)流式方向 :batch(iter(sort(iter(shuffle(iter(deep(iter(travel(iter( d ))))))))))
根據(jù)數(shù)據(jù)流式抽取部分過程畫出時(shí)序圖如下:

附:python 手動遍歷迭代器
想遍歷一個(gè)可迭代對象中的所有元素,但是卻不想使用for 循環(huán)
為了手動的遍歷可迭代對象,使用next() 函數(shù)并在代碼中捕獲StopIteration 異常。比如,下面的例子手動讀取一個(gè)文件中的所有行
def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line = next(f)
print(line, end='')
except StopIteration:
pass
通常來講, StopIteration 用來指示迭代的結(jié)尾。然而,如果你手動使用上面演示的next() 函數(shù)的話,你還可以通過返回一個(gè)指定值來標(biāo)記結(jié)尾,比如None 。下面是示例:
with open('/etc/passwd') as f:
while True:
line = next(f)
if line is None:
break
print(line, end='')
大多數(shù)情況下,我們會使用for 循環(huán)語句用來遍歷一個(gè)可迭代對象。但是,偶爾也需要對迭代做更加精確的控制,這時(shí)候了解底層迭代機(jī)制就顯得尤為重要了。下面的交互示例向我們演示了迭代期間所發(fā)生的基本細(xì)節(jié):
>>> items = [1, 2, 3] >>> # Get the iterator >>> it = iter(items) # Invokes items.__iter__() >>> # Run the iterator >>> next(it) # Invokes it.__next__() 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
總結(jié)
到此這篇關(guān)于python遍歷迭代器自動鏈?zhǔn)教幚頂?shù)據(jù)的文章就介紹到這了,更多相關(guān)python自動鏈?zhǔn)教幚頂?shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在Python程序中操作文件之isatty()方法的使用教程
這篇文章主要介紹了在Python程序中操作文件之isatty()方法的使用教程,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
在pytorch中實(shí)現(xiàn)只讓指定變量向后傳播梯度
今天小編就為大家分享一篇在pytorch中實(shí)現(xiàn)只讓指定變量向后傳播梯度,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
基于Python實(shí)現(xiàn)身份證信息識別功能
身份證是用于證明個(gè)人身份和身份信息的官方證件,在現(xiàn)代社會中,身份證被廣泛應(yīng)用于各種場景,如就業(yè)、教育、醫(yī)療、金融等,它包含了個(gè)人的基本信息,本文給大家介紹了如何基于Python實(shí)現(xiàn)身份證信息識別功能,感興趣的朋友可以參考下2024-01-01
pytorch中關(guān)于distributedsampler函數(shù)的使用
這篇文章主要介紹了pytorch中關(guān)于distributedsampler函數(shù)的使用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Python中如何控制小數(shù)點(diǎn)精度與對齊方式
在 Python 編程中,數(shù)據(jù)輸出格式化是一個(gè)常見的需求,尤其是在涉及到小數(shù)點(diǎn)精度和對齊方式時(shí),下面小編就來為大家介紹一下如何在 Python 中實(shí)現(xiàn)這些功能吧2025-03-03
Django數(shù)據(jù)庫表反向生成實(shí)例解析
這篇文章主要介紹了Django數(shù)據(jù)庫表反向生成實(shí)例解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02
python實(shí)現(xiàn)信號時(shí)域統(tǒng)計(jì)特征提取代碼
今天小編就為大家分享一篇python實(shí)現(xiàn)信號時(shí)域統(tǒng)計(jì)特征提取代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python2和Python3.6環(huán)境解決共存問題
這篇文章主要介紹了Python2和Python3.6環(huán)境解決共存問題,需要的朋友可以參考下2018-11-11
python中關(guān)于CIFAR10數(shù)據(jù)集的使用
這篇文章主要介紹了python中關(guān)于CIFAR10數(shù)據(jù)集的使用方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

