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()
model_path = './model/mnist_mlp_epoch9.model' # Construct nn MLP = NN() MLP.add(SimpleBatchNorm(name="data_batchnorm", istraining=False)) MLP.add(Fullyconnected(784, 512, name="fc1")) MLP.add(Relu(name="fc1_relu")) MLP.add(SimpleBatchNorm(name='fc1_batchnorm')) MLP.add(Fullyconnected(512, 512, name="fc2")) MLP.add(Relu(name="fc2_relu")) MLP.add(Fullyconnected(512, 10, name="fc3")) # Load model MLP.load_model(model_path) for parent, dirnames, filenames in os.walk(img_dir): for filename in filenames: if filename.endswith("jpg") or filename.endswith("png"): img_path = os.path.join(parent, filename) pil_img = Image.open(img_path).convert('L') pil_img = pil_img.resize((28, 28), Image.ANTIALIAS) img = np.array(pil_img) out_data = MLP.forward(img.reshape((1, 784))) # Softmax probs = np.exp(out_data - out_data.max(axis=1).reshape((out_data.shape[0], 1))) probs /= probs.sum(axis=1).reshape((out_data.shape[0], 1)) print img_path, 'predict:', np.argmax(probs)
MLP.add(Fullyconnected(512, 512, name="fc2")) MLP.add(Relu(name="fc2_relu")) MLP.add(Fullyconnected(512, 10, name="fc3")) # Load model MLP.load_model(model_path) # Load mnist data mnist = mnist(path="./data/", batch_size=1, test=True) num_imgs = mnist.get_num() pos = 0 total_time = 0 for i in range(num_imgs): img, label = mnist.get_batch() t1 = time.time() out_data = MLP.forward(img) t2 = time.time() # Softmax probs = np.exp(out_data - out_data.max(axis=1).reshape((out_data.shape[0], 1))) probs /= probs.sum(axis=1).reshape((out_data.shape[0], 1)) pos += np.sum(label == probs.argmax(axis=1)) print "test img%d, time:%.5f" % (i, t2 - t1) total_time += t2 - t1 print "acc:", pos / float(num_imgs) print "average time:", total_time / float(num_imgs)