Ejemplo n.º 1
0
        /// <summary>
        /// Determines all categories --> categories
        /// Determines category numbers of each attributes -->> categoryTypeNumber
        /// Determines target numbers and amounts of each categories of each attributes  -->> categoryTypeTargetNumber
        /// [i][j][k] i means attributes, j means  categories, k means targets
        /// </summary>
        /// <param name="insts"></param>
        private void DataPreparation(weka.core.Instances insts)
        {
            for (int i = 0; i < insts.numAttributes(); i++)
            {
                string[] categoryType = new string[insts.attribute(i).numValues()];
                for (int j = 0; j < insts.attribute(i).numValues(); j++)
                {
                    categoryType[j] = insts.attribute(i).value(j).ToString();
                }
                categories.Add(categoryType);
            }

            List <List <string> > lst = new List <List <string> >();

            for (int i = 0; i < insts.numInstances(); i++)
            {
                lst.Add(new List <string>());

                for (int j = 0; j < insts.instance(i).numValues(); j++)
                {
                    lst[lst.Count - 1].Add(insts.instance(i).toString(j));
                }
            }

            List <int[]>   categoryTypeNumber       = new List <int[]>();
            List <int[, ]> categoryTypeTargetNumber = new List <int[, ]>();

            for (int i = 0; i < categories.Count; i++)
            {
                categoryTypeNumber.Add(new int[categories[i].Length]);
                categoryTypeTargetNumber.Add(new int[categories[i].Length, categories[categories.Count - 1].Length]);
            }

            for (int i = 0; i < lst.Count; i++)                    //Satır
            {
                for (int j = 0; j < lst[i].Count; j++)             //Sütün
                {
                    for (int k = 0; k < categories[j].Length; k++) //Kategori Sayısı
                    {
                        string targetValue = lst[i][lst[i].Count - 1];
                        if (lst[i][j].Contains(categories[j][k]))
                        {
                            categoryTypeNumber[j][k] += 1;
                            for (int trgt = 0; trgt < categories[categories.Count - 1].Length; trgt++)
                            {
                                if (targetValue == categories[categories.Count - 1][trgt])
                                {
                                    categoryTypeTargetNumber[j][k, trgt] += 1;
                                }
                            }
                        }
                    }
                }
            }
            Twoing(insts, categoryTypeNumber, categoryTypeTargetNumber);
            Gini(insts, categoryTypeNumber, categoryTypeTargetNumber);
            LogInfo("Dataset is saved.\r\n\r\n");
            LogInfo("TWOING : " + twoingPath + "\r\n\r\n");
            LogInfo("GINI : " + giniPath + "\r\n");
        }
Ejemplo n.º 2
0
 public void Build()
 {
     this.featureIndex = new int[this.features.Count];
     for(int i=0;(i< this.features.Count);i++)
     {
         for (int j = 0; (j < Extractor.ArffAttributeLabels.Length); j++)
             if (((string)this.features[i]).Equals(Extractor.ArffAttributeLabels[j]))
             {
                 this.featureIndex[i] = j;
                 break;
             }
     }
     instances = new Instances(new StreamReader(this.filename));
     instances.Class = instances.attribute(this.features.Count);
     classifier = new J48();
     classifier.buildClassifier(instances);
     
     //setup the feature vector 
     //fvWekaAttributes = new FastVector(this.features.Count + 1);
     //for (i = 0; (i < this.features.Count); i++)
     //    fvWekaAttributes.addElement(new weka.core.Attribute(this.features[i]));
     
     
     //Setup the class attribute
     //FastVector fvClassVal = new FastVector();
     //for (i = 0; (i < this.classes.Count); i++)           
      //   fvClassVal.addElement(this.classes[i]);            
     //weka.core.Attribute ClassAttribute = new weka.core.Attribute("activity", fvClassVal);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Adds teta results of gini results to the list
        /// Change the attributes of the arff file
        /// Adds the attributes to arff file
        /// </summary>
        /// <param name="insts"></param>
        /// <param name="result"></param>
        /// <param name="path"></param>
        private void CreateNewDataset(weka.core.Instances insts, List <double[]> result, string path)
        {
            //Tetaları Listeye Ekle
            List <List <string> > lst = new List <List <string> >();

            for (int i = 0; i < insts.numInstances(); i++)
            {
                lst.Add(new List <string>());
                for (int j = 0; j < insts.instance(i).numValues() - 1; j++)
                {
                    string value = insts.instance(i).toString(j);
                    for (int k = 0; k < categories[j].Length; k++)
                    {
                        if (insts.instance(i).toString(j) == categories[j][k])
                        {
                            lst[lst.Count - 1].Add(String.Format("{0:0.00}", result[j][k]));
                            break;
                        }
                    }
                }
            }
            //Attiribute Değiştir
            for (int i = 0; i < insts.numAttributes() - 1; i++)
            {
                string name = insts.attribute(i).name().ToString();
                insts.deleteAttributeAt(i);
                weka.core.Attribute att = new weka.core.Attribute(name);
                insts.insertAttributeAt(att, i);
            }

            //Attiributeları yaz
            for (int i = 0; i < insts.numInstances(); i++)
            {
                for (int j = 0; j < insts.instance(i).numValues() - 1; j++)
                {
                    insts.instance(i).setValue(j, Convert.ToDouble(lst[i][j]));
                }
            }

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            var saver = new ArffSaver();

            saver.setInstances(insts);
            saver.setFile(new java.io.File(path));
            saver.writeBatch();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(file));
            double[]            Data  = new double[insts.numAttributes()];
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].GetType() == typeof(TextBox))
                {
                    TextBox txt   = (TextBox)list[i];
                    string  value = txt.Text.Replace('.', ',');
                    Data[i] = Convert.ToDouble(value);
                }
                else
                {
                    ComboBox combobox = (ComboBox)list[i];
                    Data[i] = Convert.ToDouble(combobox.SelectedIndex);
                }
            }
            // Data[(insts.numAttributes() - 1] = 0;
            insts.setClassIndex(insts.numAttributes() - 1);
            Instance newInsts = new Instance(1.0, Data);

            insts.add(newInsts);
            string type = model.GetType().ToString();

            if (type == "weka.classifiers.bayes.NaiveBayes")
            {
                weka.filters.Filter myDiscretize = new weka.filters.unsupervised.attribute.Discretize();
                myDiscretize.setInputFormat(insts);
                insts = weka.filters.Filter.useFilter(insts, myDiscretize);
            }
            else if (type == "weka.classifiers.lazy.IBk")
            {
                weka.filters.Filter myDummy = new weka.filters.unsupervised.attribute.NominalToBinary();
                myDummy.setInputFormat(insts);
                insts = weka.filters.Filter.useFilter(insts, myDummy);

                weka.filters.Filter myNormalize = new weka.filters.unsupervised.instance.Normalize();
                myNormalize.setInputFormat(insts);
                insts = weka.filters.Filter.useFilter(insts, myNormalize);
            }
            double index = model.classifyInstance(insts.lastInstance());

            string result = insts.attribute(insts.numAttributes() - 1).value(Convert.ToInt16(index));

            MessageBox.Show(result);
        }
Ejemplo n.º 5
0
		/// <summary> Prints left side of condition..
		/// 
		/// </summary>
		/// <param name="data">training set.
		/// </param>
		public override System.String leftSide(Instances data)
		{
			
			return data.attribute(m_attIndex).name();
		}
Ejemplo n.º 6
0
		/// <summary> Creates a C4.5-type split on the given data. Assumes that none of
		/// the class values is missing.
		/// 
		/// </summary>
		/// <exception cref="Exception">if something goes wrong
		/// </exception>
		public override void  buildClassifier(Instances trainInstances)
		{
			
			// Initialize the remaining instance variables.
			m_numSubsets = 0;
			//UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
			m_splitPoint = System.Double.MaxValue;
			m_infoGain = 0;
			m_gainRatio = 0;
			
			// Different treatment for enumerated and numeric
			// attributes.
			if (trainInstances.attribute(m_attIndex).Nominal)
			{
				m_complexityIndex = trainInstances.attribute(m_attIndex).numValues();
				m_index = m_complexityIndex;
				handleEnumeratedAttribute(trainInstances);
			}
			else
			{
				m_complexityIndex = 2;
				m_index = 0;
				trainInstances.sort(trainInstances.attribute(m_attIndex));
				handleNumericAttribute(trainInstances);
			}
		}
Ejemplo n.º 7
0
		/// <summary> Returns a string containing java source code equivalent to the test
		/// made at this node. The instance being tested is called "i".
		/// 
		/// </summary>
		/// <param name="index">index of the nominal value tested
		/// </param>
		/// <param name="data">the data containing instance structure info
		/// </param>
		/// <returns> a value of type 'String'
		/// </returns>
		public override System.String sourceExpression(int index, Instances data)
		{
			
			System.Text.StringBuilder expr = null;
			if (index < 0)
			{
				return "i[" + m_attIndex + "] == null";
			}
			if (data.attribute(m_attIndex).Nominal)
			{
				if (index == 0)
				{
					expr = new System.Text.StringBuilder("i[");
				}
				else
				{
					expr = new System.Text.StringBuilder("!i[");
				}
				expr.Append(m_attIndex).Append("]");
				//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
				expr.Append(".equals(\"").Append(data.attribute(m_attIndex).value_Renamed((int) m_splitPoint)).Append("\")");
			}
			else
			{
				expr = new System.Text.StringBuilder("((Double) i[");
				expr.Append(m_attIndex).Append("])");
				if (index == 0)
				{
					expr.Append(".doubleValue() <= ").Append(m_splitPoint);
				}
				else
				{
					expr.Append(".doubleValue() > ").Append(m_splitPoint);
				}
			}
			return expr.ToString();
		}
Ejemplo n.º 8
0
		/// <summary> Prints the condition satisfied by instances in a subset.
		/// 
		/// </summary>
		/// <param name="index">of subset and training set.
		/// </param>
		public override System.String rightSide(int index, Instances data)
		{
			
			System.Text.StringBuilder text;
			
			text = new System.Text.StringBuilder();
			if (data.attribute(m_attIndex).Nominal)
			{
				if (index == 0)
				{
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					text.Append(" = " + data.attribute(m_attIndex).value_Renamed((int) m_splitPoint));
				}
				else
				{
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					text.Append(" != " + data.attribute(m_attIndex).value_Renamed((int) m_splitPoint));
				}
			}
			else if (index == 0)
				text.Append(" <= " + m_splitPoint);
			else
				text.Append(" > " + m_splitPoint);
			
			return text.ToString();
		}
        public MITesDataCollectionForm(string dataDirectory, string arffFile, bool isHierarchical)
        { 
        

                       //where data is being stored
            this.dataDirectory = dataDirectory;

            //Initialize high resolution unix timer
            UnixTime.InitializeTime();

            //Initialize and start GUI progress thread
            progressMessage = null;
            aProgressThread = new Thread(new ThreadStart(ProgressThread));
            aProgressThread.Start();


            #region Load Configuration files
            //load the activity and sensor configuration files
            progressMessage = "Loading XML protocol and sensors ...";
            AXML.Reader reader = new AXML.Reader(Constants.MASTER_DIRECTORY, dataDirectory);
#if (!PocketPC)
            if (reader.validate() == false)
            {
                throw new Exception("Error Code 0: XML format error - activities.xml does not match activities.xsd!");
            }
            else
            {
#endif
            this.annotation = reader.parse();
            this.annotation.DataDirectory = dataDirectory;
            SXML.Reader sreader = new SXML.Reader(Constants.MASTER_DIRECTORY, dataDirectory);
#if (!PocketPC)

                if (sreader.validate() == false)
                {
                    throw new Exception("Error Code 0: XML format error - sensors.xml does not match sensors.xsd!");
                }
                else
                {
#endif
            this.sensors = sreader.parse(Constants.MAX_CONTROLLERS);
            progressMessage += " Completed\r\n";

            //TODO: remove BT components
            progressMessage += "Loading configuration file ...";
            MITesFeatures.core.conf.ConfigurationReader creader = new MITesFeatures.core.conf.ConfigurationReader(dataDirectory);
            this.configuration = creader.parse();
            progressMessage += " Completed\r\n";
#if (!PocketPC)
                }
            }
#endif
            #endregion Load Configuration files



            #region Initialize External Data Reception Channels

                //Initialize 1 master decoder
                this.masterDecoder = new MITesDecoder();

                //Initialize the software mode
                isExtracting = false;
                isCollectingDetailedData = false;
                isPlotting = true;
                isClassifying = true;


                #region Initialize Feature Extraction
                this.isExtracting = false;
                if (this.sensors.TotalReceivers > 0) // if there is at least 1 MIT
                    //Extractor.Initialize(this.mitesDecoders[0], dataDirectory, this.annotation, this.sensors, this.configuration);
                    Extractor.Initialize(this.masterDecoder, dataDirectory, this.annotation, this.sensors, this.configuration);
                else if (this.sensors.Sensors.Count > 0) // only built in
                    Extractor.Initialize(this.masterDecoder, dataDirectory, this.annotation, this.sensors, this.configuration);
                #endregion Initialize Feature Extraction

                labelIndex = new Hashtable();
                instances = new Instances(new StreamReader(arffFile));
                instances.Class = instances.attribute(Extractor.ArffAttributeLabels.Length);
                classifier = new J48();
                if (!File.Exists("model.xml"))
                {
                    classifier.buildClassifier(instances);
                    TextWriter tc = new StreamWriter("model.xml");
                    classifier.toXML(tc);
                    tc.Flush();
                    tc.Close();
                }
                else
                    classifier.buildClassifier("model.xml", instances);

               
                fvWekaAttributes = new FastVector(Extractor.ArffAttributeLabels.Length + 1);
                for (int i = 0; (i < Extractor.ArffAttributeLabels.Length); i++)
                    fvWekaAttributes.addElement(new weka.core.Attribute(Extractor.ArffAttributeLabels[i]));

                FastVector fvClassVal = new FastVector();
                labelCounters = new int[((AXML.Category)this.annotation.Categories[0]).Labels.Count + 1];
                activityLabels = new string[((AXML.Category)this.annotation.Categories[0]).Labels.Count + 1];
                for (int i = 0; (i < ((AXML.Category)this.annotation.Categories[0]).Labels.Count); i++)
                {
                    labelCounters[i] = 0;
                    string label = "";
                    int j = 0;
                    for (j = 0; (j < this.annotation.Categories.Count - 1); j++)
                        label += ((AXML.Label)((AXML.Category)this.annotation.Categories[j]).Labels[i]).Name.Replace(' ', '_') + "_";
                    label += ((AXML.Label)((AXML.Category)this.annotation.Categories[j]).Labels[i]).Name.Replace(' ', '_');
                    activityLabels[i] = label;
                    labelIndex.Add(label, i);
                    fvClassVal.addElement(label);
                }

                weka.core.Attribute ClassAttribute = new weka.core.Attribute("activity", fvClassVal);

                isClassifying = true;

                this.aMITesActivityCounters = new Hashtable();


                if (!((this.sensors.Sensors.Count == 1) && (this.sensors.HasBuiltinSensors)))
                {
                    //Initialize arrays to store USB and Bluetooth controllers
                    this.mitesControllers = new MITesReceiverController[this.sensors.TotalWiredReceivers];

#if (PocketPC)
                    this.bluetoothControllers = new BluetoothController[this.sensors.TotalBluetoothReceivers];
                    //this.ts = new Thread[this.sensors.TotalBluetoothReceivers];
#endif

                    //Initialize array to store Bluetooth connection status
                    //this.bluetoothConnectionStatus = new bool[this.sensors.TotalBluetoothReceivers];

                    //Initialize a decoder for each sensor
                    this.mitesDecoders = new MITesDecoder[this.sensors.TotalReceivers];


#if (PocketPC)
                    #region Bluetooth reception channels initialization
                    //Initialize and search for wockets connections
                    progressMessage += "Initializing Bluetooth receivers ... searching " + this.sensors.TotalBluetoothReceivers + " BT receivers\r\n";
                    //Try to initialize all Bluetooth receivers 10 times then exit
                    int initializationAttempt = 0;
                    while (initializationAttempt <= 10)
                    {
                        if (InitializeBluetoothReceivers() == false)
                        {
                            initializationAttempt++;

                            if (initializationAttempt == 10)
                            {
                                MessageBox.Show("Exiting: Some Bluetooth receivers in your configuration were not initialized.");
                                Application.Exit();
                                System.Diagnostics.Process.GetCurrentProcess().Kill();

                            }
                            else
                                progressMessage += "Failed to initialize all BT connections. Retrying (" + initializationAttempt + ")...\r\n";

                        }
                        else
                            break;
                        Thread.Sleep(2000);
                    }
                    #endregion Bluetooth reception channels initialization
#endif
                    #region USB reception channels initialization

                    if (InitializeUSBReceivers() == false)
                    {
                        MessageBox.Show("Exiting: Some USB receivers in your configuration were not initialized.");
#if (PocketPC)
                        Application.Exit();
                        System.Diagnostics.Process.GetCurrentProcess().Kill();
#else
                    Environment.Exit(0);
#endif

                    }
                    #endregion USB reception channels initialization

                }
                    //}
            #endregion Initialize External Data Reception Channels

#if (PocketPC)
            #region Initialize Builtin Data Reception Channels
            if (InitializeBuiltinReceivers() == false)
            {
                MessageBox.Show("Exiting: A built in receiver channel was not found.");
                Application.Exit();
                System.Diagnostics.Process.GetCurrentProcess().Kill();

            }
            #endregion Initialize Builtin Data Reception Channels

#endif            

            #region Initialize GUI Components
            //initialize the interface components
            InitializeComponent();
            //Initialize GUI timers
            progressMessage += "Initializing Timers ...";
            InitializeTimers();
            progressMessage += " Completed\r\n";

            //Initialize different GUI components
            progressMessage += "Initializing GUI ...";
            InitializeInterface();
            progressMessage += " Completed\r\n";

            this.isPlotting = true;
            //count the number of accelerometers
            if (this.sensors.IsHR)
                this.maxPlots = this.sensors.Sensors.Count - 1;
            else
                this.maxPlots = this.sensors.Sensors.Count;
            SetFormPositions();
            if (this.sensors.TotalReceivers > 0)
                aMITesPlotter = new MITesScalablePlotter(this.panel1, MITesScalablePlotter.DeviceTypes.IPAQ, maxPlots, this.masterDecoder, GetGraphSize(false));
            else
                aMITesPlotter = new MITesScalablePlotter(this.panel1, MITesScalablePlotter.DeviceTypes.IPAQ, maxPlots, this.masterDecoder, GetGraphSize(false));

            //Override the resize event
#if (PocketPC)
            this.Resize += new EventHandler(OnResize);
#else
            this.form1.Resize += new EventHandler(OnResizeForm1);
            this.form1.FormClosing += new FormClosingEventHandler(form_FormClosing);
            this.form2.Resize += new EventHandler(OnResizeForm2);
            this.form2.FormClosing += new FormClosingEventHandler(form_FormClosing);
            this.form3.Resize += new EventHandler(OnResizeForm3);
            this.form3.FormClosing += new FormClosingEventHandler(form_FormClosing);
            this.form4.Resize += new EventHandler(OnResizeForm4);
            this.form4.FormClosing += new FormClosingEventHandler(form_FormClosing);
#endif

            //Initialize the quality interface
            progressMessage += "Initializing MITes Quality GUI ...";
            InitializeQualityInterface();
            progressMessage += " Completed\r\n";

            //Remove classifier tabs
#if (PocketPC)

            this.tabControl1.TabPages.RemoveAt(4);
            this.tabControl1.SelectedIndex = 0;
#else
            this.ShowForms();
#endif


            #endregion Initialize GUI Components



            #region Initialize Quality Tracking variables
            InitializeQuality();
            #endregion Initialize Quality Tracking variables

            #region Initialize Logging
            InitializeLogging(dataDirectory);
            #endregion Initialize Logging

            #region Initialize CSV Storage (PC Only)
#if (!PocketPC)

            //create some counters for activity counts
            averageX = new int[this.sensors.MaximumSensorID + 1];
            averageY = new int[this.sensors.MaximumSensorID + 1];
            averageZ = new int[this.sensors.MaximumSensorID + 1];

            averageRawX = new int[this.sensors.MaximumSensorID + 1];
            averageRawY = new int[this.sensors.MaximumSensorID + 1];
            averageRawZ = new int[this.sensors.MaximumSensorID + 1];

            prevX = new int[this.sensors.MaximumSensorID + 1];
            prevY = new int[this.sensors.MaximumSensorID + 1];
            prevZ = new int[this.sensors.MaximumSensorID + 1];
            acCounters = new int[this.sensors.MaximumSensorID + 1];
            activityCountWindowSize = 0;

            activityCountCSVs = new StreamWriter[this.sensors.MaximumSensorID + 1];
            samplingCSVs = new StreamWriter[this.sensors.MaximumSensorID + 1];
            averagedRaw = new StreamWriter[this.sensors.MaximumSensorID + 1];
            masterCSV = new StreamWriter(dataDirectory + "\\MITesSummaryData.csv");
            hrCSV = new StreamWriter(dataDirectory + "\\HeartRate_MITes.csv");

            string csv_line1 = "UnixTimeStamp,TimeStamp,X,Y,Z";
            string csv_line2 = "UnixTimeStamp,TimeStamp,Sampling";
            string hr_csv_header = "UnixTimeStamp,TimeStamp,HR";
            string master_csv_header = "UnixTimeStamp,TimeStamp";
            foreach (Category category in this.annotation.Categories)
                master_csv_header += "," + category.Name;


            foreach (Sensor sensor in this.sensors.Sensors)
            {
                int sensor_id = Convert.ToInt32(sensor.ID);
                string location = sensor.Location.Replace(' ', '-');
                if (sensor_id > 0) //exclude HR
                {
                    activityCountCSVs[sensor_id] = new StreamWriter(dataDirectory + "\\MITes_" + sensor_id.ToString("00") + "_ActivityCount_" + location + ".csv");
                    activityCountCSVs[sensor_id].WriteLine(csv_line1);
                    averagedRaw[sensor_id] = new StreamWriter(dataDirectory + "\\MITes_" + sensor_id.ToString("00") + "_1s-RawMean_" + location + ".csv");
                    averagedRaw[sensor_id].WriteLine(csv_line1);
                    samplingCSVs[sensor_id] = new StreamWriter(dataDirectory + "\\MITes_" + sensor_id.ToString("00") + "_SampleRate_" + location + ".csv");
                    samplingCSVs[sensor_id].WriteLine(csv_line2);
                    master_csv_header += ",MITes" + sensor_id.ToString("00") + "_SR," + "MITes" + sensor_id.ToString("00") + "_AVRaw_X," +
                        "MITes" + sensor_id.ToString("00") + "_AVRaw_Y," + "MITes" + sensor_id.ToString("00") + "_AVRaw_Z," + "MITes" + sensor_id.ToString("00") + "_AC_X," +
                        "MITes" + sensor_id.ToString("00") + "_AC_Y," + "MITes" + sensor_id.ToString("00") + "_AC_Z";

                }
            }

            master_csv_header += ",HR";
            this.masterCSV.WriteLine(master_csv_header);
            this.hrCSV.WriteLine(hr_csv_header);
#endif

            #endregion Initialize CSV Storage (PC Only)

            #region Start Collecting Data



            //if (this.sensors.TotalReceivers > 0)
            //    isStartedReceiver = true;
            //Start the built in polling thread            
#if (PocketPC)
            if (this.sensors.HasBuiltinSensors)
            {
                this.pollingThread = new Thread(new ThreadStart(this.pollingData));
                this.pollingThread.Priority = ThreadPriority.Lowest;
                this.pollingThread.Start();
            }
#endif

            //Terminate the progress thread
            progressThreadQuit = true;

           
            //Enable all timer functions
            this.readDataTimer.Enabled = true;
            this.qualityTimer.Enabled = true;
            if (this.sensors.IsHR)
                this.HRTimer.Enabled = true;

            #endregion Start Collecting Data

        }
Ejemplo n.º 10
0
		/// <summary> Returns the minsAndMaxs of the index.th subset.</summary>
		public double[][] minsAndMaxs(Instances data, double[][] minsAndMaxs, int index)
		{
			
			double[][] newMinsAndMaxs = new double[data.numAttributes()][];
			for (int i = 0; i < data.numAttributes(); i++)
			{
				newMinsAndMaxs[i] = new double[2];
			}
			
			for (int i = 0; i < data.numAttributes(); i++)
			{
				newMinsAndMaxs[i][0] = minsAndMaxs[i][0];
				newMinsAndMaxs[i][1] = minsAndMaxs[i][1];
				if (i == m_attIndex)
					if (data.attribute(m_attIndex).Nominal)
						newMinsAndMaxs[m_attIndex][1] = 1;
					else
						newMinsAndMaxs[m_attIndex][1 - index] = m_splitPoint;
			}
			
			return newMinsAndMaxs;
		}
Ejemplo n.º 11
0
        /// <summary>
        /// Build the learning model for classification
        /// </summary>
        /// <param name="InstancesList">list of instances </param>
        /// <param name="NumberofClusters">Number of Clusters</param>
        /// <param name="TextBoxForFeedback">Text box for the results (can be NULL)</param>
        /// <param name="PanelForVisualFeedback">Panel to display visual results if avalaible (can be NULL)</param>
        public Classifier PerformTraining(FormForClassificationInfo WindowForClassificationParam, Instances InstancesList, /*int NumberofClusters,*/ RichTextBox TextBoxForFeedback,
                                            Panel PanelForVisualFeedback, out weka.classifiers.Evaluation ModelEvaluation, bool IsCellular)
        {
            //   weka.classifiers.Evaluation ModelEvaluation = null;
            // FormForClassificationInfo WindowForClassificationParam = new FormForClassificationInfo(GlobalInfo);
            ModelEvaluation = null;
            //  if (WindowForClassificationParam.ShowDialog() != System.Windows.Forms.DialogResult.OK) return null;
            //   weka.classifiers.Evaluation ModelEvaluation = new Evaluation(

            cParamAlgo ClassifAlgoParams = WindowForClassificationParam.GetSelectedAlgoAndParameters();
            if (ClassifAlgoParams == null) return null;

            //this.Cursor = Cursors.WaitCursor;

            //  cParamAlgo ClassificationAlgo = WindowForClassificationParam.GetSelectedAlgoAndParameters();
            cListValuesParam Parameters = ClassifAlgoParams.GetListValuesParam();

            //Classifier this.CurrentClassifier = null;

            // -------------------------- Classification -------------------------------
            // create the instances
            // InstancesList = this.ListInstances;
            this.attValsWithoutClasses = new FastVector();

            if (IsCellular)
                for (int i = 0; i < cGlobalInfo.ListCellularPhenotypes.Count; i++)
                    this.attValsWithoutClasses.addElement(cGlobalInfo.ListCellularPhenotypes[i].Name);
            else
                for (int i = 0; i < cGlobalInfo.ListWellClasses.Count; i++)
                    this.attValsWithoutClasses.addElement(cGlobalInfo.ListWellClasses[i].Name);

            InstancesList.insertAttributeAt(new weka.core.Attribute("Class", this.attValsWithoutClasses), InstancesList.numAttributes());
            //int A = Classes.Count;
            for (int i = 0; i < Classes.Count; i++)
                InstancesList.get(i).setValue(InstancesList.numAttributes() - 1, Classes[i]);

            InstancesList.setClassIndex(InstancesList.numAttributes() - 1);

            weka.core.Instances train = new weka.core.Instances(InstancesList, 0, InstancesList.numInstances());

            if (PanelForVisualFeedback != null)
                PanelForVisualFeedback.Controls.Clear();

            #region List classifiers

            #region J48
            if (ClassifAlgoParams.Name == "J48")
            {
                this.CurrentClassifier = new weka.classifiers.trees.J48();
                ((J48)this.CurrentClassifier).setMinNumObj((int)Parameters.ListDoubleValues.Get("numericUpDownMinInstLeaf").Value);
                ((J48)this.CurrentClassifier).setConfidenceFactor((float)Parameters.ListDoubleValues.Get("numericUpDownConfFactor").Value);
                ((J48)this.CurrentClassifier).setNumFolds((int)Parameters.ListDoubleValues.Get("numericUpDownNumFolds").Value);
                ((J48)this.CurrentClassifier).setUnpruned((bool)Parameters.ListCheckValues.Get("checkBoxUnPruned").Value);
                ((J48)this.CurrentClassifier).setUseLaplace((bool)Parameters.ListCheckValues.Get("checkBoxLaplacianSmoothing").Value);
                ((J48)this.CurrentClassifier).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ((J48)this.CurrentClassifier).setSubtreeRaising((bool)Parameters.ListCheckValues.Get("checkBoxSubTreeRaising").Value);

                //   CurrentClassif.SetJ48Tree((J48)this.CurrentClassifier, Classes.Length);
                this.CurrentClassifier.buildClassifier(train);
                // display results training
                // display tree
                if (PanelForVisualFeedback != null)
                {
                    GViewer GraphView = DisplayTree(GlobalInfo, ((J48)this.CurrentClassifier), IsCellular).gViewerForTreeClassif;
                    GraphView.Size = new System.Drawing.Size(PanelForVisualFeedback.Width, PanelForVisualFeedback.Height);
                    GraphView.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
                    PanelForVisualFeedback.Controls.Clear();
                    PanelForVisualFeedback.Controls.Add(GraphView);
                }
            }
            #endregion
            #region Random Tree
            else if (ClassifAlgoParams.Name == "RandomTree")
            {
                this.CurrentClassifier = new weka.classifiers.trees.RandomTree();

                if ((bool)Parameters.ListCheckValues.Get("checkBoxMaxDepthUnlimited").Value)
                    ((RandomTree)this.CurrentClassifier).setMaxDepth(0);
                else
                    ((RandomTree)this.CurrentClassifier).setMaxDepth((int)Parameters.ListDoubleValues.Get("numericUpDownMaxDepth").Value);
                ((RandomTree)this.CurrentClassifier).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeed").Value);
                ((RandomTree)this.CurrentClassifier).setMinNum((double)Parameters.ListDoubleValues.Get("numericUpDownMinWeight").Value);

                if ((bool)Parameters.ListCheckValues.Get("checkBoxIsBackfitting").Value)
                {
                    ((RandomTree)this.CurrentClassifier).setNumFolds((int)Parameters.ListDoubleValues.Get("numericUpDownBackFittingFolds").Value);
                }
                else
                {
                    ((RandomTree)this.CurrentClassifier).setNumFolds(0);
                }
                this.CurrentClassifier.buildClassifier(train);
                //string StringForTree = ((RandomTree)this.CurrentClassifier).graph().Remove(0, ((RandomTree)this.CurrentClassifier).graph().IndexOf("{") + 2);

                //Microsoft.Msagl.GraphViewerGdi.GViewer GraphView = new GViewer();
                //GraphView.Graph = GlobalInfo.WindowHCSAnalyzer.ComputeAndDisplayGraph(StringForTree);//.Remove(StringForTree.Length - 3, 3));

                //GraphView.Size = new System.Drawing.Size(panelForGraphicalResults.Width, panelForGraphicalResults.Height);
                //GraphView.Anchor = (AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
                //this.panelForGraphicalResults.Controls.Clear();
                //this.panelForGraphicalResults.Controls.Add(GraphView);

            }
            #endregion
            #region Random Forest
            else if (ClassifAlgoParams.Name == "RandomForest")
            {
                this.CurrentClassifier = new weka.classifiers.trees.RandomForest();

                if ((bool)Parameters.ListCheckValues.Get("checkBoxMaxDepthUnlimited").Value)
                    ((RandomForest)this.CurrentClassifier).setMaxDepth(0);
                else
                    ((RandomForest)this.CurrentClassifier).setMaxDepth((int)Parameters.ListDoubleValues.Get("numericUpDownMaxDepth").Value);

                ((RandomForest)this.CurrentClassifier).setNumTrees((int)Parameters.ListDoubleValues.Get("numericUpDownNumTrees").Value);
                ((RandomForest)this.CurrentClassifier).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeed").Value);

                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region KStar
            else if (ClassifAlgoParams.Name == "KStar")
            {
                this.CurrentClassifier = new weka.classifiers.lazy.KStar();
                ((KStar)this.CurrentClassifier).setGlobalBlend((int)Parameters.ListDoubleValues.Get("numericUpDownGlobalBlend").Value);
                ((KStar)this.CurrentClassifier).setEntropicAutoBlend((bool)Parameters.ListCheckValues.Get("checkBoxBlendAuto").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region SVM
            else if (ClassifAlgoParams.Name == "SVM")
            {
                this.CurrentClassifier = new weka.classifiers.functions.SMO();
                ((SMO)this.CurrentClassifier).setC((double)Parameters.ListDoubleValues.Get("numericUpDownC").Value);
                ((SMO)this.CurrentClassifier).setKernel(WindowForClassificationParam.GeneratedKernel);
                ((SMO)this.CurrentClassifier).setRandomSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeed").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region KNN
            else if (ClassifAlgoParams.Name == "KNN")
            {
                this.CurrentClassifier = new weka.classifiers.lazy.IBk();

                string OptionDistance = " -K " + (int)Parameters.ListDoubleValues.Get("numericUpDownKNN").Value + " -W 0 ";

                string WeightType = (string)Parameters.ListTextValues.Get("comboBoxDistanceWeight").Value;
                switch (WeightType)
                {
                    case "No Weighting":
                        OptionDistance += "";
                        break;
                    case "1/Distance":
                        OptionDistance += "-I";
                        break;
                    case "1-Distance":
                        OptionDistance += "-F";
                        break;
                    default:
                        break;
                }
                OptionDistance += " -A \"weka.core.neighboursearch.LinearNNSearch -A \\\"weka.core.";

                string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;
                // OptionDistance += " -A \"weka.core.";
                switch (DistanceType)
                {
                    case "Euclidean":
                        OptionDistance += "EuclideanDistance";
                        break;
                    case "Manhattan":
                        OptionDistance += "ManhattanDistance";
                        break;
                    case "Chebyshev":
                        OptionDistance += "ChebyshevDistance";
                        break;
                    default:
                        break;
                }

                if (!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value)
                    OptionDistance += " -D";
                OptionDistance += " -R ";

                OptionDistance += "first-last\\\"\"";
                ((IBk)this.CurrentClassifier).setOptions(weka.core.Utils.splitOptions(OptionDistance));

                //((IBk)this.CurrentClassifier).setKNN((int)Parameters.ListDoubleValues.Get("numericUpDownKNN").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region Multilayer Perceptron
            else if (ClassifAlgoParams.Name == "Perceptron")
            {
                this.CurrentClassifier = new weka.classifiers.functions.MultilayerPerceptron();
                ((MultilayerPerceptron)this.CurrentClassifier).setMomentum((double)Parameters.ListDoubleValues.Get("numericUpDownMomentum").Value);
                ((MultilayerPerceptron)this.CurrentClassifier).setLearningRate((double)Parameters.ListDoubleValues.Get("numericUpDownLearningRate").Value);
                ((MultilayerPerceptron)this.CurrentClassifier).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeed").Value);
                ((MultilayerPerceptron)this.CurrentClassifier).setTrainingTime((int)Parameters.ListDoubleValues.Get("numericUpDownTrainingTime").Value);
                ((MultilayerPerceptron)this.CurrentClassifier).setNormalizeAttributes((bool)Parameters.ListCheckValues.Get("checkBoxNormAttribute").Value);
                ((MultilayerPerceptron)this.CurrentClassifier).setNormalizeNumericClass((bool)Parameters.ListCheckValues.Get("checkBoxNormNumericClasses").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region ZeroR
            else if (ClassifAlgoParams.Name == "ZeroR")
            {
                this.CurrentClassifier = new weka.classifiers.rules.OneR();
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region OneR
            else if (ClassifAlgoParams.Name == "OneR")
            {
                this.CurrentClassifier = new weka.classifiers.rules.OneR();
                ((OneR)this.CurrentClassifier).setMinBucketSize((int)Parameters.ListDoubleValues.Get("numericUpDownMinBucketSize").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region Naive Bayes
            else if (ClassifAlgoParams.Name == "NaiveBayes")
            {
                this.CurrentClassifier = new weka.classifiers.bayes.NaiveBayes();
                ((NaiveBayes)this.CurrentClassifier).setUseKernelEstimator((bool)Parameters.ListCheckValues.Get("checkBoxKernelEstimator").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            #region Logistic
            else if (ClassifAlgoParams.Name == "Logistic")
            {
                this.CurrentClassifier = new weka.classifiers.functions.Logistic();
                ((Logistic)this.CurrentClassifier).setUseConjugateGradientDescent((bool)Parameters.ListCheckValues.Get("checkBoxUseConjugateGradientDescent").Value);
                ((Logistic)this.CurrentClassifier).setRidge((double)Parameters.ListDoubleValues.Get("numericUpDownRidge").Value);
                this.CurrentClassifier.buildClassifier(train);
            }
            #endregion
            //weka.classifiers.functions.SMO
            //BayesNet

            #endregion

            if (TextBoxForFeedback != null)
            {
                TextBoxForFeedback.Clear();
                TextBoxForFeedback.AppendText(this.CurrentClassifier.ToString());
            }

            TextBoxForFeedback.AppendText("\n" + (InstancesList.numAttributes() - 1) + " attributes:\n\n");
            for (int IdxAttributes = 0; IdxAttributes < InstancesList.numAttributes() - 1; IdxAttributes++)
            {
                TextBoxForFeedback.AppendText(IdxAttributes + "\t: " + InstancesList.attribute(IdxAttributes).name() + "\n");
            }

            #region evaluation of the model and results display

            if ((WindowForClassificationParam.numericUpDownFoldNumber.Enabled) && (TextBoxForFeedback != null))
            {

                TextBoxForFeedback.AppendText("\n-----------------------------\nModel validation\n-----------------------------\n");
                ModelEvaluation = new weka.classifiers.Evaluation(InstancesList);
                ModelEvaluation.crossValidateModel(this.CurrentClassifier, InstancesList, (int)WindowForClassificationParam.numericUpDownFoldNumber.Value, new java.util.Random(1));
                TextBoxForFeedback.AppendText(ModelEvaluation.toSummaryString());
                TextBoxForFeedback.AppendText("\n-----------------------------\nConfusion Matrix:\n-----------------------------\n");
                double[][] ConfusionMatrix = ModelEvaluation.confusionMatrix();

                string NewLine = "";
                for (int i = 0; i < ConfusionMatrix[0].Length; i++)
                {
                    NewLine += "c" + i + "\t";
                }
                TextBoxForFeedback.AppendText(NewLine + "\n\n");

                for (int j = 0; j < ConfusionMatrix.Length; j++)
                {
                    NewLine = "";
                    for (int i = 0; i < ConfusionMatrix[0].Length; i++)
                    {
                        NewLine += ConfusionMatrix[j][i] + "\t";
                    }
                    // if
                    TextBoxForFeedback.AppendText(NewLine + "| c" + j + " <=> " + cGlobalInfo.ListCellularPhenotypes[j].Name + "\n");
                }
            }
            #endregion

            return this.CurrentClassifier;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Evalute and display a WEKA clusterer
        /// </summary>
        /// <param name="SelectedClusterer">weka clusterer</param>
        /// <param name="InstancesList">list of instances for the validation</param>
        /// <param name="RichTextBoxToDisplayResults">Text box for the results (can be NULL)</param>
        /// <param name="PanelTodisplayGraphicalResults">Panel to display visual results if avalaible (can be NULL)</param>
        /// <returns></returns>
        public ClusterEvaluation EvaluteAndDisplayClusterer(RichTextBox RichTextBoxToDisplayResults,
                                                            Panel PanelTodisplayGraphicalResults, Instances ListInstanceForValid)
        {
            ClusterEvaluation eval = new ClusterEvaluation();
            eval.setClusterer(SelectedClusterer);
            eval.evaluateClusterer(ListInstanceForValid);

            if (RichTextBoxToDisplayResults != null)
            {

                if ((RichTextBoxToDisplayResults != null) && (eval.getNumClusters() > cGlobalInfo.ListCellularPhenotypes.Count))
                {
                    RichTextBoxToDisplayResults.Clear();
                    RichTextBoxToDisplayResults.AppendText("Error: " + eval.getNumClusters() + " clusters identifed.");
                    RichTextBoxToDisplayResults.AppendText("The maximum number of cluster is " + cGlobalInfo.ListCellularPhenotypes.Count + ".");
                    return null;

                }
                if (RichTextBoxToDisplayResults != null)
                {
                    RichTextBoxToDisplayResults.Clear();
                    RichTextBoxToDisplayResults.AppendText(eval.clusterResultsToString());
                }

                RichTextBoxToDisplayResults.AppendText("\n" + ListInstanceForValid.numAttributes() + " attributes:\n\n");
                for (int IdxAttributes = 0; IdxAttributes < ListInstanceForValid.numAttributes(); IdxAttributes++)
                {
                    RichTextBoxToDisplayResults.AppendText(IdxAttributes + "\t: " + ListInstanceForValid.attribute(IdxAttributes).name() + "\n");
                }
            }

            if (PanelTodisplayGraphicalResults != null) PanelTodisplayGraphicalResults.Controls.Clear();

            if ((PanelTodisplayGraphicalResults != null) && (SelectedClusterer.GetType().Name == "HierarchicalClusterer"))
            {
                Button ButtonToDisplayHierarchicalClustering = new Button();
                ButtonToDisplayHierarchicalClustering.Text = "Display Hierarchical Tree";
                ButtonToDisplayHierarchicalClustering.Width *= 2;
                ButtonToDisplayHierarchicalClustering.Location = new System.Drawing.Point((PanelTodisplayGraphicalResults.Width - ButtonToDisplayHierarchicalClustering.Width) / 2,
                    (PanelTodisplayGraphicalResults.Height - ButtonToDisplayHierarchicalClustering.Height) / 2);

                ButtonToDisplayHierarchicalClustering.Anchor = AnchorStyles.None;
                ButtonToDisplayHierarchicalClustering.Click += new EventHandler(ClickToDisplayHierarchicalTree);
                PanelTodisplayGraphicalResults.Controls.Add(ButtonToDisplayHierarchicalClustering);
            }

            return eval;
        }
Ejemplo n.º 13
0
        // ---- OPERATIONS ----
        ///    
        ///     <summary> * Sets the format of the input instances. If the filter is able to
        ///     * determine the output format before seeing any input instances, it
        ///     * does so here. This default implementation clears the output format
        ///     * and output queue, and the new batch flag is set. Overriders should
        ///     * call <code>super.setInputFormat(Instances)</code>
        ///     * </summary>
        ///     * <param name="instanceInfo"> an Instances object containing the input instance
        ///     * structure (any instances contained in the object are ignored - only the
        ///     * structure is required). </param>
        ///     * <returns> true if the outputFormat may be collected immediately </returns>
        ///     * <exception cref="Exception"> if the inputFormat can't be set successfully  </exception>
        ///     
        //JAVA TO VB & C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        //ORIGINAL LINE: public boolean setInputFormat(Instances instanceInfo) throws Exception
        public override bool setInputFormat(Instances instanceInfo)
        {
            base.setInputFormat(instanceInfo);

            for (int i = 0; i < instanceInfo.numAttributes(); ++i)
            {
                if (!instanceInfo.attribute(i).isNumeric())
                {
                    throw new UnsupportedAttributeTypeException("All attributes must be numeric");
                }
            }

            // Create the output buffer
            setOutputFormat();
            return true;
        }
Ejemplo n.º 14
0
		/// <summary> Checks if two headers are equivalent.
		/// 
		/// </summary>
		/// <param name="dataset">another dataset
		/// </param>
		/// <returns> true if the header of the given dataset is equivalent 
		/// to this header
		/// </returns>
		public virtual bool equalHeaders(Instances dataset)
		{
			
			// Check class and all attributes
			if (m_ClassIndex != dataset.m_ClassIndex)
			{
				return false;
			}
			if (m_Attributes.size() != dataset.m_Attributes.size())
			{
				return false;
			}
			for (int i = 0; i < m_Attributes.size(); i++)
			{
				if (!(attribute(i).Equals(dataset.attribute(i))))
				{
					return false;
				}
			}
			return true;
		}
Ejemplo n.º 15
0
		/// <summary> Merges two sets of Instances together. The resulting set will have
		/// all the attributes of the first set plus all the attributes of the 
		/// second set. The number of instances in both sets must be the same.
		/// 
		/// </summary>
		/// <param name="first">the first set of Instances
		/// </param>
		/// <param name="second">the second set of Instances
		/// </param>
		/// <returns> the merged set of Instances
		/// </returns>
		/// <exception cref="IllegalArgumentException">if the datasets are not the same size
		/// </exception>
		public static Instances mergeInstances(Instances first, Instances second)
		{
			
			if (first.numInstances() != second.numInstances())
			{
				throw new System.ArgumentException("Instance sets must be of the same size");
			}
			
			// Create the vector of merged attributes
			FastVector newAttributes = new FastVector();
			for (int i = 0; i < first.numAttributes(); i++)
			{
				newAttributes.addElement(first.attribute(i));
			}
			for (int i = 0; i < second.numAttributes(); i++)
			{
				newAttributes.addElement(second.attribute(i));
			}
			
			// Create the set of Instances
			Instances merged = new Instances(first.relationName() + '_' + second.relationName(), newAttributes, first.numInstances());
			// Merge each instance
			for (int i = 0; i < first.numInstances(); i++)
			{
				merged.add(first.instance(i).mergeInstance(second.instance(i)));
			}
			return merged;
		}
Ejemplo n.º 16
0
		/// <summary> Prints the condition satisfied by instances in a subset.
		/// 
		/// </summary>
		/// <param name="index">of subset 
		/// </param>
		/// <param name="data">training set.
		/// </param>
		public override System.String rightSide(int index, Instances data)
		{
			
			System.Text.StringBuilder text;
			
			text = new System.Text.StringBuilder();
			if (data.attribute(m_attIndex).Nominal)
				text.Append(" = " + data.attribute(m_attIndex).value_Renamed(index));
			else if (index == 0)
				text.Append(" <= " + Utils.doubleToString(m_splitPoint, 6));
			else
				text.Append(" > " + Utils.doubleToString(m_splitPoint, 6));
			return text.ToString();
		}
Ejemplo n.º 17
0
		/// <summary> Returns a string containing java source code equivalent to the test
		/// made at this node. The instance being tested is called "i".
		/// 
		/// </summary>
		/// <param name="index">index of the nominal value tested
		/// </param>
		/// <param name="data">the data containing instance structure info
		/// </param>
		/// <returns> a value of type 'String'
		/// </returns>
		public override System.String sourceExpression(int index, Instances data)
		{
			
			System.Text.StringBuilder expr = null;
			if (index < 0)
			{
				return "i[" + m_attIndex + "] == null";
			}
			if (data.attribute(m_attIndex).Nominal)
			{
				expr = new System.Text.StringBuilder("i[");
				expr.Append(m_attIndex).Append("]");
				expr.Append(".equals(\"").Append(data.attribute(m_attIndex).value_Renamed(index)).Append("\")");
			}
			else
			{
				expr = new System.Text.StringBuilder("((Double) i[");
				expr.Append(m_attIndex).Append("])");
				if (index == 0)
				{
					expr.Append(".doubleValue() <= ").Append(m_splitPoint);
				}
				else
				{
					expr.Append(".doubleValue() > ").Append(m_splitPoint);
				}
			}
			return expr.ToString();
		}
        private void Browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.ShowDialog();
            file        = ofd.SafeFileName;
            label2.Text = "Wait process in progress";

            weka.core.Instances insts = new weka.core.Instances(new java.io.FileReader(file));
            double max_value          = J48classifyTest(insts);

            model = J48cl;
            string name = "J48cl";


            double NBvalue = NaiveBayesTest(insts);

            if (NBvalue > max_value)
            {
                max_value = NBvalue;
                model     = NaiveBayescl;
                name      = "NaiveBayes";
            }
            double RFvalue = RandomForestTest(insts);

            if (RFvalue > max_value)
            {
                max_value = RFvalue;
                model     = RandomForestcl;
                name      = "RandomForest";
            }
            double RTvalue = RandomTreeTest(insts);

            if (RTvalue > max_value)
            {
                max_value = RTvalue;
                model     = RandomTreecl;
                name      = "RandomTree";
            }
            double _5IBKvalue = _5IBkTest(insts);

            if (_5IBKvalue > max_value)
            {
                max_value = _5IBKvalue;
                model     = _5IBKcl;
                name      = " _5IBK";
            }
            double _7IBKvalue = _7IBkTest(insts);

            if (_7IBKvalue > max_value)
            {
                max_value = _7IBKvalue;
                model     = _7IBKcl;
                name      = " _7IBk";
            }
            double _9IBKvalue = _9IBkTest(insts);

            if (_9IBKvalue > max_value)
            {
                max_value = _9IBKvalue;
                model     = _9IBKcl;
                name      = " _9IBk";
            }
            double LogRegressionvalue = LogRegressionTest(insts);

            if (LogRegressionvalue > max_value)
            {
                max_value = LogRegressionvalue;
                model     = LogRegressioncl;
                name      = "LogRegression";
            }
            double SVM = SupportVectorMachineTest(insts);

            if (SVM > max_value)
            {
                max_value = SVM;
                model     = SupportVectorMachine;
                name      = "SupportVectorMachine";
            }
            double ArtNN = ArtNeuralNetworkTest(insts);

            if (ArtNN > max_value)
            {
                max_value = ArtNN;
                model     = ArtNeuralNetwork;
                name      = "ArtNeuralNetwork";
            }

            label2.Text = name + " is the most successful algorithm for this data set " + "(%" + Math.Round(max_value, 2) + ")";

            for (int i = 0; i < insts.numAttributes() - 1; i++)
            {
                if (insts.attribute(i).isNominal())
                {
                    Label l = new Label();
                    flowLayoutPanel2.Controls.Add(l);

                    l.Top  = i * 30 + 175;
                    l.Left = 100;
                    l.Text = insts.attribute(i).name().ToString() + ": ";


                    ComboBox mybox = new ComboBox();
                    for (int j = 0; j < insts.attribute(i).numValues(); j++)
                    {
                        mybox.Items.Add(insts.attribute(i).value(j));
                    }
                    // Creating and setting the properties of comboBox

                    mybox.DropDownStyle = ComboBoxStyle.DropDownList;
                    mybox.Size          = new Size(100, 30);
                    mybox.Top           = i * 30 + 175;
                    l.Left    = 200;
                    mybox.Tag = i;
                    flowLayoutPanel2.Controls.Add(mybox);
                    list.Add(mybox);
                }
                else
                {
                    Label l = new Label();
                    flowLayoutPanel2.Controls.Add(l);

                    l.Text = insts.attribute(i).name().ToString() + ": ";
                    TextBox txt = new TextBox();
                    txt.Tag = i;
                    list.Add(txt);
                    flowLayoutPanel2.Controls.Add(txt);
                }
            }

            Button button = new Button();

            button.Name      = "Discover";
            button.Text      = "Find";
            button.Location  = new Point(468, 72);
            button.Size      = new Size(60, 30);
            button.BackColor = Color.Red;
            button.Font      = new Font(button.Font.Name, button.Font.Size, FontStyle.Bold);
            button.Click    += new EventHandler(button1_Click);

            Controls.Add(button);
        }
Ejemplo n.º 19
0
 private LabelsMetaData loadLabelsMeta(Instances data, int numLabels)
 {
     LabelsMetaDataImpl labelsData = new LabelsMetaDataImpl();
     int numAttributes = data.numAttributes();
     for (int index = numAttributes - numLabels; index < numAttributes; index++) {
         String attrName = data.attribute(index).name();
         labelsData.addRootNode(new LabelNodeImpl(attrName));
     }
     return labelsData;
 }
Ejemplo n.º 20
0
		/// <summary> Creates split on enumerated attribute.
		/// 
		/// </summary>
		/// <exception cref="Exception">if something goes wrong
		/// </exception>
		private void  handleEnumeratedAttribute(Instances trainInstances)
		{
			
			Distribution newDistribution, secondDistribution;
			int numAttValues;
			double currIG, currGR;
			Instance instance;
			int i;
			
			numAttValues = trainInstances.attribute(m_attIndex).numValues();
			newDistribution = new Distribution(numAttValues, trainInstances.numClasses());
			
			// Only Instances with known values are relevant.
			System.Collections.IEnumerator enu = trainInstances.enumerateInstances();
			//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
			while (enu.MoveNext())
			{
				//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
				instance = (Instance) enu.Current;
				if (!instance.isMissing(m_attIndex))
				{
					//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
					newDistribution.add((int) instance.value_Renamed(m_attIndex), instance);
				}
			}
			m_distribution = newDistribution;
			
			// For all values
			for (i = 0; i < numAttValues; i++)
			{
				
				if (Utils.grOrEq(newDistribution.perBag(i), m_minNoObj))
				{
					secondDistribution = new Distribution(newDistribution, i);
					
					// Check if minimum number of Instances in the two
					// subsets.
					if (secondDistribution.check(m_minNoObj))
					{
						m_numSubsets = 2;
						currIG = m_infoGainCrit.splitCritValue(secondDistribution, m_sumOfWeights);
						currGR = m_gainRatioCrit.splitCritValue(secondDistribution, m_sumOfWeights, currIG);
						if ((i == 0) || Utils.gr(currGR, m_gainRatio))
						{
							m_gainRatio = currGR;
							m_infoGain = currIG;
							m_splitPoint = (double) i;
							m_distribution = secondDistribution;
						}
					}
				}
			}
		}
Ejemplo n.º 21
0
		/// <summary> Selects C4.5-type split for the given dataset.</summary>
		public override ClassifierSplitModel selectModel(Instances data)
		{
			
			double minResult;
			//double currentResult;
			BinC45Split[] currentModel;
			BinC45Split bestModel = null;
			NoSplit noSplitModel = null;
			double averageInfoGain = 0;
			int validModels = 0;
			bool multiVal = true;
			Distribution checkDistribution;
			double sumOfWeights;
			int i;
			
			try
			{
				
				// Check if all Instances belong to one class or if not
				// enough Instances to split.
				checkDistribution = new Distribution(data);
				noSplitModel = new NoSplit(checkDistribution);
				if (Utils.sm(checkDistribution.total(), 2 * m_minNoObj) || Utils.eq(checkDistribution.total(), checkDistribution.perClass(checkDistribution.maxClass())))
					return noSplitModel;
				
				// Check if all attributes are nominal and have a 
				// lot of values.
				System.Collections.IEnumerator enu = data.enumerateAttributes();
				//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
				while (enu.MoveNext())
				{
					//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                    weka.core.Attribute attribute = (weka.core.Attribute)enu.Current;
					if ((attribute.Numeric) || (Utils.sm((double) attribute.numValues(), (0.3 * (double) m_allData.numInstances()))))
					{
						multiVal = false;
						break;
					}
				}
				currentModel = new BinC45Split[data.numAttributes()];
				sumOfWeights = data.sumOfWeights();
				
				// For each attribute.
				for (i = 0; i < data.numAttributes(); i++)
				{
					
					// Apart from class attribute.
					if (i != (data).classIndex())
					{
						
						// Get models for current attribute.
						currentModel[i] = new BinC45Split(i, m_minNoObj, sumOfWeights);
						currentModel[i].buildClassifier(data);
						
						// Check if useful split for current attribute
						// exists and check for enumerated attributes with 
						// a lot of values.
						if (currentModel[i].checkModel())
							if ((data.attribute(i).Numeric) || (multiVal || Utils.sm((double) data.attribute(i).numValues(), (0.3 * (double) m_allData.numInstances()))))
							{
								averageInfoGain = averageInfoGain + currentModel[i].infoGain();
								validModels++;
							}
					}
					else
						currentModel[i] = null;
				}
				
				// Check if any useful split was found.
				if (validModels == 0)
					return noSplitModel;
				averageInfoGain = averageInfoGain / (double) validModels;
				
				// Find "best" attribute to split on.
				minResult = 0;
				for (i = 0; i < data.numAttributes(); i++)
				{
					if ((i != (data).classIndex()) && (currentModel[i].checkModel()))
					// Use 1E-3 here to get a closer approximation to the original
					// implementation.
						if ((currentModel[i].infoGain() >= (averageInfoGain - 1e-3)) && Utils.gr(currentModel[i].gainRatio(), minResult))
						{
							bestModel = currentModel[i];
							minResult = currentModel[i].gainRatio();
						}
				}
				
				// Check if useful split was found.
				if (Utils.eq(minResult, 0))
					return noSplitModel;
				
				// Add all Instances with unknown values for the corresponding
				// attribute to the distribution for the model, so that
				// the complete distribution is stored with the model. 
				bestModel.distribution().addInstWithUnknown(data, bestModel.attIndex());
				
				// Set the split point analogue to C45 if attribute numeric.
				bestModel.SplitPoint = m_allData;
				return bestModel;
			}
			catch (System.Exception e)
			{
                System.Console.WriteLine(e.StackTrace + " " + e.Message);
			}
			return null;
		}
Ejemplo n.º 22
0
		/// <summary> Generates the classifier.
		/// 
		/// </summary>
		/// <param name="instances">set of instances serving as training data 
		/// </param>
		/// <exception cref="Exception">if the classifier has not been generated successfully
		/// </exception>
		public override void  buildClassifier(Instances instances)
		{
			//UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
			double bestVal = System.Double.MaxValue, currVal;
			//UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
			double bestPoint = - System.Double.MaxValue, sum;
			int bestAtt = - 1, numClasses;
			
			if (instances.checkForStringAttributes())
			{
				throw new Exception("Can't handle string attributes!");
			}
			
			double[][] bestDist = new double[3][];
			for (int i = 0; i < 3; i++)
			{
				bestDist[i] = new double[instances.numClasses()];
			}
			
			m_Instances = new Instances(instances);
			m_Instances.deleteWithMissingClass();
			
			if (m_Instances.numInstances() == 0)
			{
				throw new System.ArgumentException("No instances without missing " + "class values in training file!");
			}
			
			if (instances.numAttributes() == 1)
			{
				throw new System.ArgumentException("Attribute missing. Need at least one " + "attribute other than class attribute!");
			}
			
			if (m_Instances.classAttribute().Nominal)
			{
				numClasses = m_Instances.numClasses();
			}
			else
			{
				numClasses = 1;
			}
			
			// For each attribute
			bool first = true;
			for (int i = 0; i < m_Instances.numAttributes(); i++)
			{
				if (i != m_Instances.classIndex())
				{
					
					// Reserve space for distribution.
					double[][] tmpArray = new double[3][];
					for (int i2 = 0; i2 < 3; i2++)
					{
						tmpArray[i2] = new double[numClasses];
					}
					m_Distribution = tmpArray;
					
					// Compute value of criterion for best split on attribute
					if (m_Instances.attribute(i).Nominal)
					{
						currVal = findSplitNominal(i);
					}
					else
					{
						currVal = findSplitNumeric(i);
					}
					if ((first) || (currVal < bestVal))
					{
						bestVal = currVal;
						bestAtt = i;
						bestPoint = m_SplitPoint;
						for (int j = 0; j < 3; j++)
						{
							Array.Copy(m_Distribution[j], 0, bestDist[j], 0, numClasses);
						}
					}
					
					// First attribute has been investigated
					first = false;
				}
			}
			
			// Set attribute, split point and distribution.
			m_AttIndex = bestAtt;
			m_SplitPoint = bestPoint;
			m_Distribution = bestDist;
			if (m_Instances.classAttribute().Nominal)
			{
				for (int i = 0; i < m_Distribution.Length; i++)
				{
					double sumCounts = Utils.sum(m_Distribution[i]);
					if (sumCounts == 0)
					{
						// This means there were only missing attribute values
						Array.Copy(m_Distribution[2], 0, m_Distribution[i], 0, m_Distribution[2].Length);
						Utils.normalize(m_Distribution[i]);
					}
					else
					{
						Utils.normalize(m_Distribution[i], sumCounts);
					}
				}
			}
			
			// Save memory
			m_Instances = new Instances(m_Instances, 0);
		}