tensorflow实现KNN识别MNIST
2019/7/15 1:03:35
本文主要是介绍tensorflow实现KNN识别MNIST,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。
这篇关于tensorflow实现KNN识别MNIST的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python