Rename parameters in Stan for traceplot

When I plot a traceplot for a logistic regression model, the names used for the parameters are beta[1], beta[2], beta[3], etc… How can I change these?
I’ve tried looking into rename_pars from the brms package but there’s very minimal documentation on how to use it. I tried multiple things (I separate them by an OR in the last line of the code listing below) but none of them work.

stanfit <-  stan(file = "logisticRegressionModel.stan", data = totalTrainList, 
             iter=10000, seed=42)
traceplot(pars=c(stanfit))
fit <- brm(firstTeamWinStatus ~ winPctDiff + currScoreAvgDiff + otherScoreAvgDiff
           + currFTPctDiff + otherFGPctDiff + currFG3PctDiff + otherFG3PctDiff
           + currFTPctDiff + otherFTPctDiff + currRebAvgDiff + otherRebAvgDiff
           + currAstAvgDiff + otherAstAvgDiff + currTOAvgDiff + otherTOAvgDiff
           + currDefAvgDiff + otherDefAvgDiff + SeedDiff + SeedAdd, 
           data = MM2003To2021Dataset, empty = TRUE)
fit$fit <- stanfit
fit <- rename_pars(fit)
traceplot(stanfit) OR traceplot(fit) OR traceplot(fit$fit)  

You can change the variable names in the model object before running traceplot. The example below shows one way to do this.

library(tidyverse)
library(brms)
library(rstan)

# Logistic regression
prior = prior(normal(0,1), class="b")
iris = iris %>% mutate(Species = ifelse(Species=="setosa", "setosa", "other"))

fit <- brm(Species ~ ., data = iris,
           family = bernoulli(),
           prior=prior,
           iter=2000, warmup=1000, cores=4)

traceplot(fit$fit)

names(fit$fit)

[1] “b_Intercept” “b_Sepal.Length” “b_Sepal.Width” “b_Petal.Length” “b_Petal.Width” “lp__”

# Rename variables
fit$fit %>% 
  setNames(gsub("b_", "", names(.)) %>% gsub("\\.", " ", .)) %>% 
  traceplot()

2 Likes

So is there no way to make this work using Stan code? I have a pretty involved model in Stan:

data {
  int<lower=0> N;   // number of data items
  int<lower=0> K;   // number of predictors
  matrix[N, K] X;   // predictor matrix
  int y[N];         // outcome vector
  int relativePrior;
  int shrinkageIdx[4]; 
  int noShrinkageIdx[23];
}
parameters {
  real alpha;       // intercept
  vector[K] beta;   // coefficients for predictors
}
model {
  // Priors:
  alpha ~ normal(0, 10);
  if (relativePrior) {
    for (k in shrinkageIdx) {
      beta[k] ~ normal(0, 1);
    }
    for (k in noShrinkageIdx) {
      beta[k] ~ normal(0, 10);
    }
  }
  else {
    beta ~ normal(0, 10);
  }
  // Likelihood
  y ~ bernoulli_logit(alpha + X * beta);
}
generated quantities {
  vector[N] y_preds;
  real correct = 0;
  real accuracy;
  for (n in 1:N) {
    y_preds[n] = bernoulli_logit_rng(alpha + X[n] * beta);
    correct += logical_eq(y_preds[n], y[n]);
  }
  accuracy = correct / N;
}