本文共 2268 字,大约阅读时间需要 7 分钟。
为了完成本文的数据处理与图形可视化,我们需要引入以下主要库:
import osimport os.pathimport urllibimport gzipimport shutilimport numpy as npimport matplotlib.pyplot as plt
MNIST 是一个常用的手写数字数据库,包含训练集和测试集。我们从 Yann LeCun 的官方网站下载相关文件。以下是下载并解压文件的具体步骤:
if not os.path.exists('mnist'): os.mkdir("mnist")def download_and_gzip(name): if not os.path.exists(name + '.gz'): urllib.urlretrieve('http://yann.lecun.com/exdb/' + name + '.gz', name + '.gz') if not os.path.exists(name): with gzip.open(name + '.gz', "rb") as f_in, open(name, 'wb') as f_out: shutil.copyfileobj(f_in, f_out)download_and_gzip("mnist/train-images-idx3-ubyte")download_and_gzip('mnist/train-labels-idx1-ubyte')download_and_gzip('mnist/t10k-images-idx3-ubyte')download_and_gzip("mnist/t10k-labels-idx1-ubyte") 接下来,我们读取训练集和测试集的图像数据以及标签数据。
# 读取训练集图像数据loaded = np.fromfile("mnist/train-images-idx3-ubyte", dtype='uint8')loaded.shape # 读取训练集标签数据loaded = np.fromfile('mnist/train-labels-idx1-ubyte', dtype='uint8')loaded.shape # 读取测试集图像数据loaded = np.fromfile("mnist/t10k-images-idx3-ubyte", dtype='uint8')text_x = loaded[16:].reshape(10000, 28, 28)print(text_x.shape) # 读取测试集标签数据loaded = np.fromfile("mnist/t10k-labels-idx1-ubyte", dtype='uint8')test_y = loaded[8:].reshape(10000)print(test_y.shape) 将图像数据从 1D 转换为 3D 格式,便于后续处理和可视化。
train_x = loaded[16:].reshape(60000, 28, 28)text_x = loaded[16:].reshape(10000, 28, 28)print(train_x.shape)print(text_x.shape)
为了更直观地观察图像,我们可以使用 matplotlib 进行可视化。
plt.imshow(train_x[0], cmap="BrBG")plt.axis("off")plt.show() 我们也可以选择将图像按行和列分组进行批量显示。
def plot_images(images, row, col): show_image = np.vstack(np.split(np.hstack(images[:col*row]), row, axis=1)) plt.imshow(show_image, cmap='binary') plt.axis("off") plt.show()row, col = 4, 5plot_images(train_x, row, col) 通过上述代码,我们可以方便地查看训练集和测试集的图像数据分布。
MNIST 数据集包含 60,000 个训练样本和 10,000 个测试样本,每个样本包含 28x28 的图像数据。标签数据以单个字节的编码形式存储,因此我们需要将其转换为整数类型进行处理。
train_labels = train_y[0:20].reshape(4, 5)print(train_labels)
为了更直观地展示数据,我们可以使用 matplotlib 库进行图形绘制。以下是一些常用的绘图方法和示例:
# 选择颜色映射cmap = "BrBG"# 绘制图像plt.imshow(train_x[0], cmap=cmap)# 去掉坐标轴plt.axis("off")# 显示图像plt.show() 通过以上方法,我们可以清晰地看到 MNIST 数据集中的图像分布情况,方便后续的模型训练和验证。
转载地址:http://opofk.baihongyu.com/