一、KNN 分类模型的三要素
1、距离度量
2、K 值的选择
3、分类决策规则
二、TF 实现最近邻分类器(K=1)
import tensorflow as tf
import numpy as np
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '6'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist_data/", one_hot=True)
Xtrain, Ytrain = mnist.train.next_batch(5000)
Xtest, Ytest = mnist.test.next_batch(200)
print('Xtrain.shape: ', Xtrain.shape, ', Xtest.shape: ',Xtest.shape)
print('Ytrain.shape: ', Ytrain.shape, ', Ytest.shape: ',Ytest.shape)
xtrain = tf.placeholder(tf.float32, shape=[None, 784])
xtest = tf.placeholder(tf.float32, shape=[784])
distance = tf.reduce_sum(tf.subtract(xtrain, xtest)), axis=1)
pred = tf.argmin(distance, axis=0)
gpuConfig = tf.ConfigProto()
gpuConfig.gpu_options.allow_growth = True
init = tf.global_variables_initializer()
accuracy = 0.0
with tf.Session(config=gpuConfig) 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)
三、参考资料
1、TensorFlow实现最近邻分类器