gpt4 book ai didi

python - Python 中二元输出拆分算法的优化

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:56 26 4
gpt4 key购买 nike

我对这个拆分函数有疑问。函数基本上采用一个字符串,例如 word = 'optimization' 并根据生成的随机数定义它的拆分点,并将其拆分为二元语法。 '0' 标记表示词尾。考虑下面的词;左侧是输入,函数应该给出所有可能的输出之一,概率与相同单词的任何输出相同:

'optimization' = [['op', 'ti'], ['ti', 'mizati'], ['mizati', 'on'], ['on', '0']

问题:当我分析我所有的函数时,这个拆分函数消耗了最多的运行时间(处理 10 万个单词),但我一直在优化它。在这一点上我需要一些帮助。也可能有更好的方法,但我受限于自己的观点。

from numpy import mod
import nltk

def random_Bigramsplitter(word):
spw = []
length = len(word)
rand = random_int(word) # produce random number in respect to len(word)

if rand == length: # probability of not dividing
return [tuple([word, '0'])]
else:
div = mod(rand, (length + 1)) # defining division points by mod operation
bound = length-div
spw.append(div)
while div != 0:
rand = random_int(word)
div = mod(rand, (bound + 1))
bound = bound-div
spw.append(div)
result = spw

b = 0
points = []
for x in range(len(result) - 1): # calculating splitting points in respect to array structure
b += result[x]
points.append(b)

xy = 0
t = []
for i in points:
t.append(word[xy:i])
xy = i

if word[xy: len(word)] != '':
t.append(word[xy: len(word)])

t.extend('0')
c = [b for b in nltk.bigrams(t)]

return c

最佳答案

可以替换

c = [b for b in nltk.bigrams(t)]

def get_ngram(word, n):
return zip(*[word[i:] for i in xrange(n)])

c = [b for b in get_ngram(t, 2)]

这似乎更快。我并不是说这是最快的解决方案。

有更多关于优化二元组速度的答案。这似乎是一个很好的起点:Fast n-gram calculation ,我的代码片段来自:http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/

关于python - Python 中二元输出拆分算法的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com