| import numpy as np | |
| def npy_to_fvecs(npy_file, fvecs_file): | |
| # 从npy文件中加载数组 | |
| array = np.load(npy_file) | |
| data_to_fvecs(array, fvecs_file) | |
| def data_to_fvecs(array, fvecs_file): | |
| # 打开fvecs文件进行写入 | |
| with open(fvecs_file, 'wb') as f: | |
| # 获取数组的形状 | |
| num_vectors, vector_dim = array.shape | |
| # 将每个向量写入fvecs文件 | |
| for vector in array: | |
| # 向量的维度 | |
| f.write(np.array(vector_dim, dtype=np.int32).tobytes()) | |
| # 向量 | |
| f.write(vector.astype(np.float32).tobytes()) | |
| print("转换完成!") | |
| # 调用函数进行转换 | |
| # npy_file = "input.npy" # 输入的npy文件路径 | |
| # fvecs_file = "output.fevecs" | |
| # npy_to_fvecs(npy_file, fvecs_file) | |
| if __name__=='__main__': | |
| npy_file = '/tmp/test.npy' # 输入的npy文件路径 | |
| origin_file = "sift1m/sift_query.fvecs" | |
| from sift1m.loading import fvecs_read | |
| dataset,_,_ = fvecs_read(origin_file) | |
| np.save(npy_file, dataset) | |
| fvecs_file = "/tmp/output.fevecs" | |
| npy_to_fvecs(npy_file, fvecs_file) |