从TensorFlow-Examples学习TensorFlow之三:nearest_neighbor最近邻。进度
BasicModels: nearest_neighbor.py
最近邻的样例比较容易看明白,就是拿测试数据与训练数据一一比对距离,选最小作为预测结果。
- L1距离:曼哈顿距离 sum(|xi - x|)
- L2距离:欧式距离 sqr(sum((xi-x)*(xi-x)))
建图代码
1 2 3 4 5 6 7 8 9
| # tf Graph Input xtr = tf.placeholder("float", [None, 784]) xte = tf.placeholder("float", [784])
# Nearest Neighbor calculation using L1 Distance # Calculate L1 Distance distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1) # Prediction: Get min distance index (Nearest neighbor) pred = tf.arg_min(distance, 0)
|