tensorflow实现KNN识别MNIST

yipeiwu_com6年前Python基础

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) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

通过Pandas读取大文件的实例

当数据文件过大时,由于计算机内存有限,需要对大文件进行分块读取: import pandas as pd f = open('E:/学习相关/Python/数据样例/用户侧数据/te...

合并百度影音的离线数据( with python 2.3)

四种格式的解析: filelist slicelist download.cfg third_party_download.cfg 还是2个文件。替换之前版本即可。 初步测试正常,但时间...

pandas 根据列的值选取所有行的示例

如下所示: # 选取等于某些值的行记录 用 == df.loc[df['column_name'] == some_value] # 选取某列是否是某一类型的数值 用 isin...

Python实现获取汉字偏旁部首的方法示例【测试可用】

Python实现获取汉字偏旁部首的方法示例【测试可用】

本文实例讲述了Python实现获取汉字偏旁部首的方法。分享给大家供大家参考,具体如下: 功能介绍 传入一个汉字,返回其偏旁部首 字典 分为本地字典与网络字典,本地词典来自精简版的新华字典...

python获取文件真实链接的方法,针对于302返回码

使用模块requests 方式代码如下: import requests url_string="https://******" r = requests.head(url_st...