如何获取Python中Pareto分布的Q-Q图?

时间:2018-08-24 12:13:37

标签: python statistics probability

Q-Q图用于获得一组数据点与理论分布之间的拟合优度。以下是获得积分的过程。

  1. 选择要使用的样品。用表示第i个样本的X(i)对选定的样本进行排序
  2. 查找与样本对应的模型值。这是分两个步骤完成的,

    a。将每个样本与其代表的百分位数相关联。 pi =(i-0.5)/ n

    b。计算与该百分比相关的模型值。这是通过反转模型CDF来完成的,就像从模型分布中生成随机变量一样。因此,与样本i对应的模型值为Finverse(pi)。

    c。使用n点绘制Q-Q图

(X(i),Finverse(pi))1≤i≤n

使用这种方法,我想到了以下python实现。

_distn_names = ["pareto"]
def fit_to_all_distributions(data):
    dist_names = _distn_names

    params = {}
    for dist_name in dist_names:
        try:
            dist = getattr(st, dist_name)
            param = dist.fit(data)

            params[dist_name] = param
        except Exception:
            print("Error occurred in fitting")
            params[dist_name] = "Error"

    return params 

def get_q_q_plot(values, dist, params):
    values.sort()

    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    x = []

    for i in range(len(values)):
        x.append((i-0.5)/len(values))

    y = getattr(st, dist).ppf(x, loc=loc, scale=scale, *arg)

    y = list(y)

    emp_percentiles = values
    dist_percentiles = y

    print("Emperical Percentiles")
    print(emp_percentiles)

    print("Distribution Percentiles")
    print(dist_percentiles)

    plt.figure()
    plt.xlabel('dist_percentiles')
    plt.ylabel('actual_percentiles')
    plt.title('Q Q plot')
    plt.plot(dist_percentiles, emp_percentiles)
    plt.savefig("/path/q-q-plot.png")

b = 2.62
latencies = st.pareto.rvs(b, size=500)
data = pd.Series(latencies)
params = fit_to_all_distributions(data)

pareto_params = params["pareto"]

get_q_q_plot(latencies, "pareto", pareto_params)

理想情况下,我应该得到一条直线,但这就是我得到的。

QQ plot

为什么我没有直线?我的实现中有什么问题吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码获取任何分布的Q-Q图(scipy统计信息中有82个)。

import os
import matplotlib.pyplot as plt
import sys
import math
import numpy as np
import scipy.stats as st
from scipy.stats._continuous_distns import _distn_names
from scipy.optimize import curve_fit

def get_q_q_plot(latency_values, distribution):

    distribution = getattr(st, distribution)
    params = distribution.fit(latency_values)

    latency_values.sort()

    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    x = []

    for i in range(1, len(latency_values)):
        x.append((i-0.5) / len(latency_values))

    y = distribution.ppf(x, loc=loc, scale=scale, *arg)

    y = list(y)

    emp_percentiles = latency_values[1:]
    dist_percentiles = y

    return emp_percentiles, dist_percentiles