1
votes

Good afternoon !

I'm trying to implement EM algorithm from scratch. I developed a code that contains :

k=10
w_k=rep(1,k)/k
n_j=rep(0,k)

print(w_k)

data=iris[1:150,-5]
means=sample(1:dim(data)[1],k,replace=FALSE)
means
mu=iris[means,-5]
sigma=cov(data)
print("mu")
mu
print("sigma")
sigma
print("inv")
solve(sigma)
print("mu[1,] ")
as.vector(mu[1,])
as.vector(mu[1,]) %*%  solve(sigma) #line of error 

Unfortunately , this line gives the follwing error :

Error in as.vector(mu[1, ]) %*% solve(sigma) : 
  requires numeric/complex matrix/vector arguments
Execution halted

I tried to fix the problem many times by using as.matrix() but without success. Thank you in advance for help !

2

2 Answers

1
votes

The vector mu is a data.frame. Try converting that to a matrix.

as.matrix(mu[1,]) %*%  solve(sigma)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
#95     16.37781    11.46013    -0.198358   -9.473886
1
votes

mu is a data frame and should be transformed to a matrix.

k=10
w_k=rep(1,k)/k
n_j=rep(0,k)

print(w_k)

data=iris[1:150,-5]
means=sample(1:dim(data)[1],k,replace=FALSE)
means
mu=as.matrix(iris[means,-5])
sigma=cov(data)
print("mu")
mu
print("sigma")
sigma
print("inv")
solve(sigma)
print("mu[1,] ")

is.numeric(mu[1,])
is.matrix(mu[1,])
rbind(mu[1,]) %*%  solve(sigma) %*% cbind(mu[1,])