python - 将任意长度列表映射到固定长度,保留内部结果的频率和位置(尽可能)
问题描述
背景故事:
将数据集中起来输入神经网络;以文档开头(长字符串);被分割成句子,句子被减少到 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,但所有调整大小的函数都只是用零填充或相当任意的东西。
解决方案
一个简单的方法可能是这样使用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.])
推荐阅读
- c# - .Net Core 3.1 MVC 身份验证个人用户帐户和 ASP.NET Core 项目中的脚手架身份
- nginx - 如何在 Nginx 上使用多个网站/路径提供静态内容?
- c# - Jetbrains Rider 无法在 .net 核心项目上运行测试
- r - R 字典使用字符串作为值还是只使用列表?
- ruby-on-rails - Heroku rails 6 上缺少 client_id 参数
- kubernetes - 如何在 k8s 上为服务帐户创建客户端证书和客户端密钥
- ansible - 如何在安装角色之前等待 ssh 在主机上可用?
- c# - 从 SQL Server 存储过程插入 DB2 数据库成功,但使用 Entity Framework 包装相同的过程失败
- python-3.x - 开始日期是当月的第一天,结束日期是下个月的第一天 Pandas
- python - 根据来自另一个 DataFrame 的值从一个 DataFrame 中选择行