在 numba.jit(nopython=True)
函数内部,我正在计算数千个 numpy 数组(一维,整数数据类型)并将它们附加到列表中。问题是某些数组看起来相等,但我不需要重复项。所以我需要一种有效的方法来检查新数组是否已存在于列表中。
在Python中可以这样完成:
import numpy as np
import numba as nb
# @nb.jit(nopython=True)
def foo(n):
uniques = []
uniques_set = set()
for _ in range(n):
arr = np.random.randint(0, 2, 2)
arr_hashable = make_hashable(arr)
if not arr_hashable in uniques_set:
uniques_set.add(arr_hashable)
uniques.append(arr)
return uniques
Run Code Online (Sandbox Code Playgroud)
我尝试了两种方法来解决这个问题:
将数组转换为元组并将元组放入集合中。
def make_hashable(arr):
return tuple(arr)
Run Code Online (Sandbox Code Playgroud)
但不幸的是,直接元组构造在 nopython 模式下不能以这种方式工作。我也尝试过这种方式:
def make_hashable(arr):
res = ()
for n in arr:
res += (n,)
return res
Run Code Online (Sandbox Code Playgroud)
和我能想到的其他类似的解决方法,但它们都在 nopython 模式下失败并出现 TypeError。
将数组转换为字符串并将其放入集合中。
def make_hashable(arr):
return arr.tostring()
Run Code Online (Sandbox Code Playgroud)
还尝试了所有可能的方法将数组转换为字符串,但似乎 numba …
我有一个scipy CSR矩阵,我想获得每一行的元素列索引.我的方法是:
import scipy.sparse as sp
N = 100
d = 0.1
M = sp.rand(N, N, d, format='csr')
indM = [row.nonzero()[1] for row in M]
Run Code Online (Sandbox Code Playgroud)
indM是我需要的,它与M的行数相同,如下所示:
[array([ 6, 7, 11, ..., 79, 85, 86]),
array([12, 20, 25, ..., 84, 93, 95]),
...
array([ 7, 24, 32, 40, 50, 51, 57, 71, 74, 96]),
array([ 1, 4, 9, ..., 71, 95, 96])]
Run Code Online (Sandbox Code Playgroud)
问题是,对于大矩阵,这种方法看起来很慢.有没有办法避免列表理解或以某种方式加快这一点?
谢谢.
我现在正在尝试为基于LSTM的NN准备输入数据.我有一些大量的文本文档,我想要的是为每个文档制作序列向量,以便我能够将它们作为列车数据提供给LSTM RNN.
我糟糕的做法:
import re
import numpy as np
#raw data
train_docs = ['this is text number one', 'another text that i have']
#put all docs together
train_data = ''
for val in train_docs:
train_data += ' ' + val
tokens = np.unique(re.findall('[a-z?-?0-9]+', train_data.lower()))
voc = {v: k for k, v in dict(enumerate(tokens)).items()}
Run Code Online (Sandbox Code Playgroud)
然后brutforce用"voc"词典替换每个doc.
有没有可以帮助完成这项任务的库?