生成器

一个简单的生成器

函数代码

def count(len):
    i = 0
    while i < len:
        yield chr(i + ord('a'))
        i += 1

主函数调用

a = count(6)
print(count)
print(type(a))
for x in a:
    print(x, end=' ')

测试输出

<function count at 0x000001E8D92EE280>
<class 'generator'>
a b c d e f 

打造一个满足要求的生成器

import random
# 图片文件,标签文件,批处理大小(经验值),数据不足时是否保存
def data_reader(img_file, label_file, batch_size=24, drop_last=False):
    # (60000, 28, 28)
    mnist_matrix = read_matrix(img_file)
    # (60000)
    mnist_label = read_matrix(label_file)

    # 将图片和标签并起来
    # [(图片1, 标签1), (图片2, 标签2), ...]
    buff = []
    # for i in range(mnist_label.shape[0]):
    #     buff.append((mnist_matrix[i,:], int(label_file[i])))
    buff = list(zip(mnist_matrix, mnist_label))

    def batch_reader():
        # 打乱数据
        random.shuffle(buff)
        b = []
        for sample in buff:
            b.append(sample)
            if len(b) == batch_size:
                yield b
                b = []
        if drop_last and len(b) != 0:
            yield b

    return batch_reader

主函数调用

data_read = data_reader('D:/Matrix/t10k-images-idx3-ubyte', 'D:/Matrix/t10k-labels-idx1-ubyte')
for i, data in enumerate(data_read()):
    model.train(data)

测试输出

从MNIST数据集文件中读取矩阵

# 读取mnist
mnist_matrix = read_matrix('D:/Matrix/t10k-images-idx3-ubyte')
print(type(mnist_matrix))
print(mnist_matrix.shape)
print(mnist_matrix)
# 预览第一张图片
mnist_sample = mnist_matrix[0]

使用OpenCV查看图片

import cv2

# OpenCV
# 图像放大
mnist_sample = cv2.resize(mnist_sample, (200, 200))
# 窗口展示图片
cv2.imshow('winname', mnist_sample)
# 窗口弹出后按0后关闭
cv2.waitKey(0)

使用PLT查看图片并保存

from PIL import Image
import matplotlib.pyplot as plt

# PLT
# 将np矩阵转换为Image对象
img = Image.fromarray(mnist_sample)
# 查看类型
print(type(img))
# 显示图片
plt.imshow(img, 'gray')
plt.show()
# 将图片存储至硬盘
img.save('D:/temp/{}.jpg'.format('mnist_sample'))

测试输出

<class 'numpy.ndarray'>
(10000, 28, 28)
[[[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 ...

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]]]
<class 'PIL.Image.Image'>
最后修改:2022 年 08 月 12 日
如果觉得我的文章对你有用,请随意赞赏❤