Extension end assistant 2021-08-05 09:44:55 阅读数:344

本文一共[544]字，预计阅读时长:1分钟~

bayesian
mcmc
extended
tecdat
language

This article will talk about Stan And how to R Use in rstan establish Stan Model . Even though Stan It provides documentation using its programming language and a user's guide with examples , But for beginners , This may be difficult to understand .

Stan Is a programming language for specifying statistical models . It is most often used as a basis for Bayesian analysis MCMC Sampler . Markov chain Monte Carlo （MCMC） It's a sampling method , Allows you to estimate a probability distribution without knowing all the mathematical properties of the distribution . It is particularly useful in Bayesian inference , Because a posteriori distribution can't be written as an expression . To use Stan, The user wants to write a Stan Program , Represent their statistical model . This program specifies the parameters in the model and the target a posteriori density .Stan The code is compiled and run with the data , Output a posteriori simulation of a set of parameters .Stan And the most popular data analysis language , Such as R、Python、shell、MATLAB、Julia and Stata The interface of . We will focus on R Use in Stan.

`rstan`

`rstan allow R The user implements the Bayesian model . You can use familiar formulas and data.frame grammar （ Such as lm()） To fit the model . By providing precompiled for common model types stan Code to implement this Simpler Syntax . It is very convenient to use , But only for specific " Commonly used " Model type . If you need to fit different model types , Then you need to use it yourself rstan code .`

The model fitting function is prefixed with stan_ Start , End with model type . The modeling function has two necessary parameters .

- The formula . A formula that specifies dependent and independent variables （y ~ x1 + x2）.

- data. A data frame containing the variables in the formula .

Besides , There is also an optional a priori parameter , It allows you to change the default a priori distribution .

stan() Function to read and compile your stan Code , And fit the model on your data set .

stan() The function has two necessary arguments .

- file . Include your Stan programmatic .stan Path to file .

- data. A named list , Provide data for the model .

As a simple example to demonstrate how to specify a model in these packages , We will use car data to fit a linear regression model . Our dependent variable is mpg, All other variables are independent variables .

First , We will fit the model . For linear regression , We use stan function .

The output shows a summary of the parameters , Including the average 、 Standard deviation and magnitude . Besides , It also shows MCMC Diagnostic statistics Rhat And effective sample size . These statistics are useful for assessing MCMC Whether the algorithm converges is very important .

Next , We will use rstan To draw up a model of the contract . Here is our model stan Code , Save in a file called stan In the file of （ You can RStudio Create a .stan file , Or use any text editor , And save with the extension .stan The file of ）.

Stan Code in " Block " Structured in . Every Stan Each model requires three blocks , Data 、 Parameters and models .

Data blocks are used to declare variables read in as data . In our case , We have the result vector （y） And prediction matrix （X）. When a matrix or vector is declared as a variable , You need to specify the dimensions of the object at the same time . therefore , We will also read the number of observations （N） And the number of predictors （K）.

The variables declared in the parameter block are the variables that will be Stan Sampled variables . In the case of linear regression , The parameter of interest is the intercept term （alpha） And the coefficient of the predictor （beta）. Besides , And the error term ,sigma.

The model block is where the variable probability declaration is defined . ad locum , We specify that the target variable has a normal distribution , The average value is α+X*β, The standard deviation is sigma. In this block , You can also specify a priori distribution of parameters . By default , The parameter is given a flat （ Non informative ） transcendental .

Besides , There are also some optional blocks ： function 、 Converted data 、 Parameters converted and number generated .

Next , We need to Stan The program formats our data in the desired way .stan() The function requires data to be passed in as a named list , The elements are the variables you define in the data block . For this program , We create an element for N、K、X and Y A list of .

Now we have our code and data ready , We pass them on to the function to fit the model .

` Output similar summary statistics , Include the average value of each parameter 、 Standard deviation and magnitude . These results may be similar but not identical . Why they are different , Because the statistics are calculated based on a posteriori random sampling .`

When using MCMC When fitting a model , It is important to check whether the chain converges . We recommend visualization to visually check MCMC Diagnostic results of . We'll create a track map ,Rhat Value diagram .

First , Let's create a trajectory diagram . The trajectory shows MCMC Sampling values of parameters during iteration . If the model has converged , Then the trajectory should look like a random scatter around the average . If the chain winds in parameter space , Or the chain converges to different values , That proves a problem . Let's demonstrate .

These trajectories show that , Both models have converged . For all parameters , All four chains are mixed , There is no obvious trend .

Next , We will check Rhat value .Rhat It is a convergence diagnosis method , It compares the parameter estimates of each chain . If the chain has converged and mixed well , that Rhat The value should be close to 1. If the chain does not converge to the same value , that Rhat Value will be greater than 1.Rhat The value is 1.05 Or higher , It shows that there is a convergence problem .rhat() The function needs a Rhat The vector of values as input , So we first extract Rhat value .

be-all Rhat Values are lower than 1.05, It shows that there is no convergence problem .

Stan It is a powerful tool for building Bayesian models , These bags make R Users can easily use Stan.

The most popular insights

版权声明：本文为[Extension end assistant]所创，转载请带上原文链接，感谢。 https://car.inotgo.com/2021/08/20210805094322987R.html

- "Xie Dajiao" Yu Yuexian died in a car accident, and their lives were also terminated by the accident
- At the age of 44, Chen Shu appeared in the brand store to shop, bought three carts of clothes, and his body size was exposed
- Buy Volvo to avoid this car. It is small and expensive. The sales volume in June was only 350 units!
- "Xie Dajiao" died in a car accident in Yuexian. He was only 50 years old. Friends in the circle sent messages to mourn
- Police responded to the cause and details of Yu Yuexian's car accident: driving into a camel in the early morning, and the driver and others were injured
- Actor Yu Yuexian died in a car accident at the age of 50. The police informed Yu Yuexian of the cause of the car accident
- “谢大脚”车祸去世，小沈阳姜超发微博悼念，翟天临都“很难过”
- 被惋惜的不止“谢大脚”，这3位车祸去世的明星，每位都让人心痛
- 警方通报于月仙车祸去世：小型客车发生交通事故造成于某某死亡
- 50岁于月仙车祸去世，与老公结婚20多年无子！把患病弟弟当儿子养
- "Xie Dajiao" died in a car accident. Xiao Shenyang Jiang Chao sent a microblog to mourn. Zhai Tianlin was "very sad"
- It is not just "Xie Dajiao" who is regretted. Each of the three stars who died in a car accident is heartbreaking
- The police reported that Yu Yuexian died in a car accident: a traffic accident on a minibus resulted in Yu's death
- Yu Yuexian, 50, died in a car accident and married her husband for more than 20 years without children! Raise your sick brother as a son
- 男星开百万豪车太高调，多次压线并占用应急车道，网友痛批没素质
- 于月仙车祸去世，《乡村爱情》官博发文：“仙”人已逝，如“月”婵娟
- The male star drove a million luxury cars too high-profile, pressed the line for many times and occupied the emergency lane. Netizens criticized him for lacking quality
- Yu Yuexian died in a car accident. The official blog of rural love wrote: "the immortal" is dead, such as the "Moon" Chan Juan
- 现在上车以太坊挖矿还有戏吗
- Now get on the bus and dig in Ethereum. Is there any play
- 于月仙车祸细节曝光，凌晨三点去参加活动，与丈夫张学松无儿无女
- The details of Yu Yuexian's car accident were exposed. She went to the event at 3 a.m. and had no children with her husband Zhang Xuesong
- 演员于月仙在阿拉善因发生车祸不幸去世
- Actor Yu Yuexian died in a car accident in Alashan
- 于月仙车祸前，在《乡村爱情》中已被边缘化，谢大脚成了广告符号
- 于月仙车祸去世：再见了，《乡村爱情》里的“小卖部女神”
- “谢大脚”于月仙车祸去世，众星发文悼念，章子怡说的话令人泪目
- Before Yu Yuexian's car accident, she was marginalized in rural love, and Xie Dajiao became an advertising symbol
- Yu Yuexian died in a car accident: goodbye, the "canteen goddess" in rural love
- 50岁“谢大脚”车祸去世，《乡村爱情》15年，已经有5位演员走了
- 50岁于月仙车祸去世！途中和两只骆驼相撞，最后一条动态令人泪目
- 于月仙车祸去世，《乡村爱情》再无“谢大脚”，永远怀念！
- "Xie Dajiao" Yu Yuexian died in a car accident. The stars sent a document to mourn. Zhang Ziyi's words made people cry
- At the age of 50, "Xie Dajiao" died in a car accident. Five actors have left in "country love" for 15 years
- 一路走好！50岁“谢大脚”于月仙车祸去世，与老公结婚多年无儿女
- 警方通报于月仙车祸原因：与两头骆驼相撞，司机和其他成员只受伤。“乡爱”官微发文悼念
- Yu Yuexian, 50, died in a car accident! On the way, he collided with two camels, and the last one was tearful
- Yu Yuexian died in a car accident. There is no "Xie Dajiao" in rural love. I will always miss it!
- All the way! Xie Dajiao, 50, died in a car accident in Yuexian. He married his husband for many years without children
- The police informed Yu Yuexian of the cause of the accident: the driver and other members were only injured when they collided with two camels“ "Township love" official wechat sent a document to mourn
- 于月仙因车祸去世，长贵可以复活，但《乡村爱情》从此再无谢大脚
- 50岁于月仙车祸去世，《乡爱》再无谢大脚，小沈阳：小姨一路走好
- 于月仙车祸细节：被撞两只骆驼也死了，全车4人，只有她去世
- 赵本山小姨子车祸去世，《乡村爱情》剧组悼念，50岁一辈子未生子
- 毫无底线！于月仙车祸去世，网红直播谢大脚超市引众怒
- 50岁于月仙遭遇车祸突然离世：原来人生真的没有那么多来日方长
- Yu Yuexian died in a car accident, and Changgui can come back to life, but "country love" has never had Xie Dajiao again
- Yu Yuexian died in a car accident at the age of 50. There is no thanks for big feet in rural love. Little Shenyang: let's go all the way
- 警方通报于月仙车祸原因：与两只骆驼相撞！赵本山女儿发文悼念
- 蹭热度无底线？于月仙车祸去世，多位网红大脚超市直播被网友骂惨
- Details of Yu Yuexian's car accident: two camels were also killed. There were 4 people in the car, and only she died
- Zhao Benshan's sister-in-law died in a car accident. The crew of "rural love" mourned that she had no children at the age of 50
- No bottom line! Yu Yuexian died in a car accident. Xie Dajiao supermarket attracted public anger
- Yu Yuexian, 50, died suddenly in a car accident: it turns out that life really doesn't have so much time
- Police informed Yu Yuexian of the cause of the accident: collision with two camels! Zhao Benshan's daughter sent a document to mourn
- No bottom line for rubbing heat? Yu Yuexian died in a car accident. Many netizens scolded her for live broadcast in wanghongdajiao supermarket
- 《乡村爱情》谢大脚扮演者车祸去世：生命来来往往，来日并不方长
- Xie Dajiao's actor in rural love died in a car accident: life comes and goes, and the future is not long
- 著名演员于月仙：因车祸猝然离世，将悲痛和心碎留给丈夫
- Famous actor Yu Yuexian: died suddenly in a car accident, leaving grief and heartbreak to her husband