5

我正在以多个时间分辨率跟踪多个离散时间序列,从而得到一个 SxRxB 矩阵,其中 S 是时间序列的数量,R 是不同分辨率的数量,B 是缓冲区,即每个序列记住多少个值。每个系列都是离散的,并使用有限范围的自然数来表示其值。我将在这里称这些“符号”。

对于每个系列,我想计算在所有测量中任何先前测量的符号直接在当前测量的任何符号之前的频率。我已经通过如下所示的 for 循环解决了这个问题,但出于明显的原因想对其进行矢量化。

我不确定我构建数据的方式是否有效,所以我愿意接受建议。我认为特别是比率矩阵可以做不同的事情。

提前致谢!

def supports_loop(data, num_series, resolutions, buffer_size, vocab_size):
    # For small test matrices we can calculate the complete matrix without problems
    indices = []
    indices.append(xrange(num_series))
    indices.append(xrange(vocab_size))
    indices.append(xrange(num_series))
    indices.append(xrange(vocab_size))
    indices.append(xrange(resolutions))

    # This is huge! :/
    # dimensions:
    #   series and value for which we calculate,
    #   series and value which precedes that measurement,
    #   resolution
    ratios = np.full((num_series, vocab_size, num_series, vocab_size, resolutions), 0.0)

    for idx in itertools.product(*indices):
        s0, v0 = idx[0],idx[1]  # the series and symbol for which we calculate
        s1, v1 = idx[2],idx[3]  # the series and symbol which should precede the we're calculating for
        res = idx[4]

        # Find the positions where s0==v0
        found0 = np.where(data[s0, res, :] == v0)[0]
        if found0.size == 0:
            continue
        #print('found {}={} at {}'.format(s0, v0, found0))

        # Check how often s1==v1 right before s0==v0
        candidates = (s1, res, (found0 - 1 + buffer_size) % buffer_size)
        found01 = np.count_nonzero(data[candidates] == v1)
        if found01 == 0:
            continue

        print('found {}={} following {}={} at {}'.format(s0, v0, s1, v1, found01))
        # total01 = number of positions where either s0 or s1 is defined (i.e. >=0)
        total01 = len(np.argwhere((data[s0, res, :] >= 0) & (data[s1, res, :] >= 0)))
        ratio = (float(found01) / total01) if total01 > 0 else 0.0
        ratios[idx] = ratio

    return ratios


def stackoverflow_example(fnc):
    data = np.array([
        [[0, 0, 1],  # series 0, resolution 0
         [1, 3, 2]], # series 0, resolution 1

        [[2, 1, 2],  # series 1, resolution 0
         [3, 3, 3]], # series 1, resoltuion 1
    ])

    num_series = data.shape[0]
    resolutions = data.shape[1]
    buffer_size = data.shape[2]
    vocab_size = np.max(data)+1

    ratios = fnc(data, num_series, resolutions, buffer_size, vocab_size)
    coordinates = np.argwhere(ratios > 0.0)
    nz_values = ratios[ratios > 0.0]
    print(np.hstack((coordinates, nz_values[:,None])))
    print('0/0 precedes 0/0 in 1 out of 3 cases: {}'.format(np.isclose(ratios[0,0,0,0,0], 1.0/3.0)))
    print('1/2 precedes 0/0 in 2 out of 3 cases: {}'.format(np.isclose(ratios[0,0,1,2,0], 2.0/3.0)))

预期输出(21 对,5 列坐标,然后是找到的计数):

[[0 0 0 0 0 1]
 [0 0 0 1 0 1]
 [0 0 1 2 0 2]
 [0 1 0 0 0 1]
 [0 1 0 2 1 1]
 [0 1 1 1 0 1]
 [0 1 1 3 1 1]
 [0 2 0 3 1 1]
 [0 2 1 3 1 1]
 [0 3 0 1 1 1]
 [0 3 1 3 1 1]
 [1 1 0 0 0 1]
 [1 1 1 2 0 1]
 [1 2 0 0 0 1]
 [1 2 0 1 0 1]
 [1 2 1 1 0 1]
 [1 2 1 2 0 1]
 [1 3 0 1 1 1]
 [1 3 0 2 1 1]
 [1 3 0 3 1 1]
 [1 3 1 3 1 3]]

在上面的示例中,系列 0 中的 0 在三分之二的情况下跟随系列 1 中的 2(因为缓冲区是循环的),因此 [0, 0, 1, 2, 0] 处的比率约为 0.6666。同样是系列 0,值 0 在三分之一的情况下跟随其自身,因此 [0, 0, 0, 0, 0] 处的比率将为 ~0.3333。还有一些其他的> 0.0。


我正在两个数据集上测试每个答案:一个很小的数据集(如上所示)和一个更现实的数据集(100 个系列,5 个分辨率,每个系列 10 个值,50 个符号)。

结果

Answer        Time (tiny)     Time (huge)     All pairs found (tiny=21)
-----------------------------------------------------------------------
Baseline      ~1ms            ~675s (!)       Yes
Saedeas       ~0.13ms         ~1.4ms          No (!)
Saedeas2      ~0.20ms         ~4.0ms          Yes, +cross resolutions
Elliot_1      ~0.70ms         ~100s (!)       Yes
Elliot_2      ~1ms            ~21s (!)        Yes
Kuppern_1     ~0.39ms         ~2.4s (!)       Yes
Kuppern_2     ~0.18ms         ~28ms           Yes
Kuppern_3     ~0.19ms         ~24ms           Yes
David         ~0.21ms         ~27ms           Yes

Saedeas 2nd 方法是明显的赢家!非常感谢你们,大家:)

4

4 回答 4

3

如果我正确理解了您的问题,我认为这段代码将以相对快速的矢量化方式为您提供所需的符号对。

import numpy as np
import time
from collections import Counter

series = 2
resolutions = 2
buffer_len = 3
symbols = range(3)

#mat = np.random.choice(symbols, size=(series, resolutions, buffer_len)).astype('uint8')

mat = np.array([
        [[0, 0, 1],  # series 0, resolution 0
         [1, 3, 2]],  # series 0, resolution 1
        [[2, 1, 2],  # series 1, resolution 0
         [3, 3, 3]],  # series 1, resoltuion 1
    ])

start = time.time()
index_mat = np.indices(mat.shape)

right_shift_indices = np.roll(index_mat, -1, axis=3)
mat_shifted = mat[right_shift_indices[0], right_shift_indices[1], right_shift_indices[2]]

# These construct all the pairs directly
first_series = np.repeat(range(series), series*resolutions*buffer_len)
second_series = np.tile(np.repeat(range(series), resolutions*buffer_len), series)
res_loop = np.tile(np.repeat(range(resolutions), buffer_len), series*series)
mat_unroll = np.repeat(mat, series, axis=0)
shift_unroll = np.tile(mat_shifted, series)

# Constructs the pairs
pairs = zip(np.ravel(first_series),
            np.ravel(second_series),
            np.ravel(res_loop),
            np.ravel(mat_unroll),
            np.ravel(shift_unroll))

pair_time = time.time() - start
results = Counter(pairs)
end = time.time() - start

print("Mat: {}").format(mat)
print("Pairs: {}").format(results)
print("Number of Pairs: {}".format(len(pairs)))
print("Pair time is: {}".format(pair_time))
print("Count time is: {}".format(end-pair_time))
print("Total time is: {}".format(end))

基本思想是根据缓冲区的时间序列将每个缓冲区循环移动适当的数量(我认为这就是您当前的代码正在做的事情)。然后,我可以通过简单地将沿系列轴偏移 1 的列表压缩在一起来生成所有符号对。

示例输出:

Mat: [[[0 0 1]
  [1 3 2]]

 [[2 1 2]
  [3 3 3]]]
Pairs: Counter({(1, 1, 1, 3, 3): 3, (1, 0, 0, 2, 0): 2, (0, 0, 0, 0, 0): 1, (1, 1, 0, 2, 2): 1, (1, 1, 0, 2, 1): 1, (0, 1, 0, 0, 2): 1, (1, 0, 1, 3, 3): 1, (0, 0, 1, 1, 3): 1, (0, 0, 1, 3, 2): 1, (1, 0, 0, 1, 1): 1, (0, 1, 0, 0, 1): 1, (0, 1, 1, 2, 3): 1, (0, 1, 0, 1, 2): 1, (1, 1, 0, 1, 2): 1, (0, 1, 1, 3, 3): 1, (1, 0, 1, 3, 2): 1, (0, 0, 0, 0, 1): 1, (0, 1, 1, 1, 3): 1, (0, 0, 1, 2, 1): 1, (0, 0, 0, 1, 0): 1, (1, 0, 1, 3, 1): 1})
Number of Pairs: 24
Pair time is: 0.000135183334351
Count time is: 5.10215759277e-05
Total time is: 0.000186204910278

编辑:真正的最后尝试。完全矢量化。

于 2018-07-09T20:35:39.057 回答
3

首先,如果没有明确嵌套 for 循环,您对自己有点不利。你最终会重复很多努力,并且在内存方面没有节省任何东西。当循环嵌套时,您可以将一些计算从一个级别移动到另一个级别,并确定哪些内部循环可以被矢量化。

def supports_5_loop(data, num_series, resolutions, buffer_size, vocab_size):
    ratios = np.full((num_series, vocab_size, num_series, vocab_size, resolutions), 0.0)
    for res in xrange(resolutions):
        for s0 in xrange(num_series):
            # Find the positions where s0==v0
            for v0 in np.unique(data[s0, res]):
                # only need to find indices once for each series and value
                found0 = np.where(data[s0, res, :] == v0)[0]
                for s1 in xrange(num_series):
                    # Check how often s1==v1 right before s0==v0
                    candidates = (s1, res, (found0 - 1 + buffer_size) % buffer_size)
                    total01 = np.logical_or(data[s0, res, :] >= 0, data[s1, res, :] >= 0).sum()
                    # can skip inner loops if there are no candidates
                    if total01 == 0:
                        continue
                    for v1 in xrange(vocab_size):
                        found01 = np.count_nonzero(data[candidates] == v1)
                        if found01 == 0:
                            continue

                        ratio = (float(found01) / total01)
                        ratios[(s0, v0, s1, v1, res)] = ratio

    return ratios

您会在时间安排中看到,大部分速度提升来自不重复的努力。

完成嵌套结构后,您可以开始查看矢量化和其他优化。

def supports_4_loop(data, num_series, resolutions, buffer_size, vocab_size):
    # For small test matrices we can calculate the complete matrix without problems

    # This is huge! :/
    # dimensions:
    #   series and value for which we calculate,
    #   series and value which precedes that measurement,
    #   resolution
    ratios = np.full((num_series, vocab_size, num_series, vocab_size, resolutions), 0.0)

    for res in xrange(resolutions):
        for s0 in xrange(num_series):
            # find the counts where either s0 or s1 are present
            total01 = np.logical_or(data[s0, res] >= 0,
                                    data[:, res] >= 0).sum(axis=1)
            s1s = np.where(total01)[0]
            # Find the positions where s0==v0
            v0s, counts = np.unique(data[s0, res], return_counts=True)
            # sorting before searching will show gains as the datasets
            # get larger
            indarr = np.argsort(data[s0, res])
            i0 = 0
            for v0, count in itertools.izip(v0s, counts):
                found0 = indarr[i0:i0+count]
                i0 += count
                for s1 in s1s:
                    candidates = data[(s1, res, (found0 - 1) % buffer_size)]
                    # can replace the innermost loop with numpy functions
                    v1s, counts = np.unique(candidates, return_counts=True)
                    ratios[s0, v0, s1, v1s, res] = counts / total01[s1]

    return ratios

不幸的是,我只能对最内层的循环进行真正的矢量化,而这只会增加 10% 的加速。在最内层循环之外,您无法保证所有向量的大小相同,因此您无法构建数组。

In [121]: (np.all(supports_loop(data, num_series, resolutions, buffer_size, vocab_size) == supports_5_loop(data, num_series, resolutions, buffer_size, vocab_size)))
Out[121]: True

In [122]: (np.all(supports_loop(data, num_series, resolutions, buffer_size, vocab_size) == supports_4_loop(data, num_series, resolutions, buffer_size, vocab_size)))
Out[122]: True
In [123]: %timeit(supports_loop(data, num_series, resolutions, buffer_size, vocab_size))
2.29 ms ± 73.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [124]: %timeit(supports_5_loop(data, num_series, resolutions, buffer_size, vocab_size))
949 µs ± 5.37 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [125]: %timeit(supports_4_loop(data, num_series, resolutions, buffer_size, vocab_size))
843 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
于 2018-07-10T13:39:48.967 回答
1

所以这是一个逃避的答案,但我一直在使用@Saedeas 的答案,并且根据我机器上的时间已经能够稍微优化它。我确实相信有一种方法可以在没有循环的情况下做到这一点,但中间数组的大小可能会令人望而却步。

我所做的更改是删除run()函数末尾发生的串联。这是创建一个新数组并且是不必要的。相反,我们在开头创建完整大小的数组,直到最后才使用最后一行。

我所做的另一个改变是平铺的single效率略低。我已经用速度更快的代码替换了它。

我相信这可以做得更快,但需要一些工作。我正在测试更大的尺寸,所以请告诉我你的机器上的时间。

代码如下;

import numpy as np
import logging
import sys
import time
import itertools
import timeit


logging.basicConfig(stream=sys.stdout,
                    level=logging.DEBUG,
                    format='%(message)s')


def run():
    series = 2
    resolutions = 2
    buffer_len = 3
    symbols = range(50)

    #mat = np.random.choice(symbols, size=(series, resolutions, buffer_len))

    mat = np.array([
            [[0, 0, 1],  # series 0, resolution 0
             [1, 3, 2]],  # series 0, resolution 1
            [[2, 1, 2],  # series 1, resolution 0
             [3, 3, 3]],  # series 1, resoltuion 1
            # [[4, 5, 6, 10],
            #  [7, 8, 9, 11]],
        ])

    # logging.debug("Original:")
    # logging.debug(mat)

    start = time.time()
    index_mat = np.indices((series, resolutions, buffer_len))

    # This loop shifts all series but the one being looked at, and zips the
    # element being looked at with every other member of that row
    cross_pairs = np.empty((series, resolutions, buffer_len, series, 2), int)
    #cross_pairs = []
    right_shift_indices = [index_mat[0], index_mat[1], (index_mat[2] - 1) % buffer_len]

    for i in range(series):
        right_shift_indices[2][i] = (right_shift_indices[2][i] + 1) % buffer_len


        # create a new matrix from the modified indices
        mat_shifted = mat[right_shift_indices]
        mat_shifted_t = mat_shifted.T.reshape(-1, series)
        single = mat_shifted_t[:, i]

        #print np.tile(single,(series-1,1)).T
        #print single.reshape(-1,1).repeat(series-1,1)
        #print single.repeat(series-1).reshape(-1,series-1)

        mat_shifted_t = np.delete(mat_shifted_t, i, axis=1)

        #cross_pairs[i,:,:,:-1] = (np.dstack((np.tile(single, (mat_shifted_t.shape[1], 1)).T, mat_shifted_t))).reshape(resolutions, buffer_len, (series-1), 2, order='F')
        #cross_pairs[i,:,:,:-1] = (np.dstack((single.reshape(-1,1).repeat(series-1,1), mat_shifted_t))).reshape(resolutions, buffer_len, (series-1), 2, order='F')
        cross_pairs[i,:,:,:-1] = np.dstack((single.repeat(series-1).reshape(-1,series-1), mat_shifted_t)).reshape(resolutions, buffer_len, (series-1), 2, order='F')

        right_shift_indices[2][i] = (right_shift_indices[2][i] - 1) % buffer_len
        #cross_pairs.extend([zip(itertools.repeat(x[i]), np.append(x[:i], x[i+1:])) for x in mat_shifted_t])

    #consecutive_pairs = np.empty((series, resolutions, buffer_len, 2, 2), int)
    #print "1", consecutive_pairs.shape
    # tedious code to put this stuff in the right shape
    in_series_zips = np.stack([mat[:, :, :-1], mat[:, :, 1:]], axis=3)
    circular_in_series_zips = np.stack([mat[:, :, -1], mat[:, :, 0]], axis=2)
    # This creates the final array.
    # Index 0 is the preceding series
    # Index 1 is the resolution
    # Index 2 is the location in the buffer
    # Index 3 is for the first n-1 elements, the following series, and for the last element
    #         it's the next element of the Index 0 series
    # Index 4 is the index into the two element pair
    cross_pairs[:,:,:-1,-1] = in_series_zips
    cross_pairs[:,:,-1,-1] = circular_in_series_zips

    end = time.time()
    #logging.debug("Pairs encountered:")
    #logging.debug(pairs)
    logging.info("Elapsed: {}".format(end - start))

if __name__ == '__main__':
    run()
于 2018-07-14T17:26:27.860 回答
1

使这个向量化的一个技巧是comb[i] = buffer1[i]+buffer2[i-1]*voc_size为每对系列制作一个数组。然后每个组合在数组中获得一个唯一值。并且可以通过做找到组合v1[i] = comb[i] % voc_size, v2[i] = comb[i]//voc_size。只要系列的数量不是很高(我认为<10000),就没有必要进行任何进一步的矢量化。

def support_vectorized(data, num_series, resolutions, buffer_size, vocab_size):
    ratios = np.zeros((num_series, vocab_size, num_series, vocab_size, resolutions))
    prev = np.roll(data, 1, axis=2)  # Get previous values
    prev *= vocab_size  # To separate prev from data
    for i, series in enumerate(data):
        for j, prev_series in enumerate(prev):
            comb = series + prev_series
            for k, buffer in enumerate(comb):
                idx, counts = np.unique(buffer, return_counts=True)
                v = idx % vocab_size    
                v2 = idx // vocab_size
                ratios[i, v, j, v2, k] = counts/buffer_size
    return ratios

但是,如果 S 或 R 很大,则可以进行完全矢量化,但这会占用大量内存:

def row_unique(comb):
    comb.sort(axis=-1)
    changes = np.concatenate((
        np.ones((comb.shape[0], comb.shape[1], comb.shape[2], 1), dtype="bool"),
        comb[:, :,:, 1:] != comb[:, :, :, :-1]), axis=-1)
    vals = comb[changes]
    idxs = np.nonzero(changes)
    tmp = np.hstack((idxs[-1], 0))
    counts = np.where(tmp[1:], np.diff(tmp), comb.shape[-1]-tmp[:-1])
    return idxs, vals, counts


def supports_full_vectorized(data, num_series, resolutions, buffer_size, vocab_size):
    ratios = np.zeros((num_series, vocab_size, num_series, vocab_size, resolutions))
    prev = np.roll(data, 1, axis=2)*vocab_size
    comb = data + prev[:, None]  # Create every combination
    idxs, vals, counts = row_unique(comb)  # Get unique values and counts for each row
    ratios[idxs[1], vals % vocab_size, idxs[0], vals // vocab_size, idxs[2]] = counts/buffer_size
    return ratios

但是,因为S=100这比以前的解决方案要慢。中间立场是在系列上保持一个 for 循环,以减少内存使用:

def row_unique2(comb):
    comb.sort(axis=-1)
    changes = np.concatenate((
        np.ones((comb.shape[0], comb.shape[1], 1), dtype="bool"),
        comb[:, :, 1:] != comb[:, :, :-1]), axis=-1)
    vals = comb[changes]
    idxs = np.nonzero(changes)
    tmp = np.hstack((idxs[-1], 0))
    counts = np.where(tmp[1:], np.diff(tmp), comb.shape[-1]-tmp[:-1])
    return idxs, vals, counts


def supports_half_vectorized(data, num_series, resolutions, buffer_size, vocab_size):
    prev = np.roll(data, 1, axis=2)*vocab_size
    ratios = np.zeros((num_series, vocab_size, num_series, vocab_size, resolutions))
    for i, series in enumerate(data):
        comb = series + prev
        idxs, vals, counts = row_unique2(comb)
        ratios[i, vals % vocab_size, idxs[0], vals // vocab_size, idxs[1]] = counts/buffer_size
    return ratios

不同解决方案的运行时间表明这support_half_vectorized是最快的

In [41]: S, R, B, voc_size = (100, 5, 1000, 29)

In [42]: data = np.random.randint(voc_size, size=S*R*B).reshape((S, R, B))

In [43]: %timeit support_vectorized(data, S, R, B, voc_size)
1 loop, best of 3: 4.84 s per loop

In [44]: %timeit supports_full_vectorized(data, S, R, B, voc_size)
1 loop, best of 3: 5.3 s per loop

In [45]: %timeit supports_half_vectorized(data, S, R, B, voc_size)
1 loop, best of 3: 4.36 s per loop

In [46]: %timeit supports_4_loop(data, S, R, B, voc_size)
1 loop, best of 3: 36.7 s per loop
于 2018-07-11T11:16:31.167 回答