首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tensorflow中的KNN -使用图来预测未见的数据

Tensorflow中的KNN -使用图来预测未见的数据
EN

Stack Overflow用户
提问于 2017-06-28 20:55:42
回答 1查看 551关注 0票数 4

基于Tensorflow中的KNN的以下示例-使用该图来“预测”一些未见数据的标签的最佳方法是什么?

代码语言:javascript
复制
from __future__ import print_function

import numpy as np
import tensorflow as tf

# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

# 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)
# Prediction: Get min distance index (Nearest neighbor)
pred = tf.arg_min(distance, 0)

accuracy = 0.

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
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
        print("Test", i, "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)
EN

回答 1

Stack Overflow用户

发布于 2017-07-06 20:56:04

您可以通过将这些行附加到"with tf.Session() as sess:“中的末尾来完成此操作。

代码语言:javascript
复制
# Generate new (unseen) data
X, y = mnist.test.next_batch(1)

# Compute index of new data
nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: X[0, :]})

# Print the computed prediction 
print("Test", i, 
      "Prediction:", np.argmax(Ytr[nn_index]),
      "True Class:", np.argmax(y[0]))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44803133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档