TensorBoard-PROJECTOR-高维向量可视化

2024-04-28 20:32

本文主要是介绍TensorBoard-PROJECTOR-高维向量可视化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

TensorBoard-PROJECTOR-高维向量可视化

 

PROJECTOR用于将高维向量进行可视化,通过PCA,T-SNE等方法将高维向量投影到三维坐标系。

具体操作和解释见代码和注释:

import tensorflow as tf
import mnist_inference
import osfrom tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.examples.tutorials.mnist import input_databatch_size = 128
learning_rate_base = 0.8
learning_rate_decay = 0.99
training_steps = 10000
moving_average_decay = 0.99log_dir = 'log'
sprite_file = 'mnist_sprite.jpg'
meta_file = 'mnist_meta.tsv'
tensor_name = 'final_logits'#获取瓶颈层数据,即最后一层全连接层的输出
def train(mnist):with tf.variable_scope('input'):x = tf.placeholder(tf.float32,[None,784],name='x-input')y_ = tf.placeholder(tf.float32,[None,10],name='y-input')y = mnist_inference.build_net(x)global_step = tf.Variable(0,trainable=False)with tf.variable_scope('moving_average'):ema = tf.train.ExponentialMovingAverage(moving_average_decay,global_step)ema_op = ema.apply(tf.trainable_variables())with tf.variable_scope('loss_function'):loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,1)))with tf.variable_scope('train_step'):learning_rate = tf.train.exponential_decay(learning_rate_base,global_step,mnist.train.num_examples/batch_size,learning_rate_decay,staircase=True)train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)train_op = tf.group(train_step,ema_op)with tf.Session() as sess:sess.run(tf.global_variables_initializer())for i in range(training_steps):xs,ys = mnist.train.next_batch(batch_size)_,loss_value,step = sess.run([train_op,loss,global_step],feed_dict={x:xs,y_:ys})if step % 100 == 0 :print('step:{},loss:{}'.format(step,loss_value))final_result = sess.run(y,feed_dict={x:mnist.test.images})return final_resultdef visualisation(final_result):#定义一个新向量保存输出层向量的取值y = tf.Variable(final_result,name=tensor_name)#定义日志文件writersummary_writer = tf.summary.FileWriter(log_dir)#ProjectorConfig帮助生成日志文件config = projector.ProjectorConfig()#添加需要可视化的embeddingembedding = config.embeddings.add()#将需要可视化的变量与embedding绑定embedding.tensor_name = y.name#指定embedding每个点对应的标签信息,#这个是可选的,没有指定就没有标签信息embedding.metadata_path = meta_file#指定embedding每个点对应的图像,#这个文件也是可选的,没有指定就显示一个圆点embedding.sprite.image_path = sprite_file#指定sprite图中单张图片的大小embedding.sprite.single_image_dim.extend([28,28])#将projector的内容写入日志文件projector.visualize_embeddings(summary_writer,config)#初始化向量y,并将其保存到checkpoints文件中,以便于TensorBoard读取sess = tf.InteractiveSession()sess.run(tf.global_variables_initializer())saver = tf.train.Saver()saver.save(sess,os.path.join(log_dir,'model'),training_steps)summary_writer.close()def main(_):mnist = input_data.read_data_sets('MNIST_data',one_hot=True)final_result = train(mnist)visualisation(final_result)if __name__ == '__main__':tf.app.run()

生成sprite图和meta文件:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import os
from tensorflow.examples.tutorials.mnist import input_datalog_dir = './log'
sprite_file = 'mnist_sprite.jpg'
meta_file = 'mnist_meta.tsv'def create_sprite_image(images):if isinstance(images,list):images = np.array(images)#获取图像的高和宽img_h = images.shape[1]img_w = images.shape[2]#对图像数目开方,并向上取整,得到sprite图每边的图像数目num = int(np.ceil(np.sqrt(images.shape[0])))#初始化sprite图sprite_image = np.zeros([img_h*num,img_w*num])#为每个小图像赋值for i in range(num):for j in range(num):cur = i * num + jif cur < images.shape[0]:sprite_image[i*img_h:(i+1)*img_h,j*img_w:(j+1)*img_w] = images[cur]return sprite_imageif __name__ == '__main__':mnist = input_data.read_data_sets('MNIST_data',one_hot=False)#黑底白字变成白底黑字to_visualise = 1 - np.reshape(mnist.test.images,[-1,28,28])sprite_image = create_sprite_image(to_visualise)#存储展示图像path_mnist_sprite = os.path.join(log_dir,sprite_file)plt.imsave(path_mnist_sprite,sprite_image,cmap='gray')plt.imshow(sprite_image,cmap='gray')#存储每个下标对应的标签path_mnist_metadata = os.path.join(log_dir,meta_file)with open(path_mnist_metadata,'w') as f:f.write('Index\tLabel\n')for index,label in enumerate(mnist.test.labels):f.write('{}\t{}\n'.format(index,label))
  • 如图 
    这里写图片描述

执行tensorboard –logdir=log后,浏览器打开localhost:6006,即可观察到相应结果。 
这里写图片描述

可见每个高维向量都被投影到一个三维坐标系中,同一个类别的向量彼此靠近,形成一个一个的簇,且界限明显,可见分类效果较好。

同时左边栏中还有一些可选项: 
这里写图片描述 
Label by:可以选择Label和Index,将鼠标放到相应的点上,可以显示该点的Label或者Index

Color by:可选Label和No color map,前者会根据不同的label给点赋予不同的颜色,后者不涂色,一律为黑白,如图所示。 
这里写图片描述

在下方栏中,我们还可以选择T-SNE,PCA,CUSTOM等降维方法,默认选择PCA。

T-SNE效果如图: 
这里写图片描述

在右方栏中,我们可以根据Label查找某个类,如图,我们可以找到Label为4的点。 
这里写图片描述

这篇关于TensorBoard-PROJECTOR-高维向量可视化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/944186

相关文章

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

8种快速易用的Python Matplotlib数据可视化方法汇总(附源码)

《8种快速易用的PythonMatplotlib数据可视化方法汇总(附源码)》你是否曾经面对一堆复杂的数据,却不知道如何让它们变得直观易懂?别慌,Python的Matplotlib库是你数据可视化的... 目录引言1. 折线图(Line Plot)——趋势分析2. 柱状图(Bar Chart)——对比分析3

使用Vue-ECharts实现数据可视化图表功能

《使用Vue-ECharts实现数据可视化图表功能》在前端开发中,经常会遇到需要展示数据可视化的需求,比如柱状图、折线图、饼图等,这类需求不仅要求我们准确地将数据呈现出来,还需要兼顾美观与交互体验,所... 目录前言为什么选择 vue-ECharts?1. 基于 ECharts,功能强大2. 更符合 Vue

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1