简体   繁体   English

在 Stan 调整线性回归的问题

[英]Problems adjusting Linear Regression at Stan

I'm having trouble adjusting a linear regression model on the stan.我在调整 stan 上的线性回归模型时遇到问题。 When observing the error message, the identification in the block part of the transformed parameters is noted.在观察错误信息时,会注意到转换参数的块部分中的标识。

See below the structure of the code in stan.请参阅下面的 stan 代码结构。

Packages:

library(rstan)
library(bayesplot)

Data:数据:

head(Orange)
cols <- c(colnames(Orange[-1]))
Orange <- Orange[,cols]
str(Orange)

Code in stan:斯坦代码:

See that the block structure within the stan follows the recommended pattern, however I am not able to identify which part of the code may seem wrong to me.看到 stan 中的块结构遵循推荐的模式,但是我无法确定代码的哪一部分对我来说可能是错误的。

y = Orange$circumference
x = Orange$age
n = length(y)

regresstan = '
data{
  int n;
  real y[n];
  real x[n];
}

parameters{
  real alpha;
  real beta;
  real sigma;
}

transformed parameters{
    real mu[n];
    mu = alpha + beta*x;
}

model{
  //Priors
  alpha ~ normal(0, 100);
  beta ~ normal(0, 100);
  sigma ~ uniform(0, 100);

  //Likelihood
    y ~ normal(mu, sigma);
}
'

Error:错误:

SYNTAX ERROR, MESSAGE(S) FROM PARSER:
No matches for: 

  real * real[ ]

Available argument signatures for operator*:

  real * real
  vector * real
  row_vector * real
  matrix * real
  row_vector * vector
  vector * row_vector
  matrix * vector
  row_vector * matrix
  matrix * matrix
  real * vector
  real * row_vector
  real * matrix

No matches for: 

  real + ill-formed

Available argument signatures for operator+:

  int + int
  real + real
  vector + vector
  row_vector + row_vector
  matrix + matrix
  vector + real
  row_vector + real
  matrix + real
  real + vector
  real + row_vector
  real + matrix
  +int
  +real
  +vector
  +row_vector
  +matrix

Expression is ill formed.
 error in 'modele28054257a16_a9d23411185fa271b60f20be43062e80' at line 16, column 23
  -------------------------------------------------
    14: transformed parameters{
    15:     real mu[n];
    16:     mu = alpha + beta*x;
                              ^
    17: }
  -------------------------------------------------

Error in stanc(file = file, model_code = model_code, model_name = model_name,  : 
  failed to parse Stan model 'a9d23411185fa271b60f20be43062e80' due to the above error.

The error comes from the transformed parameters block at the line错误来自该行的转换参数块

mu = alpha + beta*x;

The error is saying you can't multiply a real scalar by a real vector (the error of real * real[ ] ).错误是说您不能将实数标量乘以实数向量( real * real[ ]的误差)。 You can solve this by looping over the values of mu您可以通过循环 mu 的值来解决这个问题

transformed parameters {
  real mu[n];
  for(i in 1:n) {
    mu[i] = alpha + beta * x[i];
  }
}

which resolves the issue as now you have a real scalar times a real scalar.这解决了这个问题,因为现在你有一个真正的标量乘以一个真正的标量。

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

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