Ich führen Beispielcode, um ein Diagramm zu erstellen, um Markov Chain Monte Carlo zu beschreiben. https://github.com/davharris/mcmc-tutorial Allerdings ich die folgende Ausnahme von der letzten Zeile des Codes ausgelöst. "Fehler: Ästhetik muss entweder die Länge 1 oder die gleiche wie die Daten (250000) sein: x, y"r ggplot Fehler: Ästhetik muss entweder die Länge 1 oder die gleiche wie die Daten (250000):
Der Code wurde im Folgenden aufgelistet.
library(MASS)
library(ggplot2)
lik = function(x, y) {
dnorm(x - 3) * dnorm(y - x + 2)
}
grid.values = seq(min.x, max.x, length = 500)
grid = expand.grid(x = grid.values, y = grid.values)
z = lik(grid$x, grid$y)
gaussian.plot = ggplot(data = grid, aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_fill_gradient2() + coord_equal()
gaussian.plot
maxit = 50
samples = matrix(NA, nrow = maxit, ncol = 2, dimnames = list(NULL, c("x", "y")))
samples[1, ] = c(0, 0) # start at 0,0
for (i in 2:maxit) {
# propose a new sample point
proposal = samples[i - 1, ] + rnorm(2, mean = 0, sd = 1)
# Compare its likelihood with the current position
old.lik = lik(samples[i - 1, "x"], samples[i - 1, "y"])
new.lik = lik(proposal["x"], proposal["y"])
ratio = new.lik/old.lik
# flip a coin and accept the new proposal with probability min(ratio, 1)
if (rbinom(1, size = 1, prob = min(ratio, 1))) {
samples[i, ] = proposal
} else {
# If you don't accept the proposal, just keep what you had in the last
# time step
samples[i, ] = samples[i - 1, ]
}
}
gaussian.plot + geom_path(mapping = aes(x = samples[, "x"], y = samples[, "y"]),
color = "orange") + geom_point(mapping = aes(x = samples[, "x"], y = samples[,
"y"]))
Es ist schwierig zu reproduzieren, wenn die Daten nicht enthalten sind. Quote: 'Fehler in seq (min.x, max.x, length = 500): Objekt 'min.x' nicht gefunden ' – nilsole