numpy中flat/flatten用法区别

numpy.ndarray.flat/flatten

ndarray.flat

A 1-D iterator over the array. /将数组转换为1-D的迭代器 /
flat返回的是一个迭代器,可以用for访问数组每一个元素

import numpy as np
a = np.arange(4).reshape(2,2)
print(a)
for i in a.flat:
    print(i)
#迭代器可以用list进行输出
print(list(a.flat))
print(type(a.flat))#返回类型为 numpy.flatiter
#可以用索引对迭代器进行引号
a.flat[3]
[[0 1]
 [2 3]]
0
1
2
3
[0, 1, 2, 3]
<class 'numpy.flatiter'>
3

ndarray.flatten(order=’C’)

Return a copy of the array collapsed into one dimension.
将数组的副本转换为一个维度,并返回

可选参数,order:{‘C’,‘F’,‘A’,‘K’}

  • ‘C’:C-style,行序优先
  • ‘F’:Fortran-style,列序优先
  • ‘A’:if a is Fortran contiguous in memory ,flatten in column_major order
  • ‘K’:按照元素在内存出现的顺序进行排序
    默认为’C’

举例如下:

a = np.array([[4,5],[4,9]])
#默认按行转换
b= a.flatten()
print(b)
#换成列来划分
c = a.flatten('F')
print(c)
[4 5 4 9]
[4 4 5 9]
### Faiss 中 NumPy 的集成与使用 Faiss 是一个高效的相似度搜索库,支持多种索引类型以及大规摸向量检索场景。为了高效利用 Faiss 进行操作,通常会结合 NumPy 数组来准备输入数据。以下是关于如何在 Faiss 中使用 NumPy 数据的具体说明: #### 准备数据 在使用 Faiss 前,需确保数据是以连续的内存块形式存储,并采用 `float32` 类型[^2]。这可以通过调用 NumPy 提供的方法实现: ```python import numpy as np # 将数据转换为连续的 float32 类型数组 x = np.random.rand(1000, 128).astype('float32') x = np.ascontiguousarray(x, dtype='float32') ``` 上述代码片段展示了如何创建随机浮点数矩阵并将其调整为适合 Faiss 处理的形式。 #### 创建索引 一旦准备好数据,就可以通过定义合适的索引来构建 Faiss 结构。例如,最简单的 Flat 索引可以直接用于精确距离计算[^5]: ```python d = x.shape[1] # 向量维度 index = faiss.IndexFlatL2(d) # 使用 L2 距离的平面索引 print(index.is_trained) # 输出 True 表明无需训练此类型的索引 index.add(x) # 添加数据至索引 print(index.ntotal) # 打印当前索引中的总条目数量 ``` 以上代码基于给定的嵌入向量集合初始化了一个 Flat 索引实例[^4]。 #### 查询最近邻 完成索引建立之后,即可执行 k-NN (k近邻) 查找任务。下面的例子演示了如何针对某些查询点找到其最近邻居及其对应的距离值: ```python k = 4 # 返回前四个最近邻 query_vectors = np.random.rand(5, d).astype('float32') # 随机生成五个测试样本作为查询对象 distances, indices = index.search(query_vectors, k) for i in range(len(indices)): print(f"Query {i}: Nearest neighbors are at positions {indices[i]} with distances {distances[i]}") ``` 当面对超大规模数据集时,如果单一节点资源不足以支撑整个流程,则可探索分布式解决方案比如 Faiss-on-Spark 来分配工作负载于多台机器之上[^1]。 #### 性能优化建议 对于特定参数设置下的性能考量方面,在 SIFT1M 测试集中发现增大 M 参数会影响内存消耗;然而 efSearch 和 nprobe 对整体内存占用无显著作用[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值