当前位置: 首页>>代码示例>>C#>>正文


C# Matrix.SetColumnVector方法代码示例

本文整理汇总了C#中Matrix.SetColumnVector方法的典型用法代码示例。如果您正苦于以下问题:C# Matrix.SetColumnVector方法的具体用法?C# Matrix.SetColumnVector怎么用?C# Matrix.SetColumnVector使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Matrix的用法示例。


在下文中一共展示了Matrix.SetColumnVector方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Regression

 public Regression(double[] xdata, double[] ydata, int degree)
 {
     int numberOfSamples = xdata.Length;
     //Define the results
     coefficients = new double[degree + 1];
     predicted = new double[numberOfSamples];
     //Set up X and Y Matricies
     Matrix YMatrix = new Matrix(ydata, numberOfSamples);
     Matrix XMatrix = new Matrix(numberOfSamples, degree + 1);
     XMatrix.SetColumnVector(new Vector(numberOfSamples, 1.0), 0);
     for (int i = 0; i < degree; i++)
     {
         XMatrix.SetColumnVector(new Vector(RaisePower(xdata, i + 1)), i + 1);
     }
     //Do the calcs
     Matrix XTranspose = Matrix.Transpose(XMatrix);
     Matrix Temp = (XTranspose * XMatrix).Inverse();
     Matrix hat = XMatrix.Multiply(Temp).Multiply(XTranspose);
     Matrix result = Temp.Multiply(XTranspose * YMatrix);
     //Get the coefficients
     coefficients = result.GetColumnVector(0);
     //Calculate the predicted values
     Matrix Y = new Matrix(ydata, ydata.Count());
     predicted = hat.Multiply(Y).GetColumnVector(0);
 }
开发者ID:sridhar19091986,项目名称:htmlconvertsql,代码行数:25,代码来源:CsharpCurveFit.cs

示例2: ToMatrixByColumns

 public static Matrix ToMatrixByColumns(this Vector input, int columnSize)
 {
     int matrixSize = (int)Math.Sqrt(input.Length);
     Matrix columnsMatrix = new Matrix(m: matrixSize, n: matrixSize);
     for (int i = 0; i < matrixSize; ++i)
     {
         double[] column = input.Skip(i * matrixSize).Take(matrixSize).ToArray();
         columnsMatrix.SetColumnVector(new Vector(column), i);
     }
     return columnsMatrix;
 }
开发者ID:smilingjb12,项目名称:Perceptron,代码行数:11,代码来源:VectorExtensions.cs

示例3: start

        public void start(Analysis parent, HttpResponse response, System.Web.SessionState.HttpSessionState session)
        {
            ParameterStream stream = ParameterStream.getStream(session);
            String[] features = (String[]) stream.get("selectedFeatures");
            int PCs = (int) stream.get("numberOfPCs");
            Registry.Registry registry = Registry.Registry.getRegistry(session);
            System.Data.DataSet ds = (System.Data.DataSet) registry.GetDataset((string) stream.get("dataSetName"));

            //retrieve dataset table (assume one for now)
            System.Data.DataTable dt = ds.Tables[0];
            
            
            //raw data
            double[,] rawData = new double[dt.Rows.Count, features.Count()];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < features.Count(); j++)
                    rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
            }

            //Create matrix to hold data for PCA
            Matrix X = new Matrix(rawData);

            //Remove mean
            Vector columnVector;
            for (int i = 0; i < X.ColumnCount; i++)
            {
                columnVector = X.GetColumnVector(i);
                X.SetColumnVector(columnVector.Subtract(columnVector.Average()),i);
            }

            Matrix PCmatrix = new Matrix(X.ColumnCount, PCs, 0);
            Vector Weights = new Vector(PCs);

            System.Diagnostics.Stopwatch watch = new Stopwatch();

            //Run algorithm and time it
            watch.Start();
            NIPALS(X, PCs, PCmatrix, Weights);
            watch.Stop();
            stream.set("algRunTime", watch.ElapsedMilliseconds);
            
            /*
            response.Buffer = true;
            response.Write(PCmatrix.ToString() + "\n");
            response.Write(Weights.ToString() + "\n");
            response.Flush();
            */
            Debug.WriteLine("Done with PCA");
            stream.set("PCmatrix", PCmatrix);
            stream.set("Weights", Weights);
            parent.next(response, session);
        }
开发者ID:ridhi29,项目名称:dataminingproject,代码行数:53,代码来源:NIPALS_PCA.cs

示例4: NIPALS


//.........这里部分代码省略.........
            //E is the residual error after i itereations
            int i;
            //PCmatrix = new Matrix(PCs, X.ColumnCount, 0);
            //EigenValues = new Vector(PCs);
            Matrix E = X.Clone();
            Vector u = new Vector(E.RowCount);
            Vector v = new Vector(E.ColumnCount);
            Matrix E_transposed;
            int initialVector = 0;
            //convergence threshold
            const double threshold = 0.0000001;

            //from http://www.vias.org/tmdatanaleng/dd_nipals_algo.html
            for (i = 0; i < PCs; i++)
            {
                //printMatrix(E, "E");
                //1.    u := x(i) 	Select a column vector xi of the matrix X and copy it to the vector u
                //The vector must be such that the self-inner product is not zero 

                double ut_u = 0;
                Boolean valid = false;
                while (!valid && initialVector < E.ColumnCount)
                {
                    u = E.GetColumnVector(initialVector);
                    initialVector++;
                    if (u.ScalarMultiply(u) != 0)
                        valid = true;
                }
                if (!valid)
                    throw new Exception("Could not find " + PCs + " principal components");

                E_transposed = E.Clone();
                E_transposed.Transpose();
                //printMatrix(E_transposed, "E transposed");

                //int step = 1;
                double error = 1;
                while (error > threshold)
                {
                    //  Console.Out.WriteLine("PC " + (i+1) + " Step : " + step++);

                    //2. 	v := (X'u)/(u'u) 	Project the matrix X onto u in order to find the corresponding loading vs
                    //Console.Out.WriteLine("u: " + u.ToColumnMatrix().ToString());
                    ut_u = u.ScalarMultiply(u);
                    if (ut_u == 0)
                        throw new Exception("Principal component results in complex answer");

                    //Console.Out.WriteLine("u'u: " + ut_u);

                    Matrix v_prime = E_transposed.Multiply(u.ToColumnMatrix());
                    //printMatrix(v_prime, "v prime");
                    v = v_prime.GetColumnVector(0) / ut_u;
                    //Console.Out.WriteLine("v: " + v.ToString());

                    //3.    v := v/|v| 	Normalize the loading vector v to length 1
                    v = v.Normalize();
                    //v = v / v.Norm();
                    //Console.Out.WriteLine("v after normalization: " + v.ToString());


                    //4.1 	u_old := u  Store the score vector u into uold 
                    Vector u_old = u.Clone();
                    //Console.Out.WriteLine("u old: " + u_old.ToString());

                    //4.2      u := (Xp)/(v'v) 	and project the matrix X onto v in order to find corresponding score vector u
                    Matrix u_prime = E.Multiply(v.ToColumnMatrix());
                    //Console.Out.WriteLine("u_prime: ");
                    //printMatrix(u_prime);

                    Vector u_primeColumn = u_prime.GetColumnVector(0);
                    //Console.Out.WriteLine("u_primeColumn: " + u_primeColumn.ToString());

                    double v_v = v.ScalarMultiply(v);

                    //Console.Out.WriteLine("v_v: " + v_v);

                    u = u_primeColumn / v_v;
                    //Console.Out.WriteLine("new u: " + u.ToString());

                    //5. 	d := uold-u 	In order to check for the convergence of the process 
                    //calculate the difference vector d as the difference between the previous scores
                    //and the current scores. If the difference |d| is larger than a pre-defined threshold,
                    //then return to step 2.
                    Vector d = u_old.Subtract(u);
                    //Console.Out.WriteLine("d: " + d.ToString());
                    error = d.Norm();
                    //Console.Out.WriteLine("Error: " + error.ToString());

                }
                //6. 	E := X - tp' 	Remove the estimated PCA component (the product of the scores and the loadings) from X
                Matrix tp = u.ToColumnMatrix().Multiply(v.ToRowMatrix());
                //printMatrix(tp, "tp'");
                E.Subtract(tp);

                PCmatrix.SetColumnVector(v, i);
                EigenValues[i] = u.Norm();
                //7. 	X := E 	In order to estimate the other PCA components repeat this procedure from step 1 using the matrix E as the new X

            }
        }
开发者ID:ridhi29,项目名称:dataminingproject,代码行数:101,代码来源:NIPALS_PCA.cs

示例5: irisPCA

        public static void irisPCA()
        {
            //setup to read from CSV
            String CSVfilePath = "C:\\dataminingproject";
            String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + CSVfilePath + ";Extended Properties='text;HDR=Yes;FMT=Delimited'";
            //Setup connection  
            OleDbConnection connection = new OleDbConnection(connectionString);
            //read everything
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + "iris.csv", connection);
            //table to hold the data
            System.Data.DataTable dt = new System.Data.DataTable();
            //adapter to read the data
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            connection.Open();
            da.Fill(dt);

            //data should be in the table now
            // create a matrix to hold the data, ignore species
            //        Matrix iris = new Matrix (dt.Rows.Count, dt.Columns.Count -1);
            //select columns
            dt.Columns.Remove(dt.Columns[4]);
            double[,] dataArray = new double[dt.Rows.Count,dt.Columns.Count];
           // double sample = Array.ConvertAll<System.Data.DataRow, double[]>(dt.Select(),;
            
            for(int i = 0; i<dt.Rows.Count;i++){
                Console.Out.Write ("[ ");
                for(int j = 0; j<dt.Columns.Count;j++){
                    dataArray[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(j);
                    Console.Out.Write (dt.Rows[i].ItemArray.ElementAt(j).ToString() + ", ");
                }
                Console.Out.WriteLine (" ]");
            }
            //dt.Rows.CopyTo(dataArray, 0);
            //double[] dataArray = Array.ConvertAll(
            Matrix iris = new Matrix(dataArray);
            printMatrix(iris, "iris");

            //remove mean
            for (int i = 0; i < iris.ColumnCount; i++)
                iris.SetColumnVector(iris.GetColumnVector(i).Subtract(iris.GetColumnVector(i).Average()), i);

            int PCs = 2;
            Matrix PCmatrix = new Matrix(iris.ColumnCount, PCs, 0);
            Vector EigenValues = new Vector(PCs);
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            try
            {
                timer.Start();
                NIPALS(iris, PCs, PCmatrix, EigenValues);
                timer.Stop();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.ToString());
                Console.In.ReadLine();
                return;
            }
            Console.Out.WriteLine("NIPALS Time: " + timer.ElapsedMilliseconds);

            printMatrix(PCmatrix, "Principal Components");
            printMatrix(EigenValues.ToRowMatrix(), "Weights");

            
            Console.Out.WriteLine("SVD:");
            timer.Reset();
            timer.Start();
            SingularValueDecomposition svd = iris.SingularValueDecomposition;
            timer.Stop();
            Console.Out.WriteLine("SVD Time: " + timer.ElapsedMilliseconds);

            //Console.Out.WriteLine("LSV: ");
            //printMatrix(svd.LeftSingularVectors);
            Console.Out.WriteLine("RSV: ");
            printMatrix(svd.RightSingularVectors);
            Console.Out.WriteLine("S: ");
            printMatrix(svd.S);
            Console.Out.WriteLine("Singular Values: ");
            printMatrix(svd.SingularValues.ToRowMatrix());
            Console.In.ReadLine();
            


//            Console.Out.WriteLine(dt.Rows[0].ItemArray.Take(4).ToArray<double>());
            /*
            for (int i=0;i<iris.ColumnCount;i++){
                iris.SetColumnVector(dt.Columns[i].Container.Components.GetEnumerator.
            } 
             */
        }
开发者ID:ranjanroy21,项目名称:dataminingproject,代码行数:90,代码来源:Program.cs

示例6: Main

        //private static MathNet.Numerics.Algorithms.LinearAlgebra.Atlas.AtlasLinearAlgebraProvider provider;
        static void Main(string[] args)
        {
            Console.Out.WriteLine ("Hello...");

            irisPCA();
            //provider = new MathNet.Numerics.Algorithms.LinearAlgebra.Atlas.AtlasLinearAlgebraProvider();

            /*
            double[,] A = new double[2,2];
            A[0, 0] = 5;
            A[0, 1] = 0;
            A[1, 0] = 0;
            A[1, 1] = 10;
            
            /*
            double[,] A = new double[3, 2];
            A[0, 0] = 5;
            A[0, 1] = 0;
            A[1, 0] = 0;
            A[1, 1] = 10;
            A[2, 0] = 5;
            A[2, 1] = 15;
            */

            double[,] A = new double[4, 3];
            A[0, 0] = 1;
            A[0, 1] = 2;
            A[0, 2] = 3;
            A[1, 0] = 4;
            A[1, 1] = 5;
            A[1, 2] = 6;
            A[2, 0] = 6;
            A[2, 1] = 5;
            A[2, 2] = 4;
            A[3, 0] = 3;
            A[3, 1] = 2;
            A[3, 2] = 1;
            Matrix X = new Matrix(A);

            //remove mean
            for (int i=0;i<X.ColumnCount;i++)
                X.SetColumnVector(X.GetColumnVector(i).Subtract(X.GetColumnVector(i).Average()),i);


            printMatrix(X, "X");
            int PCs = 2;
            Matrix PCmatrix = new Matrix(X.ColumnCount, PCs, 0);
            Vector EigenValues = new Vector(PCs);

            try
            {
                NIPALS(X, PCs, PCmatrix, EigenValues);
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.ToString());
                Console.In.ReadLine();
                return;
            }
            
            printMatrix(PCmatrix, "Principal Components");
            double projection = PCmatrix.GetColumnVector(0).ScalarMultiply(PCmatrix.GetColumnVector(1));
            Console.Out.WriteLine("projection:  " + projection);
            printMatrix(EigenValues.ToRowMatrix(), "Weights");
            
            Console.Out.WriteLine("SVD:");
            SingularValueDecomposition svd = X.SingularValueDecomposition;
            Console.Out.WriteLine("LSV: ");
            printMatrix(svd.LeftSingularVectors);
            Console.Out.WriteLine("RSV: ");
            printMatrix(svd.RightSingularVectors);
            Console.Out.WriteLine("S: ");
            printMatrix(svd.S);
            Console.Out.WriteLine("Singular Values: ");
            printMatrix(svd.SingularValues.ToRowMatrix());
            Console.In.ReadLine();
        }
开发者ID:ranjanroy21,项目名称:dataminingproject,代码行数:78,代码来源:Program.cs

示例7: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            Matrix PCmatrix = (Matrix)stream.get("PCmatrix");
            String[] features = (String[])stream.get("selectedFeatures");

            System.Data.DataSet ds = (System.Data.DataSet)registry.GetDataset((string)stream.get("dataSetName"));

            //retrieve dataset table (assume one for now)
            System.Data.DataTable dt = ds.Tables[0];

            //raw data
            double[,] rawData = new double[dt.Rows.Count, features.Count()];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < features.Count(); j++)
                    rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
            }

            //Create matrix to hold data for PCA
            Matrix X = new Matrix(rawData);

            //Remove mean
            Vector columnVector;
            for (int i = 0; i < X.ColumnCount; i++)
            {
                columnVector = X.GetColumnVector(i);
                X.SetColumnVector(columnVector.Subtract(columnVector.Average()), i);
            }

            //get first two PCs
            Matrix xy = new Matrix(PCmatrix.RowCount,2);
            xy.SetColumnVector(PCmatrix.GetColumnVector(0),0);
            xy.SetColumnVector(PCmatrix.GetColumnVector(1),1);

            
            //project
            Matrix projected = X.Multiply(xy);

            DataPoint point;
            Projection.Series.Clear();
            Projection.Legends.Clear();


            //if a label column is selected
            String LabelColumnName = LabelColumn.Text;

            if (!LabelColumnName.Equals(""))
            {

                //get labels
                int labelColumnIndex = dt.Columns[LabelColumnName].Ordinal;
                List<String> labels = new List<String>();
                String item;
                
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    item = (String)dt.Rows[i].ItemArray.ElementAt(labelColumnIndex);
                    if (!labels.Contains(item))
                        labels.Add(item);
                }
                Projection.Legends.Add(LabelColumnName);
                System.Drawing.Font font = Projection.Legends[LabelColumnName].Font = new System.Drawing.Font(Projection.Legends[LabelColumnName].Font.Name, 14);

                //Configure series
                foreach (String label in labels)
                {
                    Projection.Series.Add(label);
                    Projection.Series[label].LegendText = label;
                    Projection.Series[label].IsXValueIndexed = false;
                    Projection.Series[label].ChartType = SeriesChartType.Point;
                    Projection.Series[label].MarkerSize = 8;
                }

                //Add points
                for (int i = 0; i < projected.RowCount; i++)
                {
                    point = new DataPoint(projected[i, 0], projected[i, 1]);
                    String label = dt.Rows[i].ItemArray[labelColumnIndex].ToString();
                    Projection.Series[label].Points.Add(point);
                }

            }
            else
            {
                //Single plot graph
                Projection.Series.Add("series1");
                Projection.Series[0].IsXValueIndexed = false;
                Projection.Series[0].ChartType = SeriesChartType.Point;
                Projection.Series[0].MarkerSize = 8;

                for (int i = 0; i < projected.RowCount; i++)
                {
                    point = new DataPoint(projected[i, 0], projected[i, 1]);
                    Projection.Series[0].Points.Add(point);
                }
            }
        }
开发者ID:ranjanroy21,项目名称:dataminingproject,代码行数:97,代码来源:PCA_2D_Projection.aspx.cs

示例8: addcontrol


//.........这里部分代码省略.........
                        Projection.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                        Projection.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                        DataMiningApp.Analysis.ParameterStream stream;
                        Registry.Registry registry;

                        stream = DataMiningApp.Analysis.ParameterStream.getStream(Session);
                        registry = Registry.Registry.getRegistry(Session);

                        Matrix PCmatrix = (Matrix)stream.get("PCmatrix");
                        String[] features = (String[])stream.get("selectedFeatures");

                        System.Data.DataSet ds = (System.Data.DataSet)registry.GetDataset((string)stream.get("dataSetName"));

                        //retrieve dataset table (assume one for now)
                        System.Data.DataTable dt = ds.Tables[0];

                        //raw data
                        double[,] rawData = new double[dt.Rows.Count, features.Count()];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            for (int j = 0; j < features.Count(); j++)
                                rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
                        }

                        //Create matrix to hold data for PCA
                        Matrix X = new Matrix(rawData);

                        //Remove mean
                        Vector columnVector;
                        for (int i = 0; i < X.ColumnCount; i++)
                        {
                            columnVector = X.GetColumnVector(i);
                            X.SetColumnVector(columnVector.Subtract(columnVector.Average()), i);
                        }

                        //get first two PCs
                        Matrix xy = new Matrix(PCmatrix.RowCount, 2);
                        xy.SetColumnVector(PCmatrix.GetColumnVector(0), 0);
                        xy.SetColumnVector(PCmatrix.GetColumnVector(1), 1);

                        //project
                        Matrix projected = X.Multiply(xy);

                        DataPoint point;
                        Projection.Series.Clear();
                        Projection.Legends.Clear();


                        //if a label column is selected
                        String LabelColumnName = "Species";

                        if (!LabelColumnName.Equals(""))
                        {

                            //get labels
                            int labelColumnIndex = dt.Columns[LabelColumnName].Ordinal;
                            List<String> labels = new List<String>();
                            String item;

                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                item = (String)dt.Rows[i].ItemArray.ElementAt(labelColumnIndex);
                                if (!labels.Contains(item))
                                    labels.Add(item);
                            }
开发者ID:ranjanroy21,项目名称:dataminingproject,代码行数:67,代码来源:Default.aspx.cs


注:本文中的Matrix.SetColumnVector方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。