最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
tensorflow实现KNN识别MNIST
时间:2018-03-19 编辑:猪哥 来源:一聚教程网
KNN算法算是最简单的机器学习算法之一了,这个算法最大的特点是没有训练过程,是一种懒惰学习,这种结构也可以在tensorflow实现。
KNN的最核心就是距离度量方式,官方例程给出的是L1范数的例子,我这里改成了L2范数,也就是我们常说的欧几里得距离度量,另外,虽然是叫KNN,意思是选取k个最接近的元素来投票产生分类,但是这里只是用了最近的那个数据的标签作为预测值了。
__author__ = 'freedom' import tensorflow as tf import numpy as np def loadMNIST(): from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data',one_hot=True) return mnist def KNN(mnist): train_x,train_y = mnist.train.next_batch(5000) test_x,test_y = mnist.train.next_batch(200) xtr = tf.placeholder(tf.float32,[None,784]) xte = tf.placeholder(tf.float32,[784]) distance = tf.sqrt(tf.reduce_sum(tf.pow(tf.add(xtr,tf.neg(xte)),2),reduction_indices=1)) pred = tf.argmin(distance,0) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) right = 0 for i in range(200): ansIndex = sess.run(pred,{xtr:train_x,xte:test_x[i,:]}) print 'prediction is ',np.argmax(train_y[ansIndex]) print 'true value is ',np.argmax(test_y[i]) if np.argmax(test_y[i]) == np.argmax(train_y[ansIndex]): right += 1.0 accracy = right/200.0 print accracy if __name__ == "__main__": mnist = loadMNIST() KNN(mnist)
-
下一个: php怎么把字符串指定字符分割成数组
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27