# Compare reconstruction error for different K values
networks_small <- makeNetworksFast(qc_data, nNet = 5, nCells = 100,
nComp = 3, verbose = FALSE, seed = 1)
k_values <- c(2, 3, 5, 7, 10)
errors <- numeric(length(k_values))
for (i in seq_along(k_values)) {
td <- tensorDecomposition(networks_small, K = k_values[i],
maxIter = 100, useCpp = TRUE)
# Compute reconstruction error
reconstructed <- as.matrix(td$X)
original_mean <- Reduce(`+`, lapply(networks_small, as.matrix)) / length(networks_small)
errors[i] <- sqrt(mean((reconstructed - original_mean)^2))
}
plot(k_values, errors, type = "b", pch = 19, col = "#E74C3C", lwd = 2,
xlab = "Tensor Rank (K)", ylab = "Reconstruction RMSE",
main = "Tensor Rank Selection")
grid()
# Mark elbow point
optimal_k <- k_values[which.min(diff(diff(errors)) > 0)]
abline(v = optimal_k, lty = 2, col = "#3498DB")
legend("topright", paste("Suggested K =", optimal_k), bty = "n")