用tensorflow测试最近邻分类算法

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数据集前5000做训练集,200测试集
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距离
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)

运行结果:

Xtrain.shape:  (5000, 784) , Xtest.shape:  (200, 784)
Ytrain.shape:  (5000, 10) , Ytest.shape:  (200, 10)
。。。。。。。
Test 197 Predicted Class Label: 7 True Class Label: 7
Test 198 Predicted Class Label: 3 True Class Label: 5
Test 199 Predicted Class Label: 7 True Class Label: 7
Done!
Accuracy: 0.905

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值