180411 利用python自定义batch-generator批量数据生成器

34 篇文章 0 订阅
25 篇文章 0 订阅

简单思路演示代码

  • 简单代码演示,基本思路(实际中需要像后面代码一样先洗牌,且每次shuffer后顺序不同)
a = np.arange(100)

def batch_gen(data):  # 定义batch数据生成器
    idx = 0
    while True:
        if idx+10>100:
            idx=0
        start = idx
        idx += 10
        yield data[start:start+10]

gen = batch_gen(a)

for i in range(20):
    b = next(gen)  # 在循环中利用next()函数调用batch数据
    print(b)
  • 代码运行结果
[0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]
[0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29]
[30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49]
[50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69]
[70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89]
[90 91 92 93 94 95 96 97 98 99]

实际batch-generator代码

  • 定义批量数据生成器
def shuffle_aligned_list(data):
    """Shuffle arrays in a list by shuffling each array identically."""
    num = data[0].shape[0]
    p = np.random.permutation(num)
    return [d[p] for d in data]

def batch_generator(data, batch_size, shuffle=True):
    """Generate batches of data.

    Given a list of array-like objects, generate batches of a given
    size by yielding a list of array-like objects corresponding to the
    same slice of each input.
    """
    if shuffle:
        data = shuffle_aligned_list(data)

    batch_count = 0
    while True:
        if batch_count * batch_size + batch_size > len(data[0]):
            batch_count = 0

            if shuffle:
                data = shuffle_aligned_list(data)

        start = batch_count * batch_size
        end = start + batch_size
        batch_count += 1
        yield [d[start:end] for d in data]
  • 实例化批量数据生成器
# make data
x = np.arange(1,51).reshape((10,5))
y = np.arange(1,11).reshape((-1,1))

# define epochs and batch_size
batch_size = 5
epochs_num = (len(x)//batch_size)*epochs

# define generator
batch_gen = batch_generator([x,y],batch_size) # assign batch_gen as batch generator
  • 利用next()循环语句中调用gen
for i in range(20):
    batch_x,batch_y = next(batch_gen)
    if int(i%2)==0:
        print('Epoch %d'%int(i/2))
    print('The %d Batch_y:\n '%(i+1),batch_y.reshape((1,-1)),'\n')
Epoch 1
The 1 Batch_y:
  [[ 5  2  7 10  4]] 

The 2 Batch_y:
  [[1 3 6 9 8]] 

Epoch 2
The 3 Batch_y:
  [[2 3 6 8 1]] 

The 4 Batch_y:
  [[ 5  9 10  4  7]] 

Epoch 3
The 5 Batch_y:
  [[ 2 10  1  3  8]] 

The 6 Batch_y:
  [[7 9 6 5 4]] 

Epoch 4
The 7 Batch_y:
  [[2 4 5 3 6]] 

The 8 Batch_y:
  [[ 1  7  9  8 10]] 

Epoch 5
The 9 Batch_y:
  [[10  4  7  5  2]] 

The 10 Batch_y:
  [[1 8 9 6 3]] 

Epoch 6
The 11 Batch_y:
  [[6 3 8 9 7]] 

The 12 Batch_y:
  [[ 1 10  2  4  5]] 

Epoch 7
The 13 Batch_y:
  [[1 3 4 5 8]] 

The 14 Batch_y:
  [[ 9  6  7 10  2]] 

Epoch 8
The 15 Batch_y:
  [[ 7 10  5  2  9]] 

The 16 Batch_y:
  [[6 4 3 1 8]] 

Epoch 9
The 17 Batch_y:
  [[ 3 10  2  4  8]] 

The 18 Batch_y:
  [[5 6 1 7 9]] 

Epoch 10
The 19 Batch_y:
  [[ 1  4  7 10  3]] 

The 20 Batch_y:
  [[8 9 6 5 2]]
### 回答1: 可以使用 Python 的元编程技术,利用函数工厂来批量生成大量函数。以下是一个示例代码: ```python def make_function(n): def func(): print(f"This is function {n}") return func for i in range(10): function_name = f"function_{i}" globals()[function_name] = make_function(i) # 调用生成的函数 function_0() function_1() function_2() # ... ``` 这段代码中,`make_function` 函数是一个函数工厂,用于生成新的函数。在循环中,我们通过 `globals()` 函数将生成的函数添加到全局命名空间中,从而可以在其他代码中调用这些函数。 ### 回答2: Python中可以用循环结构批量生成大量函数。以下是一个示例代码: ```python def generate_functions(num): for i in range(num): exec(f"def func_{i+1}():\n print('This is function {i+1}')") # 调用函数生成10个函数 generate_functions(10) # 调用生成的函数 func_1() # 输出:This is function 1 func_2() # 输出:This is function 2 # ...... func_10() # 输出:This is function 10 ``` 在上述代码中,`generate_functions(num)`是一个生成函数的函数,`num`为要生成的函数的数量。在循环中,使用了`exec()`函数动态地执行字符串形式的函数定义代码,通过`f-string`的方式生成了不同名称的函数。每个生成的函数都会输出对应的函数编号。 通过调用`generate_functions(num)`函数,我们可以根据需要生成任意数量的函数。然后,我们可以直接调用生成的函数,每个函数的名称都带有对应的函数编号。 注意:批量生成函数会导致全局命名空间中存在大量的函数变量,这可能会对代码的可读性和维护性造成影响。因此,在实际应用中需要谨慎使用和管理这些函数。 ### 回答3: 在Python中,可以使用装饰器和循环来批量生成大量函数。 装饰器是Python中用来修饰函数的特殊语法结构,可以在函数定义之前加上@符号,然后在此装饰器函数中进行一些操作。通过定义一个装饰器函数,并在需要生成大量函数的地方使用该装饰器,可以实现批量生成的效果。 下面是一个示例: ```python def batch_function_generator(n): def decorator(func): def wrapper(*args, **kwargs): result = [] for i in range(n): result.append(func(*args, **kwargs)) return result return wrapper return decorator @batch_function_generator(5) def square(x): return x**2 result = square(2) print(result) ``` 在上面的例子中,`batch_function_generator`是一个装饰器函数,它接受一个参数n,表示生成函数的数量。它返回一个装饰器函数`decorator`,该函数用来修饰生成函数`func`。在装饰器函数`wrapper`中,通过循环调用生成函数`func`,将结果存入一个列表中,最后返回这个列表。 通过使用装饰器`@batch_function_generator(5)`修饰了函数`square`,就生成了5个平方函数。在调用`square(2)`时,返回的结果是[4, 4, 4, 4, 4],每个元素都是2的平方。 通过这种方式,可以方便地批量生成大量函数,而不需要手动定义每个函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GuokLiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值