我有一个段落列表,我想在它们的组合上运行zipf发行版。
我的代码如下:
from itertools import *
from pylab import *
from collections import Counter
import matplotlib.pyplot as plt
paragraphs = " ".join(targeted_paragraphs)
for paragraph in paragraphs:
frequency = Counter(paragraph.split())
counts = array(frequency.values())
tokens = frequency.keys()
ranks = arange(1, len(counts)+1)
indices = argsort(-counts)
frequencies = counts[indices]
loglog(ranks, frequencies, marker=".")
title("Zipf plot for Combined Article Paragraphs")
xlabel("Frequency Rank of Token")
ylabel("Absolute Frequency of Token")
grid(True)
for n in list(logspace(-0.5, log10(len(counts)-1), 20).astype(int)):
dummy = text(ranks[n], frequencies[n], " " + tokens[indices[n]],
verticalalignment="bottom",
horizontalalignment="left")
目的我试图在该图中绘制“拟合线”,并将其值分配给变量。但是我不知道如何添加。对于这两个问题的任何帮助将不胜感激。
最佳答案
我知道距问这个问题已经有一段时间了。但是,我在scipy site处遇到了针对此问题的可能解决方案。
我以为我会在这里发布,以防其他人需要。
我没有段落信息,因此这里是一个被称为dict
的frequency
,它具有段落出现作为其值。
然后,我们获取其值并转换为numpy数组。定义zipf distribution parameter
,该值必须> 1。
最后显示样本的直方图以及概率密度函数
工作代码:
import random
import matplotlib.pyplot as plt
from scipy import special
import numpy as np
#Generate sample dict with random value to simulate paragraph data
frequency = {}
for i,j in enumerate(range(50)):
frequency[i]=random.randint(1,50)
counts = frequency.values()
tokens = frequency.keys()
#Convert counts of values to numpy array
s = np.array(counts)
#define zipf distribution parameter. Has to be >1
a = 2.
# Display the histogram of the samples,
#along with the probability density function
count, bins, ignored = plt.hist(s, 50, normed=True)
plt.title("Zipf plot for Combined Article Paragraphs")
x = np.arange(1., 50.)
plt.xlabel("Frequency Rank of Token")
y = x**(-a) / special.zetac(a)
plt.ylabel("Absolute Frequency of Token")
plt.plot(x, y/max(y), linewidth=2, color='r')
plt.show()
情节
关于python - 使用FITTED-LINE matplotlib构建Zipf分布,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39114402/