资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

python绘制密度函数 python密度函数曲线

如何用python求出某已知正态分布的概率密度

Python正态分布概率计算方法,喜欢算法的伙伴们可以参考学习下。需要用到math模块。先了解一下这个模块方法,再来写代码会更好上手。

公司主营业务:成都网站建设、成都做网站、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联建站是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联建站推出政和免费做网站回馈大家。

def st_norm(u):

'''标准正态分布'''

import math

x=abs(u)/math.sqrt(2)

T=(0.0705230784,0.0422820123,0.0092705272,

0.0001520143,0.0002765672,0.0000430638)

E=1-pow((1+sum([a*pow(x,(i+1))

for i,a in enumerate(T)])),-16)

p=0.5-0.5*E if u0 else 0.5+0.5*E

return(p)

def norm(a,sigma,x):

'''一般正态分布'''

u=(x-a)/sigma

return(st_norm(u))

while 1:

'''输入一个数时默认为标准正态分布

输入三个数(空格隔开)时分别为期望、方差、x

输入 stop 停止'''

S=input('please input the parameters:\n')

if S=='stop':break

try:

L=[float(s) for s in S.split()]

except:

print('Input error!')

continue

if len(L)==1:

print('f(x)=%.5f'%st_norm(L[0]))

elif len(L)==3:

print('f(x)=%.5f'%norm(L[0],L[1],L[2]))

else:

print('Input error!')

python 绘制和密度图笔记

import pandasas pd

import numpyas np

import seabornas sns

import matplotlib.pyplotas plt

pd.set_option('display.max_columns', 10000)

pd.set_option('display.max_rows', 10000000000)

pd.set_option('display.width', 100000)

income = pd.read_excel(r'D:\bigData\0629demo\dataSource\income.xlsx')

fill_data = income.fillna(value={'workclass': income.workclass.mode()[0], 'occupation': income.occupation.mode()[0],

                            'native-country': income['native-country'].mode()[0]}, inplace=True)

# print(income.apply(lambda x: np.sum(x.isnull())))

# print(income)

print(income.describe())

print(income.describe(include=['object']))

# 设置绘图风格

plt.style.use('ggplot')

# 设置多图形组合

fig, axes = plt.subplots(2, 1)

# 绘制不同收入水平下的年龄核密度图

# kind='kde', label='=50K', ax=axes[0], legend=True, linestyle='-'

# kind='kde', label='50K', ax=axes[0], legend=True, linestyle='--'

income['age'][income.income ==' =50K'].plot(kind='kde', ax=axes[0], label='=50K', legend=True, linestyle='-')

income['age'][income.income ==' 50K'].plot(kind='kde', ax=axes[0], label='50K', legend=True, linestyle='--')

# 绘制不同收入水平下的周工作小时数核密度图

# kind='kde', label='= 50K', ax=axes[1], legend=True,  linestyle='-'

# kind='kde', label=' 50K', ax=axes[1], legend=True, linestyle='--'

income['hours-per-week'][income.income ==' =50K'].plot(kind='kde', label='= 50K', ax=axes[1], legend=True,

                                                    linestyle='-')

income['hours-per-week'][income.income ==' 50K'].plot(kind='kde', label=' 50K', ax=axes[1], legend=True,

                                                    linestyle='--')

plt.show()

# 构造不同收入水平下各种族人数的数据

race = pd.DataFrame(income.groupby(by=['race', 'income']).agg(np.size).loc[:, 'age'])

# 重设行索引

race = race.reset_index()

# 变量重命名

race.rename(columns={'age':'counts'}, inplace=True)

print(race)

# 排序

race.sort_values(by=['race', 'counts'], ascending=False, inplace=True)

# 构造不同收入水平下各家庭关系人数的数据

relationship = pd.DataFrame(income.groupby(by=['relationship', 'income']).agg(np.size).loc[:, 'age'])

relationship = relationship.reset_index()

relationship.rename(columns={'age':'counts'}, inplace=True)

relationship.sort_values(by=['relationship', 'counts'], ascending=False, inplace=True)

plt.figure(figsize=(15, 10))

sns.barplot(x='race', y='counts', hue='income', data=race)

plt.show()

plt.figure(figsize=(15, 10))

sns.barplot(x='relationship', y='counts', hue='income', data=relationship)

plt.show()

如何使用python做统计分析

Shape Parameters

形态参数

While a general continuous random variable can be shifted and scaled

with the loc and scale parameters, some distributions require additional

shape parameters. For instance, the gamma distribution, with density

γ(x,a)=λ(λx)a−1Γ(a)e−λx,

requires the shape parameter a. Observe that setting λ can be obtained by setting the scale keyword to 1/λ.

虽然一个一般的连续随机变量可以被位移和伸缩通过loc和scale参数,但一些分布还需要额外的形态参数。作为例子,看到这个伽马分布,这是它的密度函数

γ(x,a)=λ(λx)a−1Γ(a)e−λx,

要求一个形态参数a。注意到λ的设置可以通过设置scale关键字为1/λ进行。

Let’s check the number and name of the shape parameters of the gamma

distribution. (We know from the above that this should be 1.)

让我们检查伽马分布的形态参数的名字的数量。(我们知道从上面知道其应该为1)

from scipy.stats import gamma

gamma.numargs

1

gamma.shapes

'a'

Now we set the value of the shape variable to 1 to obtain the

exponential distribution, so that we compare easily whether we get the

results we expect.

现在我们设置形态变量的值为1以变成指数分布。所以我们可以容易的比较是否得到了我们所期望的结果。

gamma(1, scale=2.).stats(moments="mv")

(array(2.0), array(4.0))

Notice that we can also specify shape parameters as keywords:

注意我们也可以以关键字的方式指定形态参数:

gamma(a=1, scale=2.).stats(moments="mv")

(array(2.0), array(4.0))

Freezing a Distribution

冻结分布

Passing the loc and scale keywords time and again can become quite

bothersome. The concept of freezing a RV is used to solve such problems.

不断地传递loc与scale关键字最终会让人厌烦。而冻结RV的概念被用来解决这个问题。

rv = gamma(1, scale=2.)

By using rv we no longer have to include the scale or the shape

parameters anymore. Thus, distributions can be used in one of two ways,

either by passing all distribution parameters to each method call (such

as we did earlier) or by freezing the parameters for the instance of the

distribution. Let us check this:

通过使用rv我们不用再更多的包含scale与形态参数在任何情况下。显然,分布可以被多种方式使用,我们可以通过传递所有分布参数给对方法的每次调用(像我们之前做的那样)或者可以对一个分布对象冻结参数。让我们看看是怎么回事:

rv.mean(), rv.std()

(2.0, 2.0)

This is indeed what we should get.

这正是我们应该得到的。

Broadcasting

广播

The basic methods pdf and so on satisfy the usual numpy broadcasting

rules. For example, we can calculate the critical values for the upper

tail of the t distribution for different probabilites and degrees of

freedom.

像pdf这样的简单方法满足numpy的广播规则。作为例子,我们可以计算t分布的右尾分布的临界值对于不同的概率值以及自由度。

stats.t.isf([0.1, 0.05, 0.01], [[10], [11]])

array([[ 1.37218364, 1.81246112, 2.76376946],

[ 1.36343032, 1.79588482, 2.71807918]])

Here, the first row are the critical values for 10 degrees of freedom

and the second row for 11 degrees of freedom (d.o.f.). Thus, the

broadcasting rules give the same result of calling isf twice:

这里,第一行是以10自由度的临界值,而第二行是以11为自由度的临界值。所以,广播规则与下面调用了两次isf产生的结果相同。

stats.t.isf([0.1, 0.05, 0.01], 10)

array([ 1.37218364, 1.81246112, 2.76376946])

stats.t.isf([0.1, 0.05, 0.01], 11)

array([ 1.36343032, 1.79588482, 2.71807918])

If the array with probabilities, i.e, [0.1, 0.05, 0.01] and the array of

degrees of freedom i.e., [10, 11, 12], have the same array shape, then

element wise matching is used. As an example, we can obtain the 10% tail

for 10 d.o.f., the 5% tail for 11 d.o.f. and the 1% tail for 12 d.o.f.

by calling

但是如果概率数组,如[0.1,0.05,0.01]与自由度数组,如[10,11,12]具有相同的数组形态,则元素对应捕捉被作用,我们可以分别得到10%,5%,1%尾的临界值对于10,11,12的自由度。

stats.t.isf([0.1, 0.05, 0.01], [10, 11, 12])

array([ 1.37218364, 1.79588482, 2.68099799])

Specific Points for Discrete Distributions

离散分布的特殊之处

Discrete distribution have mostly the same basic methods as the

continuous distributions. However pdf is replaced the probability mass

function pmf, no estimation methods, such as fit, are available, and

scale is not a valid keyword parameter. The location parameter, keyword

loc can still be used to shift the distribution.

离散分布的简单方法大多数与连续分布很类似。当然像pdf被更换为密度函数pmf,没有估计方法,像fit是可用的。而scale不是一个合法的关键字参数。Location参数,关键字loc则仍然可以使用用于位移。

The computation of the cdf requires some extra attention. In the case of

continuous distribution the cumulative distribution function is in most

standard cases strictly monotonic increasing in the bounds (a,b) and

has therefore a unique inverse. The cdf of a discrete distribution,

however, is a step function, hence the inverse cdf, i.e., the percent

point function, requires a different definition:

ppf(q) = min{x : cdf(x) = q, x integer}

Cdf的计算要求一些额外的关注。在连续分布的情况下,累积分布函数在大多数标准情况下是严格递增的,所以有唯一的逆。而cdf在离散分布,无论如何,是阶跃函数,所以cdf的逆,分位点函数,要求一个不同的定义:

ppf(q) = min{x : cdf(x) = q, x integer}

For further info, see the docs here.

为了更多信息可以看这里。

We can look at the hypergeometric distribution as an example

from scipy.stats import hypergeom

[M, n, N] = [20, 7, 12]

我们可以看这个超几何分布的例子

from scipy.stats import hypergeom

[M, n, N] = [20, 7, 12]

If we use the cdf at some integer points and then evaluate the ppf at

those cdf values, we get the initial integers back, for example

如果我们使用在一些整数点使用cdf,它们的cdf值再作用ppf会回到开始的值。

x = np.arange(4)*2

x

array([0, 2, 4, 6])

prb = hypergeom.cdf(x, M, n, N)

prb

array([ 0.0001031991744066, 0.0521155830753351, 0.6083591331269301,

0.9897832817337386])

hypergeom.ppf(prb, M, n, N)

array([ 0., 2., 4., 6.])

If we use values that are not at the kinks of the cdf step function, we get the next higher integer back:

如果我们使用的值不是cdf的函数值,则我们得到一个更高的值。

hypergeom.ppf(prb + 1e-8, M, n, N)

array([ 1., 3., 5., 7.])

hypergeom.ppf(prb - 1e-8, M, n, N)

array([ 0., 2., 4., 6.])

统计学入门级:常见概率分布+python绘制分布图

如果随机变量X的所有取值都可以逐个列举出来,则称X为离散型随机变量。相应的概率分布有二项分布,泊松分布。

如果随机变量X的所有取值无法逐个列举出来,而是取数轴上某一区间内的任一点,则称X为连续型随机变量。相应的概率分布有正态分布,均匀分布,指数分布,伽马分布,偏态分布,卡方分布,beta分布等。(真多分布,好恐怖~~)

在离散型随机变量X的一切可能值中,各可能值与其对应概率的乘积之和称为该随机变量X的期望值,记作E(X) 。比如有随机变量,取值依次为:2,2,2,4,5。求其平均值:(2+2+2+4+5)/5 = 3。

期望值也就是该随机变量总体的均值。 推导过程如下:

= (2+2+2+4+5)/5

= 1/5 2 3 + 4/5 + 5/5

= 3/5 2 + 1/5 4 + 1/5 5

= 0.6 2 + 0.2 4 + 0.2 5

= 60% 2 + 20% 4 + 20%*5

= 1.2 + 0.8 + 1

= 3

倒数第三步可以解释为值为2的数字出现的概率为60%,4的概率为20%,5的概率为20%。 所以E(X) = 60% 2 + 20% 4 + 20%*5 = μ = 3。

0-1分布(两点分布),它的随机变量的取值为1或0。即离散型随机变量X的概率分布为:P{X=0} = 1-p, P{X=1} = p,即:

则称随机变量X服从参数为p的0-1分布,记作X~B(1,p)。

在生活中有很多例子服从两点分布,比如投资是否中标,新生婴儿是男孩还是女孩,检查产品是否合格等等。

大家非常熟悉的抛硬币试验对应的分布就是二项分布。抛硬币试验要么出现正面,要么就是反面,只包含这两个结果。出现正面的次数是一个随机变量,这种随机变量所服从的概率分布通常称为 二项分布 。

像抛硬币这类试验所具有的共同性质总结如下:(以抛硬币为例)

通常称具有上述特征的n次重复独立试验为n重伯努利试验。简称伯努利试验或伯努利试验概型。特别地,当试验次数为1时,二项分布服从0-1分布(两点分布)。

举个栗子:抛3次均匀的硬币,求结果出现有2个正面的概率 。

已知p = 0.5 (出现正面的概率) ,n = 3 ,k = 2

所以抛3次均匀的硬币,求结果出现有2个正面的概率为3/8。

二项分布的期望值和方差 分别为:

泊松分布是用来描述在一 指定时间范围内或在指定的面积或体积之内某一事件出现的次数的分布 。生活中服从泊松分布的例子比如有每天房产中介接待的客户数,某微博每月出现服务器瘫痪的次数等等。 泊松分布的公式为 :

其中 λ 为给定的时间间隔内事件的平均数,λ = np。e为一个数学常数,一个无限不循环小数,其值约为2.71828。

泊松分布的期望值和方差 分别为:

使用Python绘制泊松分布的概率分布图:

因为连续型随机变量可以取某一区间或整个实数轴上的任意一个值,所以通常用一个函数f(x)来表示连续型随机变量,而f(x)就称为 概率密度函数 。

概率密度函数f(x)具有如下性质 :

需要注意的是,f(x)不是一个概率,即f(x) ≠ P(X = x) 。在连续分布的情况下,随机变量X在a与b之间的概率可以写成:

正态分布(或高斯分布)是连续型随机变量的最重要也是最常见的分布,比如学生的考试成绩就呈现出正态分布的特征,大部分成绩集中在某个范围(比如60-80分),很小一部分往两端倾斜(比如50分以下和90多分以上)。还有人的身高等等。

正态分布的定义 :

如果随机变量X的概率密度为( -∞x+∞):

则称X服从正态分布,记作X~N(μ,σ²)。其中-∞μ+∞,σ0, μ为随机变量X的均值,σ为随机变量X的标准差。 正态分布的分布函数

正态分布的图形特点 :

使用Python绘制正态分布的概率分布图:

正态分布有一个3σ准则,即数值分布在(μ-σ,μ+σ)中的概率为0.6827,分布在(μ-2σ,μ+2σ)中的概率为0.9545,分布在(μ-3σ,μ+3σ)中的概率为0.9973,也就是说大部分数值是分布在(μ-3σ,μ+3σ)区间内,超出这个范围的可能性很小很小,仅占不到0.3%,属于极个别的小概率事件,所以3σ准则可以用来检测异常值。

当μ=0,σ=1时,有

此时的正态分布N(0,1) 称为标准正态分布。因为μ,σ都是确定的取值,所以其对应的概率密度曲线是一条 形态固定 的曲线。

对标准正态分布,通常用φ(x)表示概率密度函数,用Φ(x)表示分布函数:

假设有一次物理考试特别难,满分100分,全班只有大概20个人及格。与此同时语文考试很简单,全班绝大部分都考了90分以上。小明的物理和语文分别考了60分和80分,他回家后告诉家长,这时家长能仅仅从两科科目的分值直接判断出这次小明的语文成绩要比物理好很多吗?如果不能,应该如何判断呢?此时Z-score就派上用场了。 Z-Score的计算定义 :

即 将随机变量X先减去总体样本均值,再除以总体样本标准差就得到标准分数啦。如果X低于平均值,则Z为负数,反之为正数 。通过计算标准分数,可以将任何一个一般的正态分布转化为标准正态分布。

小明家长从老师那得知物理的全班平均成绩为40分,标准差为10,而语文的平均成绩为92分,标准差为4。分别计算两科成绩的标准分数:

物理:标准分数 = (60-40)/10 = 2

语文:标准分数 = (85-95)/4 = -2.5

从计算结果来看,说明这次考试小明的物理成绩在全部同学中算是考得很不错的,而语文考得很差。

指数分布可能容易和前面的泊松分布混淆,泊松分布强调的是某段时间内随机事件发生的次数的概率分布,而指数分布说的是 随机事件发生的时间间隔 的概率分布。比如一班地铁进站的间隔时间。如果随机变量X的概率密度为:

则称X服从指数分布,其中的参数λ0。 对应的分布函数 为:

均匀分布的期望值和方差 分别为:

使用Python绘制指数分布的概率分布图:

均匀分布有两种,分为 离散型均匀分布和连续型均匀分布 。其中离散型均匀分布最常见的例子就是抛掷骰子啦。抛掷骰子出现的点数就是一个离散型随机变量,点数可能有1,2,3,4,5,6。每个数出现的概率都是1/6。

设连续型随机变量X具有概率密度函数:

则称X服从区间(a,b)上的均匀分布。X在等长度的子区间内取值的概率相同。对应的分布函数为:

f(x)和F(x)的图形分别如下图所示:

均匀分布的期望值和方差 分别为:

如何在Python中实现这五类强大的概率分布

举个例子,一个表示抛硬币结果的随机变量可以表示成

Python

X = {1 如果正面朝上,

2 如果反面朝上}

随机变量是一个变量,它取值于一组可能的值(离散或连续的),并服从某种随机性。随机变量的每个可能取值的都与一个概率相关联。随机变量的所有可能取值和与之相关联的概率就被称为概率分布(probability distributrion)。

我鼓励大家仔细研究一下scipy.stats模块。

概率分布有两种类型:离散(discrete)概率分布和连续(continuous)概率分布。

离散概率分布也称为概率质量函数(probability mass function)。离散概率分布的例子有伯努利分布(Bernoulli distribution)、二项分布(binomial distribution)、泊松分布(Poisson distribution)和几何分布(geometric distribution)等。

连续概率分布也称为概率密度函数(probability density function),它们是具有连续取值(例如一条实线上的值)的函数。正态分布(normal distribution)、指数分布(exponential distribution)和β分布(beta distribution)等都属于连续概率分布。

python制作分布图

制作分布图类似密度图,在python中利用pandas来提取分布数据是比较方便的。主要用到pandas的cut和groupby等函数。

官方文档链接

主要参数为x和bins。

x为数据源,数组格式的都支持,list,numpy.narray, pandas.Series。

bins可以为int,也可以为序列。

我们定义bins为一个序列,默认为左开右闭的区间:

对言值列按cats做groupby,然后调用get_stats统计函数,再用unstack函数将层次化的行索引“展开”为列。

G2在之前的文章中有介绍,文章 《python结合G2绘制精美图形》 。

一句话绘制出来,但具体的区间段难以区分出来。

bokeh是python的一个优秀的绘图工具包,与pandas结合的比较好。 bokeh文档

作者原文链接: python制作分布图


分享标题:python绘制密度函数 python密度函数曲线
浏览地址:http://cdkjz.cn/article/dodiggg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220