python遍历迭代器自动链式处理数据的实例代码

作者:365/24/60 时间:2022-04-12 18:38:29 

python遍历迭代器自动链式处理数据

pytorch.utils.data可兼容迭代数据训练处理,在dataloader中使用提高训练效率:借助迭代器避免内存溢出不足的现象、借助链式处理使得数据读取利用更高效(可类比操作系统的资源调控)

书接上文,使用迭代器链式处理数据,在Process类的__iter__方法中执行挂载的预处理方法,可以嵌套包裹多层处理方法,类似KoaJs洋葱模型,在for循环时,自动执行预处理方法返回处理后的数据

分析下述示例中输入数据依次执行顺序:travel -> deep -> shuffle -> sort -> batch,实际由于嵌套循环或设置缓存的存在,数据流式会有变化,具体如后图分析

from torch.utils.data import IterableDataset
# ...

import random

class Process(IterableDataset):
   def __init__(self, data, f):
       self.data = data
       # 绑定处理函数
       self.f = f  
   def __iter__(self):
       # for循环遍历时,返回一个当前环节处理的迭代器对象
       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 = []
# 对训练数据进行的多个预处理步骤
dataset = Process(data, travel)
dataset = Process(dataset , deep)
dataset = Process(dataset , shuffle)
dataset = Process(dataset , sort)
train_dataset = Process(p, batch)

# 可在此处断点测试
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)

由上可以构造数据流式方向 :batch(iter(sort(iter(shuffle(iter(deep(iter(travel(iter( d ))))))))))

根据数据流式抽取部分过程画出时序图如下:

python遍历迭代器自动链式处理数据的实例代码

附:python 手动遍历迭代器

想遍历一个可迭代对象中的所有元素,但是却不想使用for 循环

为了手动的遍历可迭代对象,使用next() 函数并在代码中捕获StopIteration 异常。比如,下面的例子手动读取一个文件中的所有行

def manual_iter():
   with open('/etc/passwd') as f:
       try:
           while True:
               line = next(f)
               print(line, end='')
       except StopIteration:
           pass

通常来讲, StopIteration 用来指示迭代的结尾。然而,如果你手动使用上面演示的next() 函数的话,你还可以通过返回一个指定值来标记结尾,比如None 。下面是示例:

with open('/etc/passwd') as f:
   while True:
       line = next(f)
       if line is None:
           break
   print(line, end='')

大多数情况下,我们会使用for 循环语句用来遍历一个可迭代对象。但是,偶尔也需要对迭代做更加精确的控制,这时候了解底层迭代机制就显得尤为重要了。下面的交互示例向我们演示了迭代期间所发生的基本细节:

>>> 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
>>>

来源:https://www.cnblogs.com/lhx9527/p/15757646.html

标签:python,遍历,迭代器
0
投稿

猜你喜欢

  • jQuery中文入门教程

    2007-12-09 19:20:00
  • Python实现子类调用父类的初始化实例

    2023-09-20 00:25:27
  • Python使用graphviz画流程图过程解析

    2022-06-19 06:45:18
  • python3实现用turtle模块画一棵随机樱花树

    2023-11-30 06:04:07
  • 解决图片撑大问题

    2009-09-22 14:51:00
  • asp如何显示数据库中的图片和超级链接?

    2010-06-08 09:38:00
  • 如何用python批量发送工资条邮件

    2021-03-07 10:53:09
  • 在Win 2003中配置ASP.net环境

    2007-10-14 12:02:00
  • 如何给windows设置定时任务并运行python脚本

    2023-09-18 13:40:19
  • 巧用CSS滤镜做图案文字

    2011-04-29 14:06:00
  • python multiply()与dot使用示例讲解

    2021-08-14 19:34:52
  • python字符串不可变数据类型

    2021-04-14 23:07:09
  • oracle 动态AdvStringGrid完美示例 (AdvStringGrid使用技巧/Cells)

    2009-06-19 17:21:00
  • 判定IE的各个版本

    2010-01-19 14:01:00
  • Python中pandas dataframe删除一行或一列:drop函数详解

    2021-07-09 16:46:47
  • 一文秒懂pandas中iloc()函数

    2023-07-31 18:20:42
  • 2011年网页设计发展趋势

    2011-01-10 20:45:00
  • python中的内置函数getattr()介绍及示例

    2023-01-15 19:16:46
  • [图]关于网站开发中缓存 cache应用

    2008-08-19 18:14:00
  • Python列表生成器的循环技巧分享

    2023-10-06 21:24:28
  • asp之家 网络编程 m.aspxhome.com