R语言中dnorm, pnorm, qnorm与rnorm以及随机数

Python011

R语言中dnorm, pnorm, qnorm与rnorm以及随机数,第1张

--

title: R语言中dnorm, pnorm, qnorm与rnorm以及随机数

date: 2018-09-07 12:02:00

type: "tags"

tags:

在R语言中,与正态分布(或者说其它分布)有关的函数有四个,分别为dnorm,pnorm,qnorm和rnorm,其中,dnorm表示密度函数,pnorm表示分布函数,qnorm表示分位数函数,rnorm表示生成随机数的函数。在R中与之类似的函数还有很多,具体的可以通过 help(Distributions) 命令去查看,对于分位数或百分位数的一些介绍可以看这篇笔记 《分位数及其应用》 ,关于正态分布的知识可以看这篇笔记 《正态分布笔记》 。

现在这篇笔记就介绍一下这些函数的区别。

R提供了多种随机数生成器(random number generators, RNG),默认采用的是Mersenne twister方法产生的随机数,该方法是由Makoto Matsumoto和Takuji Nishimura于1997年提出来的,其循环周期是 。R里面还提供了了Wichmann-Hill、Marsaglia-Multicarry、Super-Duper、Knuth-TAOCP-2002、Knuth-TAOCP和L'Ecuyer-CMRG等几种随机数生成方法,可以通过 RNGkind() 函数进行更改,例如,如果要改为WIchmann-Hill方法,就使用如下语句:

在R中使用随机数函数,例如 rnorm() 函数来生成的随机数是不一样的,有时我们在做模拟时,为了比较不同的方法,就需要生成的随机数都一样,即重复生成相同的随机数,此时就可以使用 set.seed() 来设置随机数种子,其参数为整数,如下所示

dnorm 中的 d 表示 density , norm 表示正态贫,这个函数是正态分布的 概率密度(probability density)函数 。

正态分布的公式如下所示:

给定x,μ和σ后, dnorm() 这个函数返回的就是会返回上面的这个公式的值,这个值就是Z-score,如果是标准正态分布,那么上述的公式就变成了这个样子,如下所示:

现在看一个案例,如下所示:

dnorm(0,mean=0,sd=1) 由于是标准正态分布函数的概率密度,这个命令其实可以直接写为 dnorm(0) 即可,如下所示:

再看一个非标准正态分布的案例,如下所示:

虽然在 dnorm() 中,x是一个概率密度函数(PDF,Probability Density Function)的独立变量,但它也能看作是一组经过Z转换后的一组变量,现在我们看一下使用 dnorm 来绘制一个正态分布的概率密度函数曲线,如下所示:

现在使用 dnorm() 函数计算一下Z_scores的概率密度,如下所示:

现在绘图,如下所示:

从上面的结果可以看出,在每个Z-score处, dnorm 可以绘制出这个Z-score对应的正态分布的pdf的高度。

pnorm 函数中的 p 表示Probability,它的功能是,在正态分布的PDF曲线上,返回从负无穷到 q 的积分,其中这个 q 指的是一个Z-score。现在我们大概就可以猜测出 pnorm(0) 的值是0.5,因为在标准正态分布曲线上,当Z-score等于0时,这个点正好在标准正态分布曲线的正中间,那么从负无穷到0之间的曲线面积就是整个标准正态分布曲线下面积的一半,如下所示:

pnorm 函数还能使用 lower.tail 参数,如果 lower.tail 设置为 FALSE ,那么 pnorm() 函数返回的积分就是从 q 到正无穷区间的PDF下的曲线面积,因此我们就知道了, pnorm(q) 与 1-pnorm(q,lower.tail=FALSE) 的结果是一样的,如下所示:

在计算机出现之前的时代里,统计学家们使用正态分布进行统计时,通常是要查正态分布表的,但是,在计算机时代,通常都不使用正态分布表了,在R中, pnorm() 这个函数完全可以取代正态分布表了,现在我们使用一个Z-scores的向量来计算一下相应的累积概率,如下所示:

以上就是标准正态分布的 累积分布函数(CDF,Cumulative Distribution Function) 曲线。

简单来说, qnorm 是正态分布 累积分布函数(CDF,Cumulative Distribution Function) 的反函数,也就是说它可以视为 pnorm 的反函数,这里的 q 指的是quantile,即分位数。

使用 qnorm 这个函数可以回答这个问题:正态分布中的第p个分位数的Z-score是多少?

现在我们来计算一下,在正态分布分布中,第50百分位数的Z-score是多少,如下所示:

再来看一个案例:在正态分布中,第96个百分位的Z-score是多少,如下所示:

再来看一个案例:在正态分布中,第99个百分位的Z-score是多少,如下所示:

再来看一下 pnorm() 这个函数,如下所示:

从上面我们可以看到, pnorm 这个函数的功能是,我们知道某个Z-score是多少,它位于哪个分位数上。

接着我们进一步举例来说明一下 qnorm 和 pnorm 的具体功能,如下所示:

现在进行绘图,如下所示:

rnomr() 函数的功能用于生成一组符合正态分布的随机数,在学习各种统计学方法时, rnorm 这个函数应该是最常用的,它的参数有 n , mean , sd ,其中n表示生成的随机数,mean与sd分别表示正态分布的均值与标准差,现在举个例子,如下所示:

现在我们绘制一下上面的几个向量的直方图,看一下它们的均值是否在70附近,如下所示:

在R语言中,生成不同分布的各种类型的函数都是以d,p,q,r开头的,使用原理跟上面的正态分布都一样。

sample() 函数是一个用于生成随机数的重要的核心函数,如果仅传递一个数值n给它,就会返回一个从1到n的自然数的排列,如果传递是 n:m 就是生成从n到m的随机数,如是是 7,5 ,则会生成5个小于7的随机数,如下所示:

从上面的结果可以看出来,这些数字都是不同的,也就是说,sample函数默认情况下是不重复抽样,每个值只出现一次,如果允许有重复抽样,需要添加参数 replace = TRUE ,如下所示:

sample函数通常会从某些向量中随机挑一些参数,如下所示:

也可以挑日期,如下所示:

上述分布函数前面加上r,p、q、d就可以表示相应的目的:

function D = CART(train_features, train_targets, params, region)

% Classify using classification and regression trees

% Inputs:

% features - Train features

% targets- Train targets

% params - [Impurity type, Percentage of incorrectly assigned samples at a node]

% Impurity can be: Entropy, Variance (or Gini), or Missclassification

% region- Decision region vector: [-x x -y y number_of_points]

%

% Outputs

% D - Decision sufrace

[Ni, M] = size(train_features)

%Get parameters

[split_type, inc_node] = process_params(params)

%For the decision region

N = region(5)

mx = ones(N,1) * linspace (region(1),region(2),N)

my = linspace (region(3),region(4),N)' * ones(1,N)

flatxy = [mx(:), my(:)]'

%Preprocessing

[f, t, UW, m] = PCA(train_features, train_targets, Ni, region)

train_features = UW * (train_features - m*ones(1,M))

flatxy = UW * (flatxy - m*ones(1,N^2))

%Build the tree recursively

disp('Building tree')

tree= make_tree(train_features, train_targets, M, split_type, inc_node, region)

%Make the decision region according to the tree

disp('Building decision surface using the tree')

targets = use_tree(flatxy, 1:N^2, tree)

D = reshape(targets,N,N)

%END

function targets = use_tree(features, indices, tree)

%Classify recursively using a tree

if isnumeric(tree.Raction)

%Reached an end node

targets = zeros(1,size(features,2))

targets(indices) = tree.Raction(1)

else

%Reached a branching, so:

%Find who goes where

in_right= indices(find(eval_r(tree.Raction)))

in_left = indices(find(eval_r(tree.Laction)))

Ltargets = use_tree(features, in_left, tree.left)

Rtargets = use_tree(features, in_right, tree.right)

targets = Ltargets + Rtargets

end

%END use_tree

function tree = make_tree(features, targets, Dlength, split_type, inc_node, region)

%Build a tree recursively

if (length(unique(targets)) == 1),

%There is only one type of targets, and this generates a warning, so deal with it separately

tree.right = []

tree.left = []

tree.Raction= targets(1)

tree.Laction= targets(1)

break

end

[Ni, M] = size(features)

Nt = unique(targets)

N = hist(targets, Nt)

if ((sum(N <Dlength*inc_node) == length(Nt) - 1) | (M == 1)),

%No further splitting is neccessary

tree.right = []

tree.left = []

if (length(Nt) ~= 1),

MLlabel = find(N == max(N))

else

MLlabel = 1

end

tree.Raction= Nt(MLlabel)

tree.Laction= Nt(MLlabel)

else

%Split the node according to the splitting criterion

deltaI = zeros(1,Ni)

split_point = zeros(1,Ni)

op = optimset('Display', 'off')

for i = 1:Ni,

split_point(i) = fminbnd('CARTfunctions', region(i*2-1), region(i*2), op, features, targets, i, split_type)

I(i) = feval_r('CARTfunctions', split_point(i), features, targets, i, split_type)

end

[m, dim] = min(I)

loc = split_point(dim)

%So, the split is to be on dimention 'dim' at location 'loc'

indices = 1:M

tree.Raction= ['features(' num2str(dim) ',indices) > ' num2str(loc)]

tree.Laction= ['features(' num2str(dim) ',indices) <= ' num2str(loc)]

in_right= find(eval_r(tree.Raction))

in_left = find(eval_r(tree.Laction))

if isempty(in_right) | isempty(in_left)

%No possible split found

tree.right = []

tree.left = []

if (length(Nt) ~= 1),

MLlabel = find(N == max(N))

else

MLlabel = 1

end

tree.Raction= Nt(MLlabel)

tree.Laction= Nt(MLlabel)

else

%...It's possible to build new nodes

tree.right = make_tree(features(:,in_right), targets(in_right), Dlength, split_type, inc_node, region)

tree.left = make_tree(features(:,in_left), targets(in_left), Dlength, split_type, inc_node, region)

end

end