0

The following code produces different outcomes when Run -> Run All is executed and when Knit is executed. Any comments are appreciated, thank you.

---
title: "Ch8-Bayessian Additive Regression Trees-lab"
jupyter:
  jupytext:
    formats: ipynb,Rmd
    text_representation:
      extension: .Rmd
      format_name: rmarkdown
      format_version: '1.2'
      jupytext_version: 1.11.2
  kernelspec:
    display_name: R
    language: R
    name: ir
editor_options: 
  chunk_output_type: console
---

# Lab: Regression Trees
## BART

The `tree` library is used to construct classification and regression trees.

```{r chunk1}
library(tree)
```



## Bayesian Additive Regression Trees



```{r chunk2}
library(ISLR2)
set.seed(1)
train <- sample(1:nrow(Boston), nrow(Boston) / 2)
```

```{r chunk3}
library(BART)
x <- Boston[, 1:12]
y <- Boston[, "medv"]
xtrain <- x[train, ]
ytrain <- y[train]
xtest <- x[-train, ]
ytest <- y[-train]
set.seed(1)
bartfit <- gbart(xtrain, ytrain, x.test = xtest)
```

Next we compute the test error.

```{r chunk4}
yhat.bart <- bartfit$yhat.test.mean
mean((ytest - yhat.bart)^2)
```


```{r chunk5}
ord <- order(bartfit$varcount.mean, decreasing = T)
bartfit$varcount.mean[ord]
```

Results
Run -> Run All gives
> mean((ytest - yhat.bart)^2)
[1] 21.73309

Knit gives
## [1] 15.94718

Tried "Clear Knit Cache", Knit on Save, always ## [1] 15.94718, run code in RStudio command by command. Always consistent [1] 21.73309

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • When you `Run All`, the code is executed in your current environment, taking into account anything you might have run previously, re-run, or just entered in the console. When you Knit, only the code in your Rmd document is executed in its own environment. If you restart R and Run All, that should be the same as when you Knit. – Gregor Thomas Jun 14 '23 at 16:59
  • Thank you, this solution worked. – Leszek Gawarecki Jun 14 '23 at 18:05

0 Answers0