Exemplo n.º 1
0
        public DoubleSVDecomp SVDecomp()
        {
            if (MatrixSVDecomp == null)
            {
                var decompServer = new DoubleSVDecompServer
                {
                    ComputeLeftVectors  = true,
                    ComputeRightVectors = true,
                    ComputeFull         = true
                };
                MatrixSVDecomp = decompServer.GetDecomp(Matrix);
            }

            return(MatrixSVDecomp);
        }
        /// <summary>
        /// 奇异值分解 singular value decomposition
        /// </summary>
        public static void DoSvd()
        {
            Utility.Status("Creating SVD");

            // 源文件数, 源文件中所有独特词数目, 源文件-索引, 源文件单词-索引
            int totalNumberOfSourceFiles                     = TfDictionary.Count;
            int totalDistinctTermsInAllSourceFiles           = IdfDictionary.Count;
            Dictionary <string, int> allSourceFilesWithIndex = TfDictionary.Keys.Select((x, index) => new { Name = x, Index = index }).ToDictionary(x => x.Name, x => x.Index);
            Dictionary <string, int> allSourceWordsWithIndex = IdfDictionary.Keys.Select((x, index) => new { Name = x, Index = index }).ToDictionary(x => x.Name, x => x.Index);

            // 源码矩阵 行数: 源码中单词数, 源文件数
            double[,] sourceMatrix = new double[totalDistinctTermsInAllSourceFiles, totalNumberOfSourceFiles];

            foreach (var fileNameWithTfDictionary in TfDictionary)
            {
                // 文件索引
                int fileIndex = allSourceFilesWithIndex[fileNameWithTfDictionary.Key];
                foreach (var fileWordWithTf in fileNameWithTfDictionary.Value)
                {
                    sourceMatrix[allSourceWordsWithIndex[fileWordWithTf.Key], fileIndex] = fileWordWithTf.Value;
                }
            }

            // 创建矩阵
            DoubleMatrix generalMatrix = new DoubleMatrix(sourceMatrix);

            // 奇异值分解 A = U S V.T
            var svd = new DoubleSVDecomp(generalMatrix);

            _uk          = new Dictionary <int, DoubleMatrix>();
            _sk          = new Dictionary <int, DoubleMatrix>();
            _vkTranspose = new Dictionary <int, DoubleMatrix>();

            Utility.LsiKs.Where(x => x <= svd.Cols).ToList().ForEach(k =>
            {
                // 创建k维矩阵
                Utility.Status("Creating k matrix of size " + k);

                DoubleMatrix U = svd.LeftVectors;
                DoubleMatrix V = svd.RightVectors;

                // 通过数组创建矩阵, 行优先存储, 可再改
                _uk.Add(k, Utility.GetDimMatrix(U, U.Rows, k));
                _sk.Add(k, Utility.GetDiagonal(svd.SingularValues, k));
                _vkTranspose.Add(k, NMathFunctions.Transpose(Utility.GetDimMatrix(V, V.Rows, k)));
            });
        }
Exemplo n.º 3
0
 public DenseMatrix(string path)
 {
     (Matrix, Size) = ReadMatrix(path);
     MatrixSVDecomp = null;
 }