简体   繁体   中英

Matrix Error: Requires numeric in R

Phi <- as.matrix(cbind(1, train.data)) # add a column of 1 as phi_0
train.len <- 75
eta <- 0.01 # Learning rate
epsilon <- 0.001 # 
tau.max <- 75 # Maximum number of iterations

T <- ifelse(train.label == c0, eval(parse(text=c0)),eval(parse(text=c1))) labels

W <- matrix(,nrow=tau.max, ncol=ncol(Phi)) # Empty Weight vector
W[1,] <- runif(ncol(Phi)) # Random initial values for weight vector

error.trace <- matrix(0,nrow=tau.max, ncol=1) # Placeholder for errors
error.trace[1] <- sum((Phi%*%W[1,])*T<0)/train.len*100 

train.data looks like:

x1    x2    x3    x4    y
5.1   3.5   1.4   0.2   C1
4.7   3.2   1.3   0.2   C1
35.0  3.6   1.4   0.2   C1

The problem happens in the last line. I checked some other posts ( Matrix expression causes error "requires numeric/complex matrix/vector arguments"? ) . they say to ensure that the data is in matrix format and I also checked they are both numeric ( Phi and W ).

The error I get is

Error in Phi %*% W[1, ] : requires numeric/complex matrix/vector arguments

I get no error when I generate some toy data: train.data <- rnorm(75) . What is your train.data ? A data frame? If so, what is sapply(train.data, class) ? I suspect you have factors / characters. In that case, your matrix Phi will be a character matrix, instead of a numerical one.

Maybe you should try using:

Phi <- cbind(1, data.matrix(train.data))

Read ?data.matrix for more. Another way is to use:

Phi <- cbind(1, sapply(train.data, as.numeric))

Update

Indeed you have a column y , which is either a factor or character column. My solution above will work. But, I don't know your context, so you should ask yourself whether it makes sense to include y column for computation. If you don't want it, drop it and use:

Phi <- cbind(1, as.matrix(train.data[,1:4]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM