【发布时间】:2018-09-06 17:51:11
【问题描述】:
我在伪 Python 代码中有以下情况,并且需要为它找到一个矢量化解决方案以进行优化,因为我正在处理数十万个用于语音分析的条目并且嵌套的 for 循环是不可行的。我想知道如何对不同大小的数组进行向量化条件检查...例如,我知道 np.greater,但这是一个元素明智的操作,它会因不同大小的数组而失败。
words = [
{'id': 0, 'word': 'Stu', 'sampleStart': 882, 'sampleEnd': 40571},
{'id': 0, 'word': ' ', 'sampleStart': 40570, 'sampleEnd': 44540},
{'id': 0, 'word': 'eyes', 'sampleStart': 44541, 'sampleEnd': 66590},
]
phonemes = [
{'id': 0, 'phoneme': ' ', 'sampleStart': 0, 'sampleEnd': 881},
{'id': 1, 'phoneme': 's', 'sampleStart': 882, 'sampleEnd': 7937},
{'id': 2, 'phoneme': 't', 'sampleStart': 7938, 'sampleEnd': 11906},
{'id': 3, 'phoneme': 'u', 'sampleStart': 11907, 'sampleEnd': 15433},
{'id': 3, 'phoneme': ' ', 'sampleStart': 15434, 'sampleEnd': 47627},
{'id': 3, 'phoneme': 'eye', 'sampleStart': 47628, 'sampleEnd': 57770},
{'id': 3, 'phoneme': 's', 'sampleStart': 57771, 'sampleEnd': 66590},
]
associatedData = []
for w in words:
startWord = w['sampleStart']
endWord = w['sampleEnd']
word = w['word']
w_id = w['id']
for p in phonemes:
startPhoneme = p['sampleStart']
endPhoneme = p['sampleEnd']
phoneme = p['phoneme']
p_id = p['id']
if startPhoneme >= startWord and endPhoneme <= endWord:
# I need to relate this data as it comes from 2 different sources
# Some computations occur here that are too ling to reproduce here, this multiplication is just to give an example
mult = startPhoneme * startWord
associatedData.append({'w_id' : w_id, 'p_id': p_id, 'word' : word, 'phoneme' : phoneme, 'someOp': startWord})
# Gather associated data for later use:
print(associatedData)
解决这个问题的好方法是什么?我对矢量操作相对较新,我已经为此苦苦挣扎了好几个小时,但没有太多结果。
【问题讨论】:
-
你能提供一个minimal reproducible example吗?如果没有看到
w和p的样子,也没有你想要的结果,很难按照你的想法去做 -
目前还不清楚您究竟想要矢量化什么 - 我建议您提供一个简短示例,说明您想要比较的两件事以及如何比较。
-
当数组大小不同时,您通常必须单独处理它们。如果它们不适合一个多维数组,则不能使用更快的整个数组方法。
-
借口,请参阅编辑后的帖子以获取更具体的示例
标签: python numpy vector conditional vectorization