随机游走生成器,自定义生成器

一、生成器产生随即游走序列及动态可视化

import numpy as np
import matplotlib.pyplot as plt
from celluloid import Camera

def random_walk(mu,x_0,sigma,N):
    a,b=mu,x_0
    for i in range(N+1):#表示一个原始数据+
        yield b#b表示需要实时监控的值,i表示时间
        b=a+b+np.random.normal(0,sigma)
#计划画三组随机游走序列
yi_1=[]
yi_2=[]
yi_3=[]
N=100
y1=random_walk(1,10,5,N)#返回一个生成器
y2=random_walk(1,5,4,N)
y3=random_walk(1,1,6,N)
print(y1)
print(y2)
print(y3)
x=[i for i in range(N+1)]
plt.ion()#交互式模式,用来生成动态图
end=1
# f1=plt.figure()
# camera=Camera(f1)
while 1:
    try:
        yi_1.append(next(y1))
        yi_2.append(next(y2))
        yi_3.append(next(y3))
        xlabel=x[:end]
        end=end+1
        plt.cla()
        plt.legend(['line1', 'line2', 'line3'], loc="upper left")
        plt.title("time line")
        plt.plot(xlabel, yi_1)
        plt.plot(xlabel, yi_2)
        plt.plot(xlabel, yi_3)
        plt.xlabel('Time')
        plt.ylabel('random value')
        # camera.snap()
        plt.pause(0.2)
    except StopIteration as si:
        print("end of iteration")
        break
plt.ioff()
#这是一个画动态图的方式,但是ffmpeg环境一直配不好,这是个什么奇葩玩意
# animation = camera.animate()
# animation.save('celluloid_minimal.gif',writer='ffmpeg')
plt.savefig("./line_graph")
compile=zip(yi_1,yi_2,yi_3)
for i in compile:
    print(i)
    

attention:如果直接list(generater),那么直接就变成了list,之后再调用生成器就失效了

在这里插入图片描述

二、迭代内容数据量过大,无法一次性加载

import numpy as np
from memory_profiler import profile
import os
from PIL import Image
from PIL import ImageFile
import sys  # 导入sys模块
sys.setrecursionlimit(5000)  # 将默认的递归深度修改为5000,因为系统默认的递归大小为1000


class Dataset:
    def __init__(self,path,start=0,step=1,max=1000):
        self.path=path
        self.start=start
        self.step=step
        self.max=max

    def path_load(self):
        lis=[]
        if not os.path.exists(self.path):
            print("could not find")
            return -1
        for root, dirs, names in os.walk(self.path):
            for filename in names:
                lis.append(os.path.join(root, filename))
        return lis

    def transform(self,images):
        img = Image.open(images)
        img = np.array(img)
        self.img = img
        return img

    def __iter__(self):

        return self
        # return iter(self._list)

    def __next__(self):
        if self.start <= self.max:
            x = self.start
            self.start += self.step
            return x
        else:
            raise StopIteration('大于max:{}'.format(self.max))

@profile
def main():
    path="./originalPics/"
    f=Dataset(path,max=5000)
    lis=f.path_load()
    for i_p in lis:
        ay=f.transform(i_p)
        print(ay)
    gen=iter(f)
    for i in gen:
        print(i)
main()

1)通过在类中添加 __iter__函数,向系统说明这是一个可迭代对象。

2)通过在类中添加 __next__函数,向系统提供该可迭代对象的迭代算法

3)在代码执行过程中,for循环函数会自动检查系统信息,识别__iter__函数,然后自动调用对应的__next__函数,生成一个迭代器。

4)所以在定义一个可迭代类时,一般__iter__ 函数要与 __next__函数成对出现。__iter__函数向系统声明这个类可迭代,__next__定义了具体的迭代器。

5)iter 与 __next__两个函数名不可改变,否则系统会不识别。

6)__next__函数的 return 在 if 判别命令的内部,每次执行__next__函数时,单次判别后直接输出。不满足判别条件时输出迭代终止。

[
n 在 if 判别命令的内部,每次执行__next__函数时,单次判别后直接输出。不满足判别条件时输出迭代终止。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值