R/parafac_fun.R

Defines functions parafac_fun

Documented in parafac_fun

#' PARAFAC loss function calculation
#'
#' @param x Vector of fitted loadings generated by the PARAFAC algorithm, can also be a Fac object
#' @param Tensor input data
#' @param lambdas If lambdas (from the kruskal tensor case) are generated to make the Fac norm 1, they can be supplied.
#'
#' @return Scalar value of the loss function
#' @export
#'
#' @examples
#' A = array(rnorm(108*2), c(108,2))
#' B = array(rnorm(100*2), c(100,2))
#' C = array(rnorm(10*2), c(10,2))
#' X = reinflateTensor(A, B, C)
#' model = parafac(X, 2)
#' f = parafac_fun(model$Fac, X)
parafac_fun = function(x, Tensor, lambdas=NULL){

  if(!methods::is(Tensor, "Tensor")){
    Tensor = rTensor::as.tensor(Tensor)
  }

  if(!methods::is(x, "list")){
    Fac = vect_to_fac(x, Tensor)
  } else{
    Fac = x
  }

  if(!is.null(lambdas)){
    Fac[[length(Fac)+1]] = as.matrix(lambdas)
  }

  W = rTensor::as.tensor(!is.na(Tensor@data))
  Xhat = reinflateFac(Fac, Tensor, returnAsTensor=TRUE)
  residuals = W * (Tensor - Xhat)

  f = 0.5 * rTensor::fnorm(residuals)
  return(f)
}

Try the parafac4microbiome package in your browser

Any scripts or data that you put into this service are public.

parafac4microbiome documentation built on June 8, 2025, 11:40 a.m.