是否可以使用Python在Zipf分配之後從列表中選擇一個元素?在Python中使用Zipf類選擇從列表中選擇元素
假設我有一個列表:
objlist = ['Here', 'in', 'the', 'wall', 'why']
到目前爲止,我所看到的https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.zipf.html 但我不能找出解決方案。
在此先感謝。
是否可以使用Python在Zipf分配之後從列表中選擇一個元素?在Python中使用Zipf類選擇從列表中選擇元素
假設我有一個列表:
objlist = ['Here', 'in', 'the', 'wall', 'why']
到目前爲止,我所看到的https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.zipf.html 但我不能找出解決方案。
在此先感謝。
只需使用numpy.random.zipf(shape_parameter)
的輸出作爲列表的索引。但是,有一個問題,zipf分發是未綁定的,並且該值可能比您的索引大。因此將其插入到try:
except:
塊中。
當您多次運行您的代碼時,會在您的列表中繪製不同的值。但是,由於zipf分配是未綁定的,並且您的列表索引不是,它不會完全zipf分佈。
Saple代碼:
objlist = ['Here', 'in', 'the', 'wall', 'why']
index = np.random.zipf([1.2, 1.2])
for idx in index:
if idx < len(objlist):
print(objlist[idx])
else:
print "Index {} exceed list".format(idx)
我希望我不是誤會你的要求,這裏是我的代碼:
import random
objlist = ['Here', 'in', 'the', 'wall', 'why']
print random.choice(objlist)
這只是隨機選擇價值。我想要按照選擇的拉鍊分佈。 – Antonis
要根據實際經驗齊普夫分佈選擇,你首先需要一張英文單詞頻率表。如果最頻繁的10萬人會,你可以得到一個here。
這是一個PDF,文本更容易處理,所以它轉換,在Linux上,你可以做
pdftotext freq100000.pdf
這將創建一個文本文件freq100000.txt,您可以使用下面的小腳本
import re
import numpy as np
record = re.compile('[0-9]+ [0-9]+ [a-z]+')
data = {}
for line in open('freq100000.txt'):
m = record.match(line.strip())
if not m is None:
rank, freq, word = m.group(0).split()
data[word] = int(rank), int(freq)
def rel_freqs(wlist):
freqs = np.array([data[word.lower()][1] for word in wlist])
ps = np.add.accumulate(freqs)
choice = np.searchsorted(ps, np.random.randint(ps[-1]))
return choice
rel_freqs(['Here', 'in', 'the', 'wall', 'why'])
函數rel_freqs
從列表中隨機選擇一個單詞並返回其索引。繪製單詞的概率與英語中出現的頻率成正比。
你的意思是這些單詞在英語中的實際頻率? –
是的。我想根據zipfs分佈選擇元素。如果我理解你的問題 – Antonis