首页 > 其他分享 >tensorflow knn mnist

tensorflow knn mnist

时间:2023-05-30 17:33:16浏览次数:34  
标签:knn vals batch tf train test tensorflow data mnist

 

# MNIST Digit Prediction with k-Nearest Neighbors
#-----------------------------------------------
#
# This script will load the MNIST data, and split
# it into test/train and perform prediction with
# nearest neighbors
#
# For each test integer, we will return the
# closest image/integer.
#
# Integer images are represented as 28x8 matrices
# of floating point numbers

import random
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework import ops
ops.reset_default_graph()

# Create graph
sess = tf.Session()

# Load the data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# Random sample
np.random.seed(13)  # set seed for reproducibility
train_size = 1000
test_size = 102
rand_train_indices = np.random.choice(len(mnist.train.images), train_size, replace=False)
rand_test_indices = np.random.choice(len(mnist.test.images), test_size, replace=False)
x_vals_train = mnist.train.images[rand_train_indices]
x_vals_test = mnist.test.images[rand_test_indices]
y_vals_train = mnist.train.labels[rand_train_indices]
y_vals_test = mnist.test.labels[rand_test_indices]

# Declare k-value and batch size
k = 4
batch_size=6

# Placeholders
x_data_train = tf.placeholder(shape=[None, 784], dtype=tf.float32)
x_data_test = tf.placeholder(shape=[None, 784], dtype=tf.float32)
y_target_train = tf.placeholder(shape=[None, 10], dtype=tf.float32)
y_target_test = tf.placeholder(shape=[None, 10], dtype=tf.float32)

# Declare distance metric
# L1
distance = tf.reduce_sum(tf.abs(tf.subtract(x_data_train, tf.expand_dims(x_data_test,1))), axis=2)

# L2
#distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x_data_train, tf.expand_dims(x_data_test,1))), reduction_indices=1))

# Predict: Get min distance index (Nearest neighbor)
top_k_xvals, top_k_indices = tf.nn.top_k(tf.negative(distance), k=k)
prediction_indices = tf.gather(y_target_train, top_k_indices)
# Predict the mode category
count_of_predictions = tf.reduce_sum(prediction_indices, axis=1)
prediction = tf.argmax(count_of_predictions, axis=1)

# Calculate how many loops over training data
num_loops = int(np.ceil(len(x_vals_test)/batch_size))

test_output = []
actual_vals = []
for i in range(num_loops):
    min_index = i*batch_size
    max_index = min((i+1)*batch_size,len(x_vals_train))
    x_batch = x_vals_test[min_index:max_index]
    y_batch = y_vals_test[min_index:max_index]
    predictions = sess.run(prediction, feed_dict={x_data_train: x_vals_train, x_data_test: x_batch,
                                         y_target_train: y_vals_train, y_target_test: y_batch})
    test_output.extend(predictions)
    actual_vals.extend(np.argmax(y_batch, axis=1))

accuracy = sum([1./test_size for i in range(test_size) if test_output[i]==actual_vals[i]])
print('Accuracy on test set: ' + str(accuracy))

# Plot the last batch results:
actuals = np.argmax(y_batch, axis=1)

Nrows = 2
Ncols = 3
for i in range(len(actuals)):
    plt.subplot(Nrows, Ncols, i+1)
    plt.imshow(np.reshape(x_batch[i], [28,28]), cmap='Greys_r')
    plt.title('Actual: ' + str(actuals[i]) + ' Pred: ' + str(predictions[i]),
                               fontsize=10)
    frame = plt.gca()
    frame.axes.get_xaxis().set_visible(False)
    frame.axes.get_yaxis().set_visible(False)
    
plt.show()

 效果:

tensorflow knn mnist_ci

标签:knn,vals,batch,tf,train,test,tensorflow,data,mnist
From: https://blog.51cto.com/u_11908275/6381018

相关文章

  • 【2023 · CANN训练营第一季】昇腾AI入门课(TensorFlow)之模型迁移
    昇腾AI入门课(TensorFlow)之模型迁移将TensorFlow网络模型迁移到异腾Al处理器执行训练,主要有两种方式:自动迁移方式。通过迁移工具对原始脚本进行AST语法树扫描,可自动分析原生的TensorFlowAPI在异腾AI处理器上的支持度,并将原始的TensorFlowi训练脚本迁移成异腾Al处理器支持的脚本,对于......
  • 基于 Mindspore 框架与 ModelArts 平台的 MNIST 手写体识别实验
    简介实验包含2部分:基于Mindspore框架的模型本地训练及预测基于Modelarts平台和PyTorch框架的模型训练及部署基于Mindspore框架的模型本地训练及预测本例子会实现一个简单的图片分类的功能,整体流程如下:处理需要的数据集,这里使用了MNIST数据集。定义一个网络,这......
  • 【2023 · CANN训练营第一季】——在华为AI加速型ECS上安装Pytorch和Tensorflow框架
    前言:在CANN训练营提供的华为云镜像环境,通过miniconda安装pytorch和Tensorflow框架。在模型迁移前准备阶段,可以用来在CPU上对模型训练进行验证。本文描述了安装过程,更换国内conda源、并分别下载例程,在Pytorch和Tensorflow框架下进行了CPU训练。还介绍了在Pytorch、Tensorflow虚拟环......
  • 数据分享|R语言逻辑回归、线性判别分析LDA、GAM、MARS、KNN、QDA、决策树、随机森林、
    全文链接:http://tecdat.cn/?p=27384最近我们被客户要求撰写关于葡萄酒的研究报告,包括一些图形和统计输出。在本文中,数据包含有关葡萄牙“VinhoVerde”葡萄酒的信息介绍该数据集(查看文末了解数据获取方式)有1599个观测值和12个变量,分别是固定酸度、挥发性酸度、柠檬酸、残糖、......
  • 使用 TensorFlow 自动微分和神经网络功能估算线性回归的参数(Estimate parameters for
    大多数的深度学习框架至少都会具备以下功能:(1)张量运算(2)自动微分(3)神经网络及各种神经层TensorFlow框架亦是如此。在《深度学习全书公式+推导+代码+TensorFlow全程案例》——洪锦魁主编清华大学出版社ISBN978-7-302-61030-4这本书第3章《TensorFlow架构与主要功能》这一......
  • macbook苹果m1芯片训练机器学习、深度学习模型,resnet101在mnist手写数字识别上做加速
    apple的m1芯片比以往cpu芯片在机器学习加速上听说有15倍的提升,也就是可以使用applemac训练深度学习pytorch模型!!!惊呆了 安装applem1芯片版本的pytorch 然后使用chatGPT生成一个resnet101的训练代码,这里注意,如果网络特别轻的话是没有加速效果的,还没有cpu的计算来的快这里......
  • 【836】Cannot import tensorflow_text
    Ref:Cannotimporttensorflow_textSometimesyouneedtoreinstallandupdatetensorflowtheninstalltensorflow_text.(Becauseyouneedyourtensorflow.__version__andtensorflow_text.__version__tohavethesameversion)Makesuretensorflowandtensor......
  • [7]数据科学-【8】TensorFlow库
    TensorFlow是一个广泛使用的机器学习和深度学习框架,它提供了丰富的工具和库,用于构建、训练和部署各种人工智能模型。本教程将带你从头开始学习如何使用TensorFlow库进行机器学习任务。我们将依次介绍TensorFlow的基本概念、张量操作、构建模型、训练模型和保存模型的方法。1.安装T......
  • 关于同时运行多个tensorflow模型时线程创建失败
    OpenMP:"libgomp:Threadcreationfailed:Resourcetemporarilyunavailable"whencoderunasregularuser这几天在跑代码的时候,因为模型需要调参,方便起见打算同时运行25个程序。但是在使用bash脚本,同时启动25个进程的时候,发现制启动了12个进程。尝试用vscode打开调试模式,......
  • ISL学习——tensorflow部分指令
    tf.keras.layers.Sequential()#用来描述神经网络的结构,其中Sequential()里面的参数是用来描述从输入层到输出层的网络结构。modnn=tf.keras.Sequential([tf.keras.layers.Dense(units=10,#参数为正整数,表示输出空间的维数为10维......