【问题标题】:Python - Generator within another generatorPython - 另一个生成器中的生成器
【发布时间】:2019-11-08 22:50:42
【问题描述】:

我必须在另一个生成器中使用一个生成器的输出。

下面是代码 -

这里 Generator 2 在 generator 1 中被调用,最终的输出是从 generator 2 接收到的。

我正在尝试使用类似下面的东西,有人可以提出解决方案吗?

def sub_gen(data) : for r in res_gen() : yield each train_datagen(r)

发电机 1

def res_gen (num_threads = 4 ):
    while (True) :
      for i in range(0,len(file_list),num_threads):
        # use multi-process to speed up
        res = []
        p = Pool(num_threads)
        patch = p.map(gen_patches,file_list[i:min(i+num_threads,len(file_list))])
        #patch = p.map(gen_patches,file_list[i:i+num_threads])
        for x in patch:
            res += x
        res1 = np.array(res)
        res1 = res1.reshape((res1.shape[0],res1.shape[1],res1.shape[2],1))
        res1 = res1.astype('float32')/255.0
        yield res1

发电机 2

def train_datagen(res1, batch_size=4):
    indices = list(range(res1.shape[0]))
    while(True):
        np.random.shuffle(indices)    # shuffle
        for i in range(0, len(indices), batch_size):
            ge_batch_y = res1[indices[i:i+batch_size]]
            noise =  np.random.normal(0, sigma/255.0, ge_batch_y.shape)   
            #noise =  K.random_normal(ge_batch_y.shape, mean=0, stddev=sigma/255.0)
            ge_batch_x = ge_batch_y + noise  # input image = clean image + noise
            yield ge_batch_x, ge_batch_y

【问题讨论】:

  • 你所拥有的究竟是什么问题?
  • 我必须在生成器 2 中调用生成器 1 的输出。
  • 所以你想要一台发电机来完成你现有发电机的工作?
  • 您是否正在寻找yield from,而您目前有yield each(这将是一个错误)?
  • @Blckknght - yield from 将输出 2 个单独的生成器结果。我想在生成器 1 中循环生成器 2,最终结果来自生成器 2。

标签: python


【解决方案1】:

我很确定您的简短 sub_gen 生成器中唯一的问题是您编写了 yield each 而不是 yield from。后者期望在它之后有一个可迭代的值(通常是另一个生成器),并且它像显式 for 循环一样产生每个值

所以我认为你的代码应该是:

def sub_gen(data) :
  for r in res_gen() :
      yield from train_datagen(r)

让我们用更简单的生成器函数来测试一下:

def foo():
    yield [1, 2]
    yield [3, 4]

def bar(iterable):
    for x in iterable:
        yield 10+x
        yield 20+x

def baz():
    for iterable in foo():
        yield from bar(iterable)

for value in baz():   # use the top-level generator!
    print(value)      # prints 11, 21, 12, 22, 13, 23, 14, 24 each on its own line

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 2011-09-09
    • 2020-10-10
    • 2012-07-15
    • 2013-10-02
    • 2018-11-16
    • 2010-12-28
    • 2015-01-16
    • 2011-04-17
    相关资源
    最近更新 更多