def test10RandomImgs(): # 读取测试集结果 dl = DataLoader('MNIST', './datasets/MNIST/') test_images, test_labels = dl.Load('test') # 生成10个连续的随机数 idx = np.random.randint(0, test_images.shape[0] - 10) random_image = test_images[idx:idx + 10, :] # testlabel = nn.test(random_image.T) MNIST_test = NN() MNIST_test.loadParams() out = MNIST_test.forward(random_image.T - 33.318421, 'test') exp_out = np.exp(out) softmax_out = exp_out / np.sum(exp_out, axis=0) # 找到最大值索引,作为分类结果 cls_res = np.argmax(softmax_out, axis=0) # 显示图像 for i in range(0, 10): plt.subplot(2, 5, i + 1) plt.title('分类: %d' % cls_res[i]) # 关闭坐标刻度 plt.xticks([]) plt.yticks([]) plt.imshow(np.reshape(random_image[i], [28, 28]), cmap='gray') plt.show()
def test(mean=33.318421): # 读取测试数据集,注意:测试时的均值仍然要与训练时均值相同 dl = DataLoader('MNIST', './datasets/MNIST/') test_images, test_labels = dl.Load('test') # 预处理 (0 均值化) test_images -= mean print('测试数据集数量: %d' % len(test_labels)) # 测试 MNIST_Net = NN() MNIST_Net.loadParams() MNIST_Net.valid(test_images.T, test_labels, 100, mode='test')