mardi 29 décembre 2020

Getting outputs from a "for" loop in r into a matrix or data frame

I am trying to perform the following loop:

  1. Compare each of the n rows of my matrix X with a X.prototype matrix.

  2. Find the closest row of X.prototype to each row of X.

  3. if the two rows have the same label (y and y.prototype), then bring the values close; otherwise, put them further.

My code:

for (i in (1:n)){ 
  
  closest.row <- which.min(colSums((t(X.prototype) - X[i,])^2))
  
  X.new.x1 <- ifelse(y.prototype[closest.row] == y[i],
                     X.prototype[closest.row,1]+(eta*(X[i,1]-X.prototype[closest.row,1])),
                     X.prototype[closest.row,1]-(eta*(X[i,1]-X.prototype[closest.row,1])))
  X.new.x2<- ifelse(y.prototype[closest.row] == y[i],
                    X.prototype[closest.row,2]+(eta*(X[i,2]-X.prototype[closest.row,2])),
                    X.prototype[closest.row,2]-(eta*(X[i,2]-X.prototype[closest.row,2])))
  X.new <- matrix(c(X.new.x1,X.new.x2),ncol=2) 

  plot(X.new.x2~X.new.x1)

 print(X.new)
  
}


----------


set.seed(123)                        # Set seed for reproducibility
n <- 100
X <- cbind(x1 = runif(n, -1.5, 1.5),
           x2 = runif(n, -1.5, 1.5)) # Generate random points
y <- as.integer(rowSums(X^2)<1)      # Determine whether inside the circle#
idx <- sample(100, 10)               # Mess up 10 class labels ...
y[idx] <- 1-y[idx]                   # ... by flipping the label

is <- c(sample(which(y==0),K), sample(which(y==1),K))
X.prototype <- X[is,]
y.prototype <- y[is]                 # Will be K times 0, followed by K times 1

K <- 10
eta <- 0.25
H <- 25

The problem is that the outcomes come out as single vectors, and I am unable to bring them together in a X.new matrix, to use for new predictions and to plot it.

this is a link to how my output looks

This is how I'd like them to look

Thank you S

Aucun commentaire:

Enregistrer un commentaire