tensorflow实现knn算法

TF v1.9.0,knn添加了L2距离,解决了 No module named 'tensorflow.contrib.boosted_trees.lib' 的问题。


# coding: utf-8

# In[1]:


import warnings
warnings.filterwarnings("ignore")
import numpy as np
import tensorflow as tf

# Import MINST data
# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets("D:/datas/data_mnist", one_hot=True)
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
mnist = read_data_sets("D:/datas/data_mnist", one_hot=True)


# In[2]:


# In this example, we limit mnist data
Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)
Xte, Yte = mnist.test.next_batch(200) #200 for testing

# 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)
# Calculate L2 Distance
distance = tf.sqrt( tf.reduce_sum( tf.square(tf.subtract(xtr, xte) ), reduction_indices=[1]) )
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.argmin(distance, 0)

# accuracy = 0.

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()


# In[3]:


# Start training
accuracy = 0.
with tf.Session() as sess:
    sess.run(init)

    # loop over test data
    for i in range(len(Xte)):
        # Get nearest neighbor
        nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})
        # Get nearest neighbor class label and compare it to its true label
        if (i+1) % 10 == 0:
            print( "Test", i+1, "Prediction:", np.argmax(Ytr[nn_index]), \
                "True Class:", np.argmax(Yte[i]) )
        # Calculate accuracy
        if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):
            accuracy += 1./len(Xte)
    print( "Done!" )
    print( "Accuracy:", accuracy )

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值