计算和绘制累积经验分布的练习

时间:2016-02-27 09:36:46

标签: python statistics montecarlo mcmc

我试图在Jonh Stachurski的书(一本专门教经济学家如何使用Python的教科书)中完成练习。其中之一是关于如何计算和绘制累积的经验分布。他们提供了一个名为ecdf的类来计算经验分布函数

# Filename: ecdf.py
# Author: John Stachurski
# Date: December 2008
# Corresponds to: Listing 6.3

class ECDF:

    def __init__(self, observations):
        self.observations = observations

    def __call__(self, x):
        counter = 0.0
        for obs in self.observations:
            if obs <= x:
                counter += 1
        return counter / len(self.observations)

并且练习读取

【Exercise 6.1.12】 Add a method to the ECDF class that uses Matplotlib to plot the em-
pirical distribution over a specified interval. Replicate the four graphs in figure 6.3
(modulo randomness).

这个数字是需要复制的 enter image description here

和算法错觉

enter image description here

以下是我的初步尝试

from ecdf import ECDF
import numpy as np
import matplotlib.pyplot as plt
from srs import SRS
from math import sqrt
from random import lognormvariate

# =========================
# parameters and arguments
# =========================
alpha, sigma2, s, delta = 0.3, 0.2, 0.5, 0.1
# numbers of draws
n = 1000
# length of each markov chain
t = 20
num_simu = [4,25,100,5000]

# Define F(k, z) = s k^alpha z + (1 - delta) k
F = lambda k, z: s * (k**alpha) * z + (1 - delta) * k 
lognorm = lambda: lognormvariate(0, sqrt(sigma2)) 


# =====================
#  create empirical distribution
# =====================

# different draw numbers
k = np.linspace(0,25,500)
for n in num_simu:
  for x in range(n):
    # list used to store capital stock (kt) in the last periods (t=20)
    kt = []  
    solow_srs = SRS(F=F, phi=lognorm, X=1.0)
    px = solow_srs.sample_path(t)
    kt.append(px[-1]) 
    # generate the empirical distribution function 
    F = ECDF(kt)
    prob_kt_n =   [F(i) for i in k]  # need to determine range
                                     # n refers to the n-th draw
# ==================================
# use for-loop to create subplots 
# ==================================   
#k = np.linspace(0,25,500)
#num_rows,num_cols = 2,2

给我带来的困难是1)如何在给定图表中存储不同抽奖号码的经验分布结果列表/数组。 2)如何使用for循环创建子图。我还遇到了一些其他小错误。 谢谢你的建议。

1 个答案:

答案 0 :(得分:0)

关于(1),我的建议是为每个观察数d = {}创建一个字典(例如d[n] = ECDF(data)然后n

Dunno关于(2)。