You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法在TensorBoard中可视化Fashion-Mnist图像嵌入问题求助

解决Fashion-Mnist TensorBoard嵌入可视化错误问题

错误原因分析

从错误截图可知,TensorBoard无法正确加载特征向量文件,结合你的代码,核心问题如下:

  • 特征向量格式错误:直接将Tensor对象写入TSV文件,导致文件内容不符合TensorBoard的解析要求
  • 标签取值错误:循环中误将图像数据作为标签存储,而非真实的分类标签
  • Sprite图尺寸不匹配:生成精灵图时使用的坐标步长与图像实际尺寸不一致,导致图像排列混乱
  • 缺少TensorBoard嵌入配置:仅生成TSV和精灵图文件,未通过TensorFlow API将嵌入信息写入日志,TensorBoard无法识别资源关联关系

修正后的代码

%load_ext tensorboard
import csv
import numpy as np
import tensorflow as tf
from PIL import Image
import mnist_reader

# 加载预训练模型
model = tf.keras.models.load_model("resnet_50.h5")

# 创建嵌入提取模型(建议取倒数第二层输出作为嵌入特征,避免最后一层Softmax的分类偏移)
embeddings = tf.keras.models.Model( 
    inputs=model.inputs, 
    outputs=model.layers[-2].output 
)

# 加载并预处理数据
data_folder = "./data"
_, _ = mnist_reader.load_mnist(data_folder, "train")
test_images, test_labels = mnist_reader.load_mnist(data_folder, "t10k")
test_images = test_images.reshape(-1, 28, 28)
# 转换为3通道适配ResNet输入
test_images = np.stack((test_images,)*3, axis=-1).astype(np.uint8)
# 归一化(与模型训练时的预处理逻辑保持一致)
test_images = test_images / 255.0

# 处理前100个样本
sample_count = 100
images_pil = []
images_embeddings = []
labels = []

for img, label in zip(test_images[:sample_count], test_labels[:sample_count]):
    # 转换为PIL图像用于生成精灵图
    img_pil = Image.fromarray((img*255).astype(np.uint8)).resize((28,28))
    # 提取嵌入特征并转换为一维numpy数组
    img_embedding = embeddings(tf.expand_dims(img, axis=0)).numpy().flatten()
    images_embeddings.append(img_embedding)
    images_pil.append(img_pil)
    labels.append(label)

# 保存特征向量TSV
with open(f'logs/embeddings/feature_vecs.tsv', 'w', newline='') as fw:
    csv_writer = csv.writer(fw, delimiter='\t')
    csv_writer.writerows(images_embeddings)

# 生成精灵图
one_square_size = int(np.ceil(np.sqrt(sample_count)))
# 以图像实际尺寸28为步长,确保图像排列无重叠
sprite_size = 28 * one_square_size
spriteimage = Image.new(
    mode='RGB',
    size=(sprite_size, sprite_size),
    color=(255,255,255)
)
for count, image in enumerate(images_pil):
    div, mod = divmod(count, one_square_size)
    h_loc = 28 * div
    w_loc = 28 * mod
    spriteimage.paste(image, (w_loc, h_loc))
spriteimage.save(f'logs/embeddings/sprite.jpg')

# 保存带类别名称的元数据TSV,提升可视化可读性
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
with open(f'logs/embeddings/metadata.tsv', 'w') as file: 
    file.write('Index\tLabel\tClass Name\n')
    for idx, label in enumerate(labels):
        file.write(f'{idx}\t{label}\t{class_names[label]}\n')

# 配置TensorBoard嵌入可视化
log_dir = "logs/embeddings"
with tf.summary.create_file_writer(log_dir).as_default():
    embedding_tensor = tf.convert_to_tensor(images_embeddings)
    # 创建嵌入层并设置权重
    embedding_layer = tf.keras.layers.Embedding(input_dim=sample_count, output_dim=embedding_tensor.shape[1])
    embedding_layer.build((None,))
    embedding_layer.set_weights([embedding_tensor])
    
    # 配置Projector关联元数据与精灵图
    from tensorboard.plugins import projector
    config = projector.ProjectorConfig()
    embedding_config = config.embeddings.add()
    embedding_config.tensor_name = embedding_layer.embeddings.name
    embedding_config.metadata_path = 'metadata.tsv'
    embedding_config.sprite.image_path = 'sprite.jpg'
    embedding_config.sprite.single_image_dim.extend([28, 28])
    projector.visualize_embeddings(log_dir, config)

# 启动TensorBoard
%tensorboard --logdir logs  --host localhost

关键修正点说明

  • 特征向量标准化:将Tensor转换为一维numpy数组,确保TSV文件每行是符合要求的特征向量
  • 标签逻辑修正:改用test_labels获取真实分类标签,添加类别名称让可视化更直观
  • Sprite图校准:使用图像实际尺寸作为排列步长,避免图像重叠或错位
  • TensorBoard配置补全:通过ProjectorConfig明确嵌入、元数据与精灵图的关联,确保TensorBoard能正确加载所有资源

内容的提问来源于stack exchange,提问作者Lakii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:50:23