0

我有一个 python 数据生成器-

import numpy as np
import tensorflow as tf

vocab_size = 5
def create_generator():
    'generates sequences of varying lengths(5 to 7) with random number from 0 to voca_size-1'
    count = 0
    while count < 5:
        sequence_len = np.random.randint(5, 8) # length varies from 5 to 7
        seq = np.random.randint(0, vocab_size, (sequence_len))
        yield seq
        count +=1

gen = tf.data.Dataset.from_generator(create_generator, 
                             args=[], 
                             output_types=tf.int32, 
                             output_shapes = (None, ), )

for g in gen:
    print(g)

它生成具有从 0 到 4 的整数值的不同长度(5 到 8)的序列。以下是生成器生成的一些序列 -

tf.Tensor([4 0 0 1 4 1], shape=(7,), dtype=int32) # 1st sequence
tf.Tensor([3 4 4 4 0], shape=(5,), dtype=int32)   # 2nd sequence
tf.Tensor([4 4 2 1 4 3], shape=(5,), dtype=int32) # 3rd sequence
tf.Tensor([1 0 2 4 0], shape=(7,), dtype=int32)   # 4th sequence
tf.Tensor([1 4 0 2 2], shape=(6,), dtype=int32)   # 5th sequence

现在我想以这样的方式修改序列 -

  • 从每个序列中删除所有偶数
  • 长度<2的序列(删除所有偶数后)被过滤掉

这应该给我们一个看起来像这样的结果 -

[1 1] # 1st sequence
[1 3] # 3rd sequence

如何使用tf.data.Dataset方法进行此类转换?

4

1 回答 1

0

您的for循环应如下所示:

new_gen = []
for g in gen:
    arr = np.array(g) % 2 != 0: 
    if len(list(arr)) >= 2:
        new_gen.append(arr)

print(new_gen)
于 2020-11-17T06:46:06.297 回答