使用 Python 随机选择训练集图片并展示

本教程展示如何使用 Python 随机选择 25 张训练集图片并展示它们及其对应的标签。

代码示例:

# 随机选择25张训练集图片
sample_images = random.sample(list(zip(x_train, y_train)), 25)

# 展示训练集中的部分图片及其种类
plt.figure(figsize=(20,20))
for n , i in enumerate(list(np.random.randint(0,len(x_train),25))) : 
    plt.subplot(5,5,n+1)
    plt.imshow(x_train[i])   
    plt.axis('off')
    plt.title(getcode(y_train[i]))

代码解释:

  1. sample_images = random.sample(list(zip(x_train, y_train)), 25): 这行代码使用 random.sample 函数从 x_trainy_train 的组合中随机选择 25 个样本,并将它们存储在 sample_images 列表中。

  2. plt.figure(figsize=(20,20)): 这行代码创建一个大小为 20x20 英寸的图像显示窗口。

  3. for n , i in enumerate(list(np.random.randint(0,len(x_train),25))) : : 这行代码使用 for 循环遍历 25 个随机生成的索引 i

  4. plt.subplot(5,5,n+1): 这行代码将图像窗口划分为 5x5 的网格,并指定当前图像在网格中的位置。

  5. plt.imshow(x_train[i]): 这行代码使用 plt.imshow 函数在当前子图上显示 x_train 中索引为 i 的图像。

  6. plt.axis('off'): 这行代码隐藏子图的坐标轴。

  7. plt.title(getcode(y_train[i])): 这行代码设置子图的标题为 y_train 中索引为 i 的标签。getcode 函数用于将标签转换为可读的文本形式。

x_trainy_train 的定义:

  • x_train 是训练集中的图像数据,通常是一个多维数组,维度为 (样本数量,图像高度,图像宽度,通道数量)
  • y_train 是训练集中对应图像的标签(类别),通常是一个向量,包含 样本数量 个标签。

例如:

  • 如果 x_train 包含 1000 张 28x28 像素的灰度图像,则 x_train 的维度为 (1000, 28, 28, 1)
  • 如果 y_train 包含 1000 个标签,每个标签表示图像的类别,则 y_train 的维度为 (1000,)

注意:

  • getcode 函数是一个自定义函数,用于将标签转换为可读的文本形式。你需要根据你的数据集和标签定义这个函数。
  • 这段代码需要导入 randomnumpymatplotlib.pyplot 库。
Python 随机选择训练集图片并展示:示例代码及解释

原文地址: https://www.cveoy.top/t/topic/pcY9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录