首页 > 解决方案 > 将任意长度列表映射到固定长度,保留内部结果的频率和位置(尽可能)

问题描述

背景故事:

将数据集中起来输入神经网络;以文档开头(长字符串);被分割成句子,句子被减少到 1 或 0,这取决于它们是否具有特征(在这种情况下,是词类)。

问题是文档的句子数量不同,因此句子和输入神经元之间不能是 1-1;你必须训练固定数量的神经元(除非我错过了什么)。

所以,我正在研究一种将数组映射到固定大小的算法,同时尽可能地保留数组中那些 1 的频率和位置(因为这就是 NN 做出决定的原因。

代码:

假设我们的目标是 10 个句子或神经元的固定长度,并且需要能够处理越来越大的数组。

new_length = 10
short = [1,0,1,0,0,0,0,1]
long  = [1,1,0,0,1,0,0,0,0,1,0,0,1]

def map_to_fixed_length(arr, new_length):
    arr_length = len(arr)
    partition_size = arr_length/new_length
    res = []
    for i in range(new_length):
        slice_start_index = int(math.floor(i * partition_size))
        slice_end_index = int(math.ceil(i * partition_size))
        partition = arr[slice_start_index:slice_end_index]
        val = sum(partition)
        res.append([slice_start_index, slice_end_index, partition])
        if val > 0:
            res.append(1)
        else:
            res.append(0)
    return res

可能不是很pythonic。无论如何,问题在于这省略了某些索引片。例如, 的最后一个索引short被省略,并且由于四舍五入,各种索引也被省略。

这是我一直在研究的简化版本,主要是添加 if 语句来解决留下的所有空白。但是有没有更好的方法来做到这一点?更有统计意义的东西?

我正在查看 numpy,但所有调整大小的函数都只是用零填充或相当任意的东西。

标签: pythonpython-3.xalgorithm

解决方案


一个简单的方法可能是这样使用scipy.interpolate.interp1d

>>> from scipy.interpolate import interp1d

>>> def resample(data, n):
...     m = len(data)
...     xin, xout = np.arange(n, 2*m*n, 2*n), np.arange(m, 2*m*n, 2*m)
...     return interp1d(xin, data, 'nearest', fill_value='extrapolate')(xout)
... 
>>> resample(short, new_length)
array([1., 0., 0., 1., 0., 0., 0., 0., 0., 1.])
>>> 
>>> resample(long, new_length)
array([1., 1., 0., 1., 0., 0., 0., 1., 0., 1.])

推荐阅读