最近邻算法,即找到训练样本中与之最近的数据,采用那个数据点的标注作为预测输出。
关于最近邻算法的原理,参考链接:KNN(k-nearest neighbor的缩写)最近邻算法原理详解
导入数据集:
导入数据集时,在TensorFlow2.0中会报错,ModuleNotFoundError: No module named ‘tensorflow.examples.tutorials.mnist’,在网上找解决方法为重新下载数据集放到Python环境中,但是我放置完成后会有警告显示Please use alternatives such as official/mnist/_DataSet.py from tensorflow/models.
tensorflow.examples.tutorials.mnist.input_data) is deprecated and will be removed in a future version.
肯定会有其他的解决方法,目前功力不够还不知道,先暂存以后解决。
import numpy as np
import tensorflow as tf
# 导入MNIST数据
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/mnist', one_hot=True)
# 在本代码中,我们限制使用的mnist数据的数量
Xtr, Ytr = mnist.train.next_batch(5000) # 5000个作为训练使用(nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200个用于测试
计算图的输入:
tensorflow程序一般分为两个阶段:
1、定义计算图所有的计算
2、在session中执行计算
tensorflow2.0中是取消了placeholder的,那么怎么重新定义计算图呢?
xtr = tf.placeholder('float', [None, 784])
xte = tf.placeholder('float', [784])
最近邻算法实现:
L1范数是指向量中各个元素绝对值之和。
tf.add(xtr, tf.negative(xte))计算了xtr-xte即元素之间的距离。
关于tf.reduce_