用yield实现next_batch()

模拟tensorflow中next_batch的实现原理来熟悉yield的应用。

yield 可以看成是return,函数执行到yield便会退出函数,返回一个生成器。想要得到返回值必须使用next()来获取,否则只会得到一个生成器。且下次调用,会从yield出执。

行。

下面看模拟该函数的运行的过程。

import numpy as np
def next_batch(train,target,batch_size):
    length=len(train)
    index=[i for i in range(length)]
    np.random.shuffle(index)
    cnt=length/batch_size+1
    while cnt>0:
        batch_x=[]
        batch_y=[]
        try:
            for i in range(batch_size):
                batch_x.append(train[index[i]])
                batch_y.append(target[index[i]])
                index.remove(index[i])
        except:
             print("结束")
        
        yield (batch_x,batch_y)
             
train=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
target=[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]
a=next_batch(train,target,3)
for i in range(7):
    print(next(a))
输出的结果:
([5, 12, 18], [0, 1, 1])
([1, 14, 11], [0, 1, 0])
([7, 19, 2], [0, 0, 1])
([15, 9, 3], [0, 0, 0])
([20, 4, 6], [1, 1, 1])
([8, 10, 13], [1, 1, 0])
结束
([16], [1])

debug该函数的实现过程

(1)第一次执行时,batch-x和batch-y分别为(10,1,12),(1,0,1),从yield处返回。

2.再次调用next(),直接从while()处执行。 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值