20170514211426159

20170514211443777

20170514211458996


20170514211536901

20170514211550982






import numpy as np
import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# 导入MNIST数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist_data/", one_hot=True)

# 我们对MNIST数据集做一个数量限制,
Xtrain, Ytrain = mnist.train.next_batch(5000) #5000 用于训练(nn candidates)
Xtest, Ytest = mnist.test.next_batch(200) #200 用于测试
print('Xtrain.shape: ', Xtrain.shape, ', Xtest.shape: ',Xtest.shape)
print('Ytrain.shape: ', Ytrain.shape, ', Ytest.shape: ',Ytest.shape)

# 计算图输入占位符
xtrain = tf.placeholder("float", [None, 784])
xtest = tf.placeholder("float", [784])

# 使用L1距离进行最近邻计算
# 计算L1距离
distance = tf.reduce_sum(tf.abs(tf.add(xtrain, tf.negative(xtest))), axis=1)
# 预测: 获得最小距离的索引 (根据最近邻的类标签进行判断)
pred = tf.arg_min(distance, 0)
#评估:判断给定的一条测试样本是否预测正确

# 初始化节点
init = tf.global_variables_initializer()

#最近邻分类器的准确率
accuracy = 0.

# 启动会话
with tf.Session() as sess:
    sess.run(init)
    Ntest = len(Xtest)  #测试样本的数量
    # 在测试集上进行循环
    for i in range(Ntest):
        # 获取当前测试样本的最近邻
        nn_index = sess.run(pred, feed_dict={xtrain: Xtrain, xtest: Xtest[i, :]})
        # 获得最近邻预测标签,然后与真实的类标签比较
        pred_class_label = np.argmax(Ytrain[nn_index])
        true_class_label = np.argmax(Ytest[i])
        print("Test", i, "Predicted Class Label:", pred_class_label,
              "True Class Label:", true_class_label)
        # 计算准确率
        if pred_class_label == true_class_label:
            accuracy += 1
    print("Done!")
    accuracy /= Ntest
    print("Accuracy:", accuracy)



 收藏 (0)  打赏  点赞 (4)

Luke 4个月前

pred = tf.arg_min(distance, 0)

TensorFlow1.3.0应该使用

pred = tf.argmin(distance, 0)

(1) 回复

Luke 4个月前

一个小细节,相减的时候,-2 0 2 2 3 3,应该是-2 0 2 3 3 3


(0) 回复

您可能需要以下文章!

友情介绍

powered by studyai.com 2017