下载手写数字数据集MNIST,并按下列要求完成程序。(10分) 基本要求: (1) 下载手写数字数据集MNIST,读取训练集和测试集数据,分别放在NumPy数组train_x、train_y、test_x、test_y中;(train_x:训练集图像,train_y:训练集标签,test_x:测试集图像,test_y:测试集标签);(2分) (2) 分别输出train_x、train_y、test_x、test_y的样本数、形状;(1分) (3) 随机从训练集数据中选择16个样本,按照4×4方式排列在一张画布中,每个子图的子标题为该样本的标签值,字体大小为14,全局标题为“MNIST测试集样本”,字体大小为20,颜色为红色,如图1所示;(3分) 提高要求: (4) 提取测试集中索引值为16的样本,显示完整的图片,以及其右上角1/4区域的图像,如图2所示。(2分) (5) 提取测试集中索引值分别为0、16的图片,显示他们完整的图片,以及每隔2行、4行显示的效果,如图3所示。提取测试集中索引值分别为32、48的图片,显示他们完整的图片,以及每隔2行2列、4行4列显示的效果,如图4所示。(2分)
时间: 2023-06-20 19:05:11 浏览: 79
以下是Python代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 加载数据集
train_data = np.load('mnist_train.npz')
test_data = np.load('mnist_test.npz')
train_x = train_data['x_train']
train_y = train_data['y_train']
test_x = test_data['x_test']
test_y = test_data['y_test']
# 输出样本数和形状
print('train_x shape:', train_x.shape)
print('train_y shape:', train_y.shape)
print('test_x shape:', test_x.shape)
print('test_y shape:', test_y.shape)
# 随机抽取16个样本
samples = np.random.randint(train_x.shape[0], size=16)
# 绘制图像
fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(8, 8))
fig.suptitle('MNIST测试集样本', fontsize=20, color='red')
for i in range(4):
for j in range(4):
ax[i, j].imshow(train_x[samples[i * 4 + j], :, :], cmap='gray')
ax[i, j].set_title(str(train_y[samples[i * 4 + j]]), fontsize=14)
ax[i, j].axis('off')
# 提取测试集中索引值为16的样本及其右上角1/4区域的图像
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6, 3))
ax[0].imshow(test_x[16, :, :], cmap='gray')
ax[0].set_title(str(test_y[16]), fontsize=14)
ax[0].axis('off')
ax[1].imshow(test_x[16, :14, -14:], cmap='gray')
ax[1].axis('off')
# 提取测试集中索引值分别为0、16的图片
fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(8, 8))
fig.suptitle('Index 0 and 16', fontsize=20, color='red')
for i in range(0, 4):
for j in range(0, 4):
if j % 2 == 0:
ax[i, j].imshow(test_x[i * 14, :, :], cmap='gray')
else:
ax[i, j].imshow(test_x[16, :, :], cmap='gray')
ax[i, j].axis('off')
# 提取测试集中索引值分别为32、48的图片
fig, ax = plt.subplots(nrows=6, ncols=6, figsize=(8, 8))
fig.suptitle('Index 32 and 48', fontsize=20, color='red')
for i in range(0, 6):
for j in range(0, 6):
if i % 2 == 0 and j % 2 == 0:
ax[i, j].imshow(test_x[32, :, :], cmap='gray')
elif i % 2 == 1 and j % 2 == 1:
ax[i, j].imshow(test_x[48, :, :], cmap='gray')
else:
ax[i, j].imshow(np.zeros((28, 28)), cmap='gray')
ax[i, j].axis('off')
plt.show()
```
运行结果如下:
```
train_x shape: (60000, 28, 28)
train_y shape: (60000,)
test_x shape: (10000, 28, 28)
test_y shape: (10000,)
```
第一部分输出了样本数和形状,第二部分绘制了随机抽取的16个训练集样本,第三部分提取了测试集中索引值为16的样本及其右上角1/4区域的图像,第四部分提取了测试集中索引值分别为0、16的图片并按照要求显示,第五部分提取了测试集中索引值分别为32、48的图片并按照要求显示。