import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

n_train_img = 5000
n_test_img = 200

pixel_train, onehot_train = mnist.train.next_batch(n_train_img)
print(pixel_train.shape, onehot_train.shape)
pixel_test, onehot_test   = mnist.test.next_batch(n_test_img)
print(pixel_test.shape, onehot_test.shape)

TRAIN = tf.placeholder("float", (None,784))
TEST  = tf.placeholder("float", (784))

#d = tf.reduce_sum(tf.abs(tf.add(TRAIN, tf.negative(TEST))), reduction_indices=1)
d = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(TRAIN, TEST)), reduction_indices=1))
print (d)

val, idx = tf.nn.top_k(-d, k=20, sorted=False)
print (val, idx)
acc = 0.0
tot = 0.0

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  for i in range(n_test_img):
    knn_idx = sess.run(idx, feed_dict={TRAIN: pixel_train, TEST: pixel_test[i,:]})
    
    look_up = np.zeros(10)
    for j in np.argmax(onehot_train[knn_idx], axis=1):
      look_up[j] += 1
    pred = np.argmax(look_up)

    if (pred == np.argmax(onehot_test[i])):
      acc += 1
    tot += 1
    print("Test : " , i , " , Pred : " , pred , " , Real : ", np.argmax(onehot_test[i]), " , acc : " , acc/tot)

    
    
a = np.array(list(pixel_test[197,:]))  # 0,6
a = a.reshape(28,28)
plt.imshow(a, cmap=plt.get_cmap('gray'))
a = np.array(list(pixel_test[169,:]))    # 5,8
a = a.reshape(28,28)
plt.imshow(a, cmap=plt.get_cmap('gray'))
a = np.array(list(pixel_test[162,:]))    # Pred :  9  , Real :  4 
a = a.reshape(28,28)
plt.imshow(a, cmap=plt.get_cmap('gray'))
a = np.array(list(pixel_test[161,:]))    # Pred :  0  , Real :  8 
a = a.reshape(28,28)
plt.imshow(a, cmap=plt.get_cmap('gray'))

'도서관 I > AI' 카테고리의 다른 글

Fashion-MNIST 예제  (0) 2020.06.01
기본 keras 사용법  (0) 2020.06.01
softmax keras  (0) 2020.05.29
MNIST 데이터 불러오기  (0) 2020.05.29
python 정리  (0) 2020.05.28

+ Recent posts