Member 12417764 Ответов: 3

Что такое ошибка в коде foll


Когда мы запустим следующий код, он покажет ошибку
Данные имени не существуют

Что я уже пробовал:

namespace SearchResults
{
    public partial class cluster_analysis : Form
    {
        ServerPath sp;
        // Graph.Chart chart;

        public cluster_analysis()
        {
            InitializeComponent();
            sp = new ServerPath();
            this.ClientSize = new System.Drawing.Size(750, 750);
        }

       


             
        class test
        { 
            public static void Main()
            { 
             // k
            }
        }

     private void button1_Click(object sender, EventArgs e)
            {
         int i=0;
      
         OleDbConnection con = (new DABasis()).getConnect();
         OleDbCommand cmd = con.CreateCommand();
         con.Open();
         cmd.CommandText = ("select * from KnowledgeTB");
               OleDbDataReader Reader = cmd.ExecuteReader();
           int [][] rawData = new int[10][];
            //if (Reader.HasRows)
                //    Reader.Read();
                 while (Reader.Read())
                {

                     int db_data = Reader.GetInt32(3);
                               rawData[i] = new int[] { i, db_data };
                    i = i + 1;
                }  
                           
               
                cmd.Dispose();
                con.Close();
        
         kmean_richTextBox1.Text += "\nBegin k-means clustering demo\n";
                      kmean_richTextBox1.Text +="\nRaw unclustered data:\n";
             kmean_richTextBox1.Text +="\n    Height          Weight";
             kmean_richTextBox1.Text +="\n-------------------\n";
           ShowData(rawData, 1, true, true);

            int numClusters = 3;
             kmean_richTextBox1.Text +="\nSetting numClusters to " + numClusters;

            int[] clustering = Cluster(rawData, numClusters); // this is it

             kmean_richTextBox1.Text +="\nK-means clustering complete\n";

             kmean_richTextBox1.Text +="Final clustering in internal form:\n";
            ShowVector(clustering, true);

             kmean_richTextBox1.Text +="Raw data by cluster:\n";
            ShowClustered(rawData, clustering, numClusters, 1);

             kmean_richTextBox1.Text +="\nEnd k-means clustering demo\n";
            Console.ReadLine();

        } // Main

     // ============================================================================

     public static int[] Cluster(int[][] rawData, int numClusters)
     {
         // k-means clustering
         // index of return is tuple ID, cell is cluster ID
         // ex: [2 1 0 0 2 2] means tuple 0 is cluster 2, tuple 1 is cluster 1, tuple 2 is cluster 0, tuple 3 is cluster 0, etc.
         // an alternative clustering DS to save space is to use the .NET BitArray class
       //  int[][] data = Normalized(rawData); // so large values don't dominate

         bool changed = true; // was there a change in at least one cluster assignment?
         bool success = true; // were all means able to be computed? (no zero-count clusters)

         // init clustering[] to get things started
         // an alternative is to initialize means to randomly selected tuples
         // then the processing loop is
         // loop
         //    update clustering
         //    update means
         // end loop
         int[] clustering = InitClustering(data.Length, numClusters, 0); // semi-random initialization
         int[][] means = Allocate(numClusters, data[0].Length); // small convenience

         int maxCount = data.Length * 10; // sanity check
         int ct = 0;
         while (changed == true && success == true && ct < maxCount)
         {
             ++ct; // k-means typically converges very quickly
             success = UpdateMeans(data, clustering, means); // compute new cluster means if possible. no effect if fail
             changed = UpdateClustering(data, clustering, means); // (re)assign tuples to clusters. no effect if fail
         }
         // consider adding means[][] as an out parameter - the final means could be computed
         // the final means are useful in some scenarios (e.g., discretization and RBF centroids)
         // and even though you can compute final means from final clustering, in some cases it
         // makes sense to return the means (at the expense of some method signature uglinesss)
         //
         // another alternative is to return, as an out parameter, some measure of cluster goodness
         // such as the average distance between cluster means, or the average distance between tuples in 
         // a cluster, or a weighted combination of both
         return clustering;
     }

     private static int[][] Normalized(int[][] rawData)
     {
         // normalize raw data by computing (x - mean) / stddev
         // primary alternative is min-max:
         // v' = (v - min) / (max - min)

         // make a copy of input data
         int[][] result = new int[rawData.Length][];
         for (int i = 0; i < rawData.Length; ++i)
         {
             result[i] = new int[rawData[i].Length];
             Array.Copy(rawData[i], result[i], rawData[i].Length);
         }

         for (int j = 0; j < result[0].Length; ++j) // each col
         {
             int colSum = 0;
             for (int i = 0; i < result.Length; ++i)
                 colSum += result[i][j];
             int mean = colSum / result.Length;
             int sum = 0;
             for (int i = 0; i < result.Length; ++i)
                 sum += (result[i][j] - mean) * (result[i][j] - mean);
             int sd = sum / result.Length;
             for (int i = 0; i < result.Length; ++i)
                 result[i][j] = (result[i][j] - mean) / sd;
         }
         return result;
     }

     private static int[] InitClustering(int numTuples, int numClusters, int randomSeed)
     {
         // init clustering semi-randomly (at least one tuple in each cluster)
         // consider alternatives, especially k-means++ initialization,
         // or instead of randomly assigning each tuple to a cluster, pick
         // numClusters of the tuples as initial centroids/means then use
         // those means to assign each tuple to an initial cluster.
         Random random = new Random(randomSeed);
         int[] clustering = new int[numTuples];
         for (int i = 0; i < numClusters; ++i) // make sure each cluster has at least one tuple
             clustering[i] = i;
         for (int i = numClusters; i < clustering.Length; ++i)
             clustering[i] = random.Next(0, numClusters); // other assignments random
         return clustering;
     }

     private static int[][] Allocate(int numClusters, int numColumns)
     {
         // convenience matrix allocator for Cluster()
         int[][] result = new int[numClusters][];
         for (int k = 0; k < numClusters; ++k)
             result[k] = new int[numColumns];
         return result;
     }

     private static bool UpdateMeans(int[][] data, int[] clustering, int[][] means)
     {
         // returns false if there is a cluster that has no tuples assigned to it
         // parameter means[][] is really a ref parameter

         // check existing cluster counts
         // can omit this check if InitClustering and UpdateClustering
         // both guarantee at least one tuple in each cluster (usually true)
         int numClusters = means.Length;
         int[] clusterCounts = new int[numClusters];
         for (int i = 0; i < data.Length; ++i)
         {
             int cluster = clustering[i];
             ++clusterCounts[cluster];
         }

         for (int k = 0; k < numClusters; ++k)
             if (clusterCounts[k] == 0)
                 return false; // bad clustering. no change to means[][]

         // update, zero-out means so it can be used as scratch matrix 
         for (int k = 0; k < means.Length; ++k)
             for (int j = 0; j < means[k].Length; ++j)
                 means[k][j] = 0;

         for (int i = 0; i < data.Length; ++i)
         {
             int cluster = clustering[i];
             for (int j = 0; j < data[i].Length; ++j)
                 means[cluster][j] += data[i][j]; // accumulate sum
         }

         for (int k = 0; k < means.Length; ++k)
             for (int j = 0; j < means[k].Length; ++j)
                 means[k][j] /= clusterCounts[k]; // danger of div by 0
         return true;
     }

     private static bool UpdateClustering(int[][] data, int[] clustering, int[][] means)
     {
         // (re)assign each tuple to a cluster (closest mean)
         // returns false if no tuple assignments change OR
         // if the reassignment would result in a clustering where
         // one or more clusters have no tuples.

         int numClusters = means.Length;
         bool changed = false;

         int[] newClustering = new int[clustering.Length]; // proposed result
         Array.Copy(clustering, newClustering, clustering.Length);

         int[] distances = new int[numClusters]; // distances from curr tuple to each mean

         for (int i = 0; i < data.Length; ++i) // walk thru each tuple
         {
             //for (int k = 0; k < numClusters; ++k)
            //     distances[k] = Distance(data[i], means[k]); // compute distances from curr tuple to all k means

             int newClusterID = MinIndex(distances); // find closest mean ID
             if (newClusterID != newClustering[i])
             {
                 changed = true;
                 newClustering[i] = newClusterID; // update
             }
         }

         if (changed == false)
             return false; // no change so bail and don't update clustering[][]

         // check proposed clustering[] cluster counts
         int[] clusterCounts = new int[numClusters];
         for (int i = 0; i < data.Length; ++i)
         {
             int cluster = newClustering[i];
             ++clusterCounts[cluster];
         }

         for (int k = 0; k < numClusters; ++k)
             if (clusterCounts[k] == 0)
                 return false; // bad clustering. no change to clustering[][]

         Array.Copy(newClustering, clustering, newClustering.Length); // update
         return true; // good clustering and at least one change
     }

  /*   private static int Distance(int[] tuple, int[] mean)
     {
         // Euclidean distance between two vectors for UpdateClustering()
         // consider alternatives such as Manhattan distance
         int sumSquaredDiffs = 0;
         for (int j = 0; j < tuple.Length; ++j)
             sumSquaredDiffs += Math.Pow((tuple[j] - mean[j]), 2);
         return Math.Sqrt(sumSquaredDiffs);
     }
        */
     private static int MinIndex(int[] distances)
     {
         // index of smallest value in array
         // helper for UpdateClustering()
         int indexOfMin = 0;
         int smallDist = distances[0];
         for (int k = 0; k < distances.Length; ++k)
         {
             if (distances[k] < smallDist)
             {
                 smallDist = distances[k];
                 indexOfMin = k;
             }
         }
         return indexOfMin;
     }

     // ============================================================================

     // misc display helpers for demo

      void ShowData(int[][] data, int decimals, bool indices, bool newLine)
     {
         for (int i = 0; i < data.Length; ++i)
         {
             if (indices)
                 kmean_richTextBox1.Text += (i.ToString().PadLeft(3) + " ");
             for (int j = 0; j < data[i].Length; ++j)
            //     for (int j = 0; j <10; ++j)
             {
                 if (data[i][j] >= 0)  kmean_richTextBox1.Text +=" \t";
                 kmean_richTextBox1.Text += (data[i][j].ToString("F" + decimals) + " ");
             }
             kmean_richTextBox1.Text += " \n";
         }
         if (newLine)  kmean_richTextBox1.Text +="";
     } // ShowData

      void ShowVector(int[] vector, bool newLine)
     {
         for (int i = 0; i < vector.Length; ++i)
             kmean_richTextBox1.Text += (vector[i] + " ");
         if (newLine)  kmean_richTextBox1.Text +="\n";
     }

      void ShowClustered(int[][] data, int[] clustering, int numClusters, int decimals)
     {
         Random rdn = new Random();
         for (int k = 0; k < numClusters; ++k)
         {
              kmean_richTextBox1.Text +="\n===================\n";
             for (int i = 0; i < data.Length; ++i)
             {
                 int clusterID = clustering[i];
                 if (clusterID != k) continue;
                 kmean_richTextBox1.Text += (i.ToString().PadLeft(3) + " ");
                 for (int j = 0; j < data[i].Length; ++j)
                 {
                     if (data[i][j] >= 0)  kmean_richTextBox1.Text +="\t ";

                     kmean_richTextBox1.Text += (data[i][j].ToString("F" + decimals) + "\t ");

                    // chart1.Series["test1"].Points.AddXY(rdn.Next(0, 10), rdn.Next(0, 10));
                     int a = data[i][j];
                    // int f = j + 1;

                     int b = data[i][j];
                     int c = Convert.ToInt32(a);
                     int d = Convert.ToInt32(b);

         chart1.Series["test1"].Points.Add(rdn.Next(c,d));//,c)), rdn.Next(0, d));
                 }
                  kmean_richTextBox1.Text +="\n";
             }
              kmean_richTextBox1.Text +="\n===================";
         }    
           


          /////////////////////////////////////////**************Graph Plot ***************/////////////////////////////////////////////
/*

        // Random rdn = new Random();
         for (int i = 0; i < 50; i++)
         {
             chart1.Series["test1"].Points.AddXY
                             (rdn.Next(0, 10), rdn.Next(0, 10));
            // chart1.Series.Add("satish");
         }

        // chart1.Series["test1"].ChartType =chart1.SeriesChartType.FastLine;
         chart1.Series["test1"].Color = Color.Red;

        */           
    







          ////////////////////////////////////////////////////////////////////////////////////






        }

     private void cluster_analysis_Load(object sender, EventArgs e)
     {
        
         
         
         //////////////////////***************************////////////////////////////////
         /*const int MaxX = 20;
            // Create new Graph
            chart = new Graph.Chart();
            chart.Location = new System.Drawing.Point(10, 10);
            chart.Size = new System.Drawing.Size(700, 700);
            // Add a chartarea called "draw", add axes to it and color the area black
            chart.ChartAreas.Add("draw");
            chart.ChartAreas["draw"].AxisX.Minimum = 0;
            chart.ChartAreas["draw"].AxisX.Maximum = MaxX;
            chart.ChartAreas["draw"].AxisX.Interval = 1;
            chart.ChartAreas["draw"].AxisX.MajorGrid.LineColor = Color.White;
            chart.ChartAreas["draw"].AxisX.MajorGrid.LineDashStyle = Graph.ChartDashStyle.Dash;
            chart.ChartAreas["draw"].AxisY.Minimum = -0.4;
            chart.ChartAreas["draw"].AxisY.Maximum = 1;
            chart.ChartAreas["draw"].AxisY.Interval = 0.2;
            chart.ChartAreas["draw"].AxisY.MajorGrid.LineColor = Color.White;
            chart.ChartAreas["draw"].AxisY.MajorGrid.LineDashStyle = Graph.ChartDashStyle.Dash;
            
            chart.ChartAreas["draw"].BackColor = Color.Black;
            
            // Create a new function series
            chart.Series.Add("MyFunc");
            // Set the type to line      
            chart.Series["MyFunc"].ChartType = Graph.SeriesChartType.Line;
            // Color the line of the graph light green and give it a thickness of 3
            chart.Series["MyFunc"].Color = Color.LightGreen;
            chart.Series["MyFunc"].BorderWidth = 3; 
            //This function cannot include zero, and we walk through it in steps of 0.1 to add coordinates to our series
            for (int x = 0.1; x < MaxX; x += 0.1)
            {
                chart.Series["MyFunc"].Points.AddXY(x, Math.Sin(x) / x);
            }
            chart.Series["MyFunc"].LegendText = "sin(x) / x";
            // Create a new legend called "MyLegend".
            chart.Legends.Add("MyLegend");
            chart.Legends["MyLegend"].BorderColor = Color.Tomato; // I like tomato juice!
            Controls.Add(this.chart); 
          * 
          */

         //////////////////////***************************////////////////////////////////
        }
     }
    
    
    }

Richard MacCutchan

Это потому, что вы не объявили объект с таким именем.

ZurdoDev

Это очень легко отладить. Почему вы застряли?

3 Ответов

Рейтинг:
2

Nirav Prabtani

Переменная, имеющая имя Data не существует.

Я думаю, что вы прокомментировали эту строку там, где вы ее объявили.

int[][] data = Normalized(rawData); // so large values don't dominate


это проверить.


Рейтинг:
2

Patrice T

//  int[][] data = Normalized(rawData); // so large values don't dominate

Тот факт, что вы прокомментировали строку, создающую переменную, может объяснить, почему вы получаете ошибку.
Если вы внимательно посмотрели на сообщение, оно также сообщит вам, где находится ошибка. Это позволяет сузить область исследования.


Рейтинг:
0

OriginalGriff

Потому что вы это прокомментировали...

//  int[][] data = Normalized(rawData); // so large values don't dominate
 

...
         int[] clustering = InitClustering(data.Length, numClusters, 0); // semi-random initialization
         int[][] means = Allocate(numClusters, data[0].Length); // small convenience