Skip to content

Instantly share code, notes, and snippets.

@eliocamp
Last active May 6, 2021 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliocamp/6b04af04a749470150b6418f4fa75dcc to your computer and use it in GitHub Desktop.
Save eliocamp/6b04af04a749470150b6418f4fa75dcc to your computer and use it in GitHub Desktop.
MDS
library(magrittr)
library(ggplot2)
library(rgl)
library(plotly)
set.seed(42)
# Cantidad de puntos por grupos
N <- 20
# Localización de los grupos
mus <- list(negro = c(-15, 5, 0),
rojo = c(-5, -15, 0),
cian = c(0, 0, 5),
rosa = c(0, 0, -5),
verde = c(5, 15, 0),
azul = c(15, -5, 0))
# Gera los grupos.
datos <- lapply(seq_along(mus), function(i) {
d <- as.data.frame(matrix(rnorm(N*3), ncol = 3) + matrix(rep(mus[[i]], N), ncol = 3, byrow = TRUE))
d$col <- names(mus)[i]
d
}) %>%
do.call(rbind, .)
# Hagamos MDS
n <- nrow(datos)
# Matriz de distancias cuadradas
D <- as.matrix(dist(as.matrix(datos[, -4])))^2
# Matriz de centrado
C <- diag(1, nrow = n) - 1/n*matrix(1, nrow = n, ncol = n)
B <- -1/2*(C %*% D %*% C)
# Calcular los autovaltores
e <- eigen(B)
# Reconstrucción de las variables en 2 dimensiones
m <- 2
mds <- as.data.frame(e$vectors[, 1:2] %*% diag(sqrt(e$values[1:2]), nrow = 2))
mds$col <- datos$col
# Plotear las variables originales en 3D
plot_ly(datos, x = ~V1, y = ~V2, z = ~V3, color = ~col) %>%
add_markers(size = 1)
# Plotear las nuevas variables en 2D
mds %>%
ggplot(aes(V1, V2)) +
geom_point(aes(color = col))
@eliocamp
Copy link
Author

eliocamp commented May 6, 2021

Datos originales en 3D
image

Datos proyectados en 2D
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment