简体   繁体   English

使用python显示卡方分布的pdf

[英]Show the pdf of a chi-squared distribution using python

I'm trying to reconstruct the pdf of the chi-squared distribution with 3 degrees of freedom from a simulated sample. 我正在尝试从模拟样本中以3个自由度重建卡方分布的pdf。 Here is my python code: 这是我的python代码:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

norm = stats.norm(0, 1)

x1 = [x * x for x in np.random.randn(1000)]
x2 = [x * x for x in np.random.randn(1000)]
x3 = [x * x for x in np.random.randn(1000)]

f = x1 + x2 + x3

plt.hist(f, 100)
plt.show()

The result I got was this. 我得到的结果就是这个。

具有3个自由度的Chi分布

Of course this is wrong. 当然这是错误的。 As shown in Wikipedia, the pdf of the chi-squared distribution with 3 degrees of freedom should go upwards first from zero and go downwards later, not something keep climbing like mine. 如Wikipedia所示,具有3个自由度的卡方分布的pdf应该先从零开始向上,然后再向下,而不是像我这样不断攀登。 Is there anything wrong with my code? 我的代码有什么问题吗? The formula I used was as follows: 我使用的公式如下:

Q = x1^2 + x2^2 + x3^2 Q = x1 ^ 2 + x2 ^ 2 + x3 ^ 2

where x1, x2 and x3 are independent, standard normal random variables. 其中x1,x2和x3是独立的标准正态随机变量。

Although I tried your code and got the same result as you, if you use your 'norm' variable to generate the random values it seems to work. 尽管我尝试了您的代码并获得了与您相同的结果,但是如果您使用“ norm”变量生成随机值,则它似乎可以工作。

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

norm = stats.norm(0, 1)

x1 = norm.rvs(size=100000)**2
x2 = norm.rvs(size=100000)**2
x3 = norm.rvs(size=100000)**2

f = x1 + x2 + x3

plt.hist(f, 60, normed=True)

# Plot the theoretical density of f
x = np.arange(0, 30, .05)
plt.plot(x, stats.chi2.pdf(x, df=3), color='r', lw=2)
plt.show()

The result I got was 我得到的结果是

Chi2的直方图

The '+' operator works differently on Python lists than on Numpy arrays. “ +”运算符在Python列表上的工作方式不同于在Numpy数组上的工作方式。

f = x1 + x2 + x3

concatenates three lists into one. 将三个列表合并为一个。 However, you want to add the content of the three lists element-wise, which could be done like this: 但是,您想逐个元素地添加三个列表的内容,可以这样进行:

f = np.array(x1) + np.array(x2) + np.array(x3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM