【问题标题】:Constructing Zipf Distribution with matplotlib, FITTED-LINE使用 matplotlib,FITTED-LINE 构建 Zipf 分布
【发布时间】:2016-08-24 04:23:57
【问题描述】:

我有一个段落列表,我想在它们的组合上运行 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")

目的 我尝试在此图中绘制“拟合线”,并将其值分配给变量。但是我不知道如何添加。对于这两个问题,我们将不胜感激。

【问题讨论】:

    标签: python python-2.7 matplotlib zipf


    【解决方案1】:

    我知道这个问题被问到已经有一段时间了。但是,我在scipy site 遇到了解决此问题的可能方法。
    我想我会在这里发帖以防其他人需要。

    我没有段落信息,所以这里有一个名为 frequency 的全新 dict,它的值是段落出现次数。

    然后我们获取它的值并转换为 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()
    

    情节

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      相关资源
      最近更新 更多