rmatrix-multiplicationdimensionality-reductionnmf

Unable to find dot product of two matrix (W and H from NMF ) with same inner dimensions


I am doing Non-Negative Matrix Factorization (NMF) of a matrix A in R. It has Genes on rows and Samples on the columns. For NMF, I am using the CRAN package NMF. Once the basis matrix W and coefficient matrix H are computed, I want to check whether the factorisation was accurate enough. For that, I am trying to calculate the dot product of W and H so as to check whether I can get the original matrix A back.

Although the inner dimensions of basis matrix W and coefficient matrix H are same (rank = 3), I cannot multiply them. I keep getting the following error. This one line error is not very helpful.

Error in x * y : non-conformable arrays

Reproducible code

# Make a 10 * 10 matrix
ranVal= sample(1:10,100,replace =T)
M=matrix(ranVal,nrow=10)

# Rename the rows and columns
rownames(M) <-  paste(rep("gene", 10),c(1:10), sep = "_")
colnames(M) <-  paste(rep("sample", 10),c(1:10), sep = "_")

# See how it looks
M

# NMF
library(NMF)
tempRes <- nmf(x = M, rank = 3, .options = c("pv"))

# NMF implementation from Brunet et al. (2004)
result <- nmf_update.brunet_R(i = 1, v = M, x = tempRes, eps=.Machine$double.eps)

# Basis Matrix
W <- .basis(result); 

# Coeff Matrix
H <- .coef(result)

# Checking dimensions
dim(W)
dim(H)

# Dot product
A <- W*H # Error: non-conformable arrays
A <- geometry::dot(W,H) # Error: non-conformable arrays

How should I go about it? Is there a different way to check it? Thanks!


Solution

  • What about W %*% H?

    W %*% H
            sample_1 sample_2   sample_3 sample_4  sample_5 sample_6
    gene_1  4.406480 6.392739  9.5742884 5.164528  5.074363 3.549958
    gene_2  7.165909 4.960877  2.3608356 5.718255  8.405870 5.817709
    gene_3  5.070350 3.804750  3.2464367 3.906296  6.383760 4.810851
    gene_4  8.356959 4.181312  0.9964025 5.167783 10.955091 8.533261
    gene_5  4.671284 5.157582 11.0938515 3.059027  7.946619 7.730591
    gene_6  5.899437 6.666820  6.0368747 6.705011  5.718862 2.998982
    gene_7  7.801179 7.052729  1.3482074 8.775604  6.398204 2.076385
    gene_8  3.501642 4.410587  9.1595473 2.720517  5.693630 5.401830
    gene_9  5.271008 7.975740  9.1787413 7.358409  4.472696 1.753683
    gene_10 5.855654 4.396895  1.0050132 5.424544  5.950780 3.326661
            sample_7 sample_8  sample_9 sample_10
    gene_1  6.781347 5.909006  8.431049  4.716241
    gene_2  4.884002 6.815600  4.339132  4.531809
    gene_3  4.015448 5.548575  3.376917  2.836615
    gene_4  4.446931 8.554956  1.793168  3.014138
    gene_5  6.644475 8.692351  5.003496  1.000724
    gene_6  6.364861 5.479570  8.536569  6.593015
    gene_7  5.804209 4.769660  8.798081  9.175741
    gene_8  5.469769 6.475237  4.801630  1.365611
    gene_9  7.673524 5.183927 11.371303  7.760969
    gene_10 3.915477 4.571069  4.548770  5.005138