Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Conformable Arrays when Doing Matrix Multiplication in R

Tags:

r

matrix

I am trying to implement Kernel Ridge Regression in R.

The formula is:

alpha <- ((lambda.I + K)^(-1)) * y

Lambda = 0.1. I = identity matrix the same size as K. y is a feature vector that has the same number of rows as K.

So I tried this in R:

I <- diag(nrow(df_matrix)
lambda <- 0.1
alpha <- (lambda * I + df_matrix) ^ (-1) * df_vector

I get the following error

Error in (0.1 * I + df_matrix)^(-1) * df_vector : non-conformable arrays

Here's some information on my dataset

> nrow(df_matrix)
[1] 8222
> ncol(df_matrix)
[1] 8222
> nrow(df_vector)
[1] 8222
> nrow(I)
[1] 8222
> ncol(I)
[1] 8222
> class(df_matrix)
[1] "matrix"
> class(df_vector)
[1] "matrix"
like image 455
DoeNoe Avatar asked Jan 06 '23 02:01

DoeNoe


1 Answers

I bet you want to have here matrix inversion, which is solve(m), instead of element-wise (m^(-1)). Also, matrix multiplication (%*%) instead of element-wise (*). So, altogether is

alpha <- solve(lambda * I + df_matrix) %*% df_vector
like image 196
Iaroslav Domin Avatar answered Jan 24 '23 06:01

Iaroslav Domin