kwarray模块
项目描述
查看文档 |
|
Gitlab (主分支) |
|
Github (镜像) |
|
Pypi |
此项目的官方网站是: https://gitlab.kitware.com/computer-vision/kwarray
kwarray模块实现了对numpy和torch的一些纯Python扩展。
kwarray模块最初是作为numpy的扩展,以及一个类似pandas的DataFrame对象,具有更快的行和列访问。但它还包括一个ArrayAPI,这是一个允许torch和numpy之间100%互操作性的包装器。它还包含一些算法,如setcover和mincost_assignment。
顶级API是
from kwarray.arrayapi import ArrayAPI, dtype_info
from .algo_assignment import (maxvalue_assignment, mincost_assignment,
mindist_assignment,)
from .algo_setcover import (setcover,)
from .dataframe_light import (DataFrameArray, DataFrameLight, LocLight,)
from .fast_rand import (standard_normal, standard_normal32, standard_normal64,
uniform, uniform32,)
from .util_averages import (RunningStats, stats_dict,)
from .util_groups import (apply_grouping, group_consecutive,
group_consecutive_indices, group_indices,
group_items,)
from .util_misc import (FlatIndexer,)
from .util_numpy import (arglexmax, argmaxima, argminima, atleast_nd, boolmask,
isect_flags, iter_reduce_ufunc, normalize,)
from .util_random import (ensure_rng, random_combinations, random_product,
seed_global, shuffle,)
from .util_slices import (embed_slice, padded_slice,)
from .util_slider import (SlidingWindow, Stitcher,)
from .util_torch import (one_hot_embedding, one_hot_lookup,)
ArrayAPI
在 kwarray 中最有用的功能之一是 kwarray.ArrayAPI 类 —— 一个帮助连接 numpy 和 torch 的类。此类包含静态方法,实现了部分 numpy API,并在 torch.Tensor 或 numpy.ndarray 对象上等效操作。
这是因为每个函数调用都会检查输入是否为 torch 张量或 numpy 数组,然后采取适当的操作。
正如你所想象的那样,在每次函数调用中验证输入可能很慢。因此,推荐使用数组 API 的方法是通过 kwarray.ArrayAPI.impl 函数。此函数只检查一次,然后返回另一个对象,该对象直接对后续相同类型的数据项执行正确的操作。
以下示例演示了两种使用模式。
import torch
import numpy as np
data1 = torch.rand(10, 10)
data2 = data1.numpy()
# Method 1: grab the appropriate sub-impl
impl1 = ArrayAPI.impl(data1)
impl2 = ArrayAPI.impl(data2)
result1 = impl1.sum(data1, axis=0)
result2 = impl2.sum(data2, axis=0)
assert np.all(impl1.numpy(result1) == impl2.numpy(result2))
# Method 2: choose the impl on the fly
result1 = ArrayAPI.sum(data1, axis=0)
result2 = ArrayAPI.sum(data2, axis=0)
assert np.all(ArrayAPI.numpy(result1) == ArrayAPI.numpy(result2))
其他注意事项
kwarray.ensure_rng 函数可以帮助你正确维护和控制本地有种子随机数生成。这意味着你不会破坏另一个库的随机状态/你的随机状态被破坏。
DataFrameArray 和 DataFrameLight 实现了 pandas API 的一部分。它们的性能不如前者强大,但速度快得多。主要的缺点是失去了 loc,但 iloc 可用。
uniform32 和 standard_normal32 是比它们的 64 位 numpy 对应版本更快的 32 位随机数生成器。
mincost_assignment 是 Munkres / 匈加利算法。它解决分配问题。
setcover - 使用近似或精确解解决最小加权集覆盖问题。
one_hot_embedding 是一个快速执行 OHE 深度学习技巧的 numpy/torch 方法。
group_items 是一种快速按另一个 numpy 数组分组 numpy 数组的方法。为了细粒度控制,我们还公开了 group_indices,它按 numpy 数组的索引分组,以及 apply_grouping,它通过这些索引对 numpy 数组进行分区。
boolmask 有效地反转 np.where。
用途
这是我在我项目中使用这个库的各个组件的频率
函数名 |
用途 |
---|---|
239 |
|
148 |
|
50 |
|
43 |
|
40 |
|
34 |
|
28 |
|
21 |
|
17 |
|
14 |
|
14 |
|
12 |
|
12 |
|
10 |
|
8 |
|
7 |
|
7 |
|
7 |
|
6 |
|
6 |
|
6 |
|
6 |
|
5 |
|
4 |
|
4 |
|
3 |
|
3 |
|
2 |
|
2 |
|
1 |
|
1 |
|
1 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |
|
0 |