0

我在 PyTorch 中使用 resnet50 创建图像特征向量。每个特征向量的长度为 2048。当我想将其写入 txt 文件时,我必须将其转换为我在下面的代码中所做的 str。问题是,长度为 2048 的向量中只有几个数字保存在 txt 文件中。我怎样才能解决这个问题?

此外,我的每个文件名(图像)都有一个在 1 到 9(9 个类)之间关联的标签。

下面的代码是对此仓库的修改:https ://github.com/christiansafka/img2vec

import numpy as np
import sys
import os
sys.path.append("..")  # Adds higher directory to python modules path.
from img_to_vec import Img2Vec
from PIL import Image
from sklearn.metrics.pairwise import cosine_similarity
import glob


input_path = "my image folder**"
img2vec = Img2Vec()
vector_fh = open('resnet50_feature_vectors.txt', 'w+')


# For each test image, we store the filename and vector as key, value in a dictionary
pics = {}

filenames = glob.glob(input_path + "/*.*")

for filename in filenames:
    print(filename)
    img = Image.open(filename)
    nd_arr = img2vec.get_vec(img)
    #str_arr = nd_arr.tostring()
    str_arr = np.array2string(nd_arr, formatter={'float_kind':lambda x: "%.2f" % x})
    vector_fh.write(str_arr+"\n")

这是我收到的结果:

$头 resnet50_feature_vectors.txt

[0.22 1.54 0.40 ... 0.15 0.56 0.22]
[0.57 1.34 1.78 ... 0.26 1.19 1.30]
[0.01 2.81 0.15 ... 0.28 0.41 0.27]
[0.30 0.80 0.15 ... 0.02 0.08 0.03]
[0.10 1.39 0.60 ... 0.13 0.25 0.04]
[0.62 0.71 0.72 ... 0.36 0.15 0.51]
[0.43 0.44 0.52 ... 0.40 0.29 0.33]
[0.07 1.14 0.40 ... 0.09 0.08 0.10]
[0.13 1.45 0.96 ... 0.19 0.03 0.11]
[0.06 1.84 0.19 ... 0.11 0.11 0.03]

我应该如何修复特征向量在 txt 文件中的保存方式?

我正在尝试遵循此处的教程,其中有一个包含每个特征向量的 .txt 文件和一个包含每个特征向量标签的 txt 文件。

我说的是 MNIST 数据集教程的 Python 部分https://lvdmaaten.github.io/tsne/code/tsne_python.zip

4

0 回答 0