tensorflow实现KNN识别MNIST
作者:freedom098 时间:2021-08-10 06:41:50
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)
来源:http://blog.csdn.net/freedom098/article/details/52117330
标签:tensorflow,KNN,MNIST
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
一文带你了解Python中的输入与输出
2023-11-26 12:05:24
![](https://img.aspxhome.com/file/2023/4/91884_0s.png)
Python函数式编程指南(三):迭代器详解
2023-06-03 06:11:52
python 下载文件的几种方式分享
2021-03-27 14:08:17
python使用thrift教程的方法示例
2022-03-14 04:29:02
![](https://img.aspxhome.com/file/2023/1/101671_0s.png)
CSS Position
2009-05-17 14:27:00
![](https://img.aspxhome.com/file/UploadPic/20095/17/static-15s.png)
讲解MaxDB数据库和MySQL数据库的主要差别
2009-01-04 13:04:00
python快速建立超简单的web服务器的实现方法
2021-03-14 23:25:14
python里运用私有属性和方法总结
2023-03-29 15:33:57
![](https://img.aspxhome.com/file/2023/0/69050_0s.png)
golang语言实现的文件上传与文件下载功能示例
2023-06-19 00:05:31
Python中使用Inotify监控文件实例
2021-03-03 14:17:05
下载Internet Explorer 9 平台预览版4
2010-08-05 20:59:00
wxPython窗口的继承机制实例分析
2023-03-04 15:55:47
![](https://img.aspxhome.com/file/2023/8/69548_0s.jpg)
python使用webbrowser浏览指定url的方法
2023-10-24 03:33:31
禁用JavaScript脚本来复制网站内容
2007-02-03 11:30:00
使用python加密主机文件几种方法实现
2021-03-06 03:16:12
js滑动展开与折叠效果(收缩)
2007-10-09 13:17:00
Python编解码问题及文本文件处理方法详解
2021-04-13 07:52:06
![](https://img.aspxhome.com/file/2023/9/72999_0s.png)
Python利用xlrd 与 xlwt 模块操作 Excel
2022-07-19 20:57:13
![](https://img.aspxhome.com/file/2023/8/103798_0s.webp)
python dataframe astype 字段类型转换方法
2022-02-19 07:58:50
PyQt5+Caffe+Opencv搭建人脸识别登录界面
2022-06-18 01:42:25
![](https://img.aspxhome.com/file/2023/5/103075_0s.jpg)