예제 #1
0
        /// <summary>
        /// Calculate the value N, which is the number of cases, from the training data, where the
        /// desiredValue matches the training data.  Only cases where the parents match the specifed
        /// parent instance are considered.
        /// </summary>
        /// <param name="network">The network to calculate for.</param>
        /// <param name="e">The event we are calculating for. (variable i)</param>
        /// <param name="parents">The parents of the specified event we are considering.</param>
        /// <param name="parentInstance">The parent instance we are looking for.</param>
        /// <returns>The value N. </returns>
        public int CalculateN(BayesianNetwork network, BayesianEvent e,
                              IList <BayesianEvent> parents, int[] parentInstance)
        {
            int result = 0;

            foreach (IMLDataPair pair in _data)
            {
                int[] d = _network.DetermineClasses(pair.Input);

                bool reject = false;

                for (int i = 0; i < parentInstance.Length; i++)
                {
                    BayesianEvent parentEvent = parents[i];
                    int           parentIndex = network.GetEventIndex(parentEvent);
                    if (parentInstance[i] != (d[parentIndex]))
                    {
                        reject = true;
                        break;
                    }
                }

                if (!reject)
                {
                    result++;
                }
            }
            return(result);
        }
        public void Execute(IExampleInterface app)
        {
            // Create a Bayesian network
            BayesianNetwork network = new BayesianNetwork();
            // Create the Uber driver event
            BayesianEvent UberDriver = network.CreateEvent("uber_driver");
            // create the witness event
            BayesianEvent WitnessSawUberDriver = network.CreateEvent("saw_uber_driver");

            // Attach the two
            network.CreateDependency(UberDriver, WitnessSawUberDriver);
            network.FinalizeStructure();

            // build the truth tables
            UberDriver?.Table?.AddLine(0.85, true);
            WitnessSawUberDriver?.Table?.AddLine(0.80, true, true);
            WitnessSawUberDriver?.Table?.AddLine(0.20, true, false);
            network.Validate();

            Console.WriteLine(network.ToString());
            Console.WriteLine($"Parameter count: {network.CalculateParameterCount()}");

            EnumerationQuery query = new EnumerationQuery(network);

            // The evidence is that someone saw the Uber driver hit the car
            query.DefineEventType(WitnessSawUberDriver, EventType.Evidence);
            // The result was the Uber driver did it
            query.DefineEventType(UberDriver, EventType.Outcome);
            query.SetEventValue(WitnessSawUberDriver, false);
            query.SetEventValue(UberDriver, false);
            query.Execute();
            Console.WriteLine(query.ToString());
        }
예제 #3
0
        public void TestK2Structure()
        {
            String[] labels = { "available", "not" };

            IMLDataSet      data    = new BasicMLDataSet(DATA, null);
            BayesianNetwork network = new BayesianNetwork();
            BayesianEvent   x1      = network.CreateEvent("x1", labels);
            BayesianEvent   x2      = network.CreateEvent("x2", labels);
            BayesianEvent   x3      = network.CreateEvent("x3", labels);

            network.FinalizeStructure();
            TrainBayesian train = new TrainBayesian(network, data, 10);

            train.InitNetwork = BayesianInit.InitEmpty;
            while (!train.TrainingDone)
            {
                train.Iteration();
            }
            train.Iteration();
            Assert.IsTrue(x1.Parents.Count == 0);
            Assert.IsTrue(x2.Parents.Count == 1);
            Assert.IsTrue(x3.Parents.Count == 1);
            Assert.IsTrue(x2.Parents.Contains(x1));
            Assert.IsTrue(x3.Parents.Contains(x2));
            Assert.AreEqual(0.714, network.GetEvent("x2").Table.FindLine(1, new int[] { 1 }).Probability, 0.001);
        }
예제 #4
0
        /// <inheritdoc/>
        public bool Iteration()
        {
            if (_index == -1)
            {
                OrderNodes();
            }
            else
            {
                BayesianEvent e    = _nodeOrdering[_index];
                double        oldP = CalculateG(_network, e, e.Parents);

                while (e.Parents.Count < _train.MaximumParents)
                {
                    BayesianEvent z = FindZ(e, _index, oldP);
                    if (z != null)
                    {
                        _network.CreateDependency(z, e);
                        oldP = _lastCalculatedP;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            _index++;
            return(_index < _data.InputSize);
        }
예제 #5
0
        /// <summary>
        /// Calculate G.
        /// </summary>
        /// <param name="network">The network to calculate for.</param>
        /// <param name="e">The event to calculate for.</param>
        /// <param name="parents">The parents.</param>
        /// <returns>The value for G.</returns>
        public double CalculateG(BayesianNetwork network,
                                 BayesianEvent e, IList <BayesianEvent> parents)
        {
            double result = 1.0;
            int    r      = e.Choices.Count;

            var args = new int[parents.Count];

            do
            {
                double n = EncogMath.Factorial(r - 1);
                double d = EncogMath.Factorial(CalculateN(network, e,
                                                          parents, args) + r - 1);
                double p1 = n / d;

                double p2 = 1;
                for (int k = 0; k < e.Choices.Count; k++)
                {
                    p2 *= EncogMath.Factorial(CalculateN(network, e, parents, args, k));
                }

                result *= p1 * p2;
            } while (EnumerationQuery.Roll(parents, args));

            return(result);
        }
예제 #6
0
        public void TestEnumeration2()
        {
            BayesianNetwork network = new BayesianNetwork();
            BayesianEvent   a       = network.CreateEvent("a");
            BayesianEvent   x1      = network.CreateEvent("x1");
            BayesianEvent   x2      = network.CreateEvent("x2");
            BayesianEvent   x3      = network.CreateEvent("x3");

            network.CreateDependency(a, x1, x2, x3);
            network.FinalizeStructure();

            a.Table.AddLine(0.5, true);         // P(A) = 0.5
            x1.Table.AddLine(0.2, true, true);  // p(x1|a) = 0.2
            x1.Table.AddLine(0.6, true, false); // p(x1|~a) = 0.6
            x2.Table.AddLine(0.2, true, true);  // p(x2|a) = 0.2
            x2.Table.AddLine(0.6, true, false); // p(x2|~a) = 0.6
            x3.Table.AddLine(0.2, true, true);  // p(x3|a) = 0.2
            x3.Table.AddLine(0.6, true, false); // p(x3|~a) = 0.6
            network.Validate();

            EnumerationQuery query = new EnumerationQuery(network);

            query.DefineEventType(x1, EventType.Evidence);
            query.DefineEventType(x2, EventType.Evidence);
            query.DefineEventType(x3, EventType.Evidence);
            query.DefineEventType(a, EventType.Outcome);
            query.SetEventValue(a, true);
            query.SetEventValue(x1, true);
            query.SetEventValue(x2, true);
            query.SetEventValue(x3, false);
            query.Execute();
            TestPercent(query.Probability, 18);
        }
예제 #7
0
        /// <summary>
        /// Calculate G. 
        /// </summary>
        /// <param name="network">The network to calculate for.</param>
        /// <param name="e">The event to calculate for.</param>
        /// <param name="parents">The parents.</param>
        /// <returns>The value for G.</returns>
        public double CalculateG(BayesianNetwork network,
                                 BayesianEvent e, IList<BayesianEvent> parents)
        {
            double result = 1.0;
            int r = e.Choices.Count;

            var args = new int[parents.Count];

            do
            {
                double n = EncogMath.Factorial(r - 1);
                double d = EncogMath.Factorial(CalculateN(network, e,
                                                          parents, args) + r - 1);
                double p1 = n/d;

                double p2 = 1;
                for (int k = 0; k < e.Choices.Count; k++)
                {
                    p2 *= EncogMath.Factorial(CalculateN(network, e, parents, args, k));
                }

                result *= p1*p2;
            } while (EnumerationQuery.Roll(parents, args));

            return result;
        }
        public void Execute(IExampleInterface app)
        {
            // build the bayesian network structure
            BayesianNetwork network        = new BayesianNetwork();
            BayesianEvent   BlueTaxi       = network.CreateEvent("blue_taxi");
            BayesianEvent   WitnessSawBlue = network.CreateEvent("saw_blue");

            network.CreateDependency(BlueTaxi, WitnessSawBlue);
            network.FinalizeStructure();
            // build the truth tales
            BlueTaxi.Table.AddLine(0.85, true);
            WitnessSawBlue.Table.AddLine(0.80, true, true);
            WitnessSawBlue.Table.AddLine(0.20, true, false);

            // validate the network
            network.Validate();
            // display basic stats
            Console.WriteLine(network.ToString());
            Console.WriteLine("Parameter count: " + network.CalculateParameterCount());
            EnumerationQuery query = new EnumerationQuery(network);

            //SamplingQuery query = new SamplingQuery(network);
            query.DefineEventType(WitnessSawBlue, EventType.Evidence);
            query.DefineEventType(BlueTaxi, EventType.Outcome);
            query.SetEventValue(WitnessSawBlue, false);
            query.SetEventValue(BlueTaxi, false);
            query.Execute();
            Console.WriteLine(query.ToString());
        }
예제 #9
0
        /// <summary>
        /// Find the value for z.
        /// </summary>
        /// <param name="e">The event that we are clauclating for.</param>
        /// <param name="n">The value for n.</param>
        /// <param name="old">The old value.</param>
        /// <returns>The new value for z.</returns>
        private BayesianEvent FindZ(BayesianEvent e, int n, double old)
        {
            BayesianEvent result    = null;
            double        maxChildP = double.NegativeInfinity;

            //System.out.println("Finding parent for: " + event.toString());
            for (int i = 0; i < n; i++)
            {
                BayesianEvent         trialParent = _nodeOrdering[i];
                IList <BayesianEvent> parents     = new List <BayesianEvent>();
                parents.CopyTo(e.Parents.ToArray(), 0);
                parents.Add(trialParent);
                //System.out.println("Calculating adding " + trialParent.toString() + " to " + event.toString());
                _lastCalculatedP = CalculateG(_network, e, parents);
                //System.out.println("lastP:" + this.lastCalculatedP);
                //System.out.println("old:" + old);
                if (_lastCalculatedP > old && _lastCalculatedP > maxChildP)
                {
                    result    = trialParent;
                    maxChildP = _lastCalculatedP;
                    //System.out.println("Current best is: " + result.toString());
                }
            }

            _lastCalculatedP = maxChildP;
            return(result);
        }
예제 #10
0
 /// <inheritdoc/>
 public EventState GetEventState(BayesianEvent theEvent)
 {
     if (!_events.ContainsKey(theEvent))
     {
         return(null);
     }
     return(_events[theEvent]);
 }
예제 #11
0
        /// <summary>
        /// Define the truth table.
        /// </summary>
        /// <param name="network">The bayesian network.</param>
        /// <param name="result">The resulting probability.</param>
        public void DefineTruthTable(BayesianNetwork network, double result)
        {
            ParsedEvent   childParsed = ChildEvent;
            BayesianEvent childEvent  = network.RequireEvent(childParsed.Label);

            // define truth table line
            int[] args = GetArgs(network);
            childEvent.Table.AddLine(result, childParsed.ResolveValue(childEvent), args);
        }
예제 #12
0
        /// <inheritdoc/>
        public void SetEventValue(BayesianEvent theEvent, int d)
        {
            if (GetEventType(theEvent) == EventType.Hidden)
            {
                throw new BayesianError("You may only set the value of an evidence or outcome event.");
            }

            GetEventState(theEvent).CompareValue = d;
            GetEventState(theEvent).Value        = d;
        }
예제 #13
0
        /// <summary>
        /// Define the relationships.
        /// </summary>
        /// <param name="network">The network.</param>
        public void DefineRelationships(BayesianNetwork network)
        {
            // define event relations, if they are not there already
            ParsedEvent   childParsed = ChildEvent;
            BayesianEvent childEvent  = network.RequireEvent(childParsed.Label);

            foreach (ParsedEvent e in this.givenEvents)
            {
                BayesianEvent parentEvent = network.RequireEvent(e.Label);
                network.CreateDependency(parentEvent, childEvent);
            }
        }
예제 #14
0
        /// <inheritdoc/>
        public bool Iteration()
        {
            BayesianEvent e = _network.Events[_index];

            foreach (TableLine line in e.Table.Lines)
            {
                line.Probability = (CalculateProbability(e, line.Result, line.Arguments));
            }
            _index++;

            return(_index < _network.Events.Count);
        }
예제 #15
0
        /// <summary>
        /// Get the arguments to this event.
        /// </summary>
        /// <param name="network">The network.</param>
        /// <returns>The arguments.</returns>
        public int[] GetArgs(BayesianNetwork network)
        {
            int[] result = new int[givenEvents.Count];

            for (int i = 0; i < givenEvents.Count; i++)
            {
                ParsedEvent   givenEvent  = this.givenEvents[i];
                BayesianEvent actualEvent = network.GetEvent(givenEvent.Label);
                result[i] = givenEvent.ResolveValue(actualEvent);
            }

            return(result);
        }
예제 #16
0
        /// <summary>
        /// Obtain the arguments for an event.
        /// </summary>
        /// <param name="theEvent">The event.</param>
        /// <returns>The arguments.</returns>
        private int[] ObtainArgs(BayesianEvent theEvent)
        {
            var result = new int[theEvent.Parents.Count];

            int index = 0;

            foreach (BayesianEvent parentEvent in theEvent.Parents)
            {
                EventState state = GetEventState(parentEvent);
                result[index++] = state.Value;
            }
            return(result);
        }
예제 #17
0
        public BayesianNetwork Create()
        {
            BayesianNetwork network = new BayesianNetwork();
            BayesianEvent   a       = network.CreateEvent("a");
            BayesianEvent   b       = network.CreateEvent("b");

            network.CreateDependency(a, b);
            network.FinalizeStructure();
            a.Table.AddLine(0.5, true);        // P(A) = 0.5
            b.Table.AddLine(0.2, true, true);  // p(b|a) = 0.2
            b.Table.AddLine(0.8, true, false); // p(b|~a) = 0.8
            network.Validate();
            return(network);
        }
예제 #18
0
        /// <summary>
        /// Calculate the probability.
        /// </summary>
        /// <param name="e">The event.</param>
        /// <param name="result">The result.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The probability.</returns>
        public double CalculateProbability(BayesianEvent e, int result, int[] args)
        {
            int eventIndex = _network.Events.IndexOf(e);
            int x          = 0;
            int y          = 0;

            // calculate overall probability
            foreach (IMLDataPair pair in _data)
            {
                int[] d = _network.DetermineClasses(pair.Input);

                if (args.Length == 0)
                {
                    x++;
                    if (d[eventIndex] == result)
                    {
                        y++;
                    }
                }
                else if (d[eventIndex] == result)
                {
                    x++;

                    int  i          = 0;
                    bool givenMatch = true;
                    foreach (BayesianEvent givenEvent in e.Parents)
                    {
                        int givenIndex = _network.GetEventIndex(givenEvent);
                        if (args[i] != d[givenIndex])
                        {
                            givenMatch = false;
                            break;
                        }
                        i++;
                    }

                    if (givenMatch)
                    {
                        y++;
                    }
                }
            }

            double num = y + 1;
            double den = x + e.Choices.Count;


            return(num / den);
        }
        /// <summary>
        /// Calculate the probability.
        /// </summary>
        /// <param name="e">The event.</param>
        /// <param name="result">The result.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The probability.</returns>
        public double CalculateProbability(BayesianEvent e, int result, int[] args)
        {
            int eventIndex = _network.Events.IndexOf(e);
            int x = 0;
            int y = 0;

            // calculate overall probability
            foreach (IMLDataPair pair in _data)
            {
                int[] d = _network.DetermineClasses(pair.Input);

                if (args.Length == 0)
                {
                    x++;
                    if (d[eventIndex] == result)
                    {
                        y++;
                    }
                }
                else if (d[eventIndex] == result)
                {
                    x++;

                    int i = 0;
                    bool givenMatch = true;
                    foreach (BayesianEvent givenEvent in e.Parents)
                    {
                        int givenIndex = _network.GetEventIndex(givenEvent);
                        if (args[i] != d[givenIndex])
                        {
                            givenMatch = false;
                            break;
                        }
                        i++;
                    }

                    if (givenMatch)
                    {
                        y++;
                    }
                }
            }

            double num = y + 1;
            double den = x + e.Choices.Count;


            return num/den;
        }
예제 #20
0
        public void TestCount()
        {
            BayesianNetwork network = new BayesianNetwork();
            BayesianEvent   a       = network.CreateEvent("a");
            BayesianEvent   b       = network.CreateEvent("b");
            BayesianEvent   c       = network.CreateEvent("c");
            BayesianEvent   d       = network.CreateEvent("d");
            BayesianEvent   e       = network.CreateEvent("e");

            network.CreateDependency(a, b, d, e);
            network.CreateDependency(c, d);
            network.CreateDependency(b, e);
            network.CreateDependency(d, e);
            network.FinalizeStructure();
            Assert.AreEqual(16, network.CalculateParameterCount());
        }
예제 #21
0
        static void Main(string[] args)
        {
            /*Przykład 4.2.3 Teoria Bayesa - Zakłady Produkcyjne Etap Manualny
             * Lesson 1 - Machine Learning in C# for Amazon ML Group created by me :-)
             * PS. Kill me I use polish :-)
             */

            BayesianNetwork network        = new BayesianNetwork();
            BayesianEvent   WadliwyElement = network.CreateEvent("wadliwy_element");
            BayesianEvent   A1             = network.CreateEvent("wadliwy_element_zaklad_A1");
            BayesianEvent   A2             = network.CreateEvent("wadliwy_element_zaklad_A2");
            BayesianEvent   A3             = network.CreateEvent("wadliwy_element_zaklad_A3");
            BayesianEvent   A4             = network.CreateEvent("wadliwy_element_zaklad_A4");

            network.CreateDependency(WadliwyElement, A1, A2, A3, A4);
            network.FinalizeStructure();

            WadliwyElement?.Table?.AddLine(0.1083, true);
            A1?.Table.AddLine(0.069, true, true);
            A1?.Table.AddLine(1 - 0.069, true, false);
            A2?.Table.AddLine(0.277, true, true);
            A2?.Table.AddLine(1 - 0.277, true, false);
            A3?.Table.AddLine(0.007, true, true);
            A3?.Table.AddLine(1 - 0.007, true, false);
            A4?.Table.AddLine(0.646, true, true);
            A4?.Table.AddLine(1 - 0.646, true, false);
            network.Validate();
            Console.WriteLine(network.ToString() + "\n");
            Console.WriteLine($"Liczba parametrów: {network.CalculateParameterCount()}");

            EnumerationQuery query = new EnumerationQuery(network);

            query.DefineEventType(WadliwyElement, EventType.Evidence);
            query.DefineEventType(A1, EventType.Outcome);
            query.DefineEventType(A2, EventType.Evidence);
            query.DefineEventType(A3, EventType.Evidence);
            query.DefineEventType(A4, EventType.Evidence);

            query.SetEventValue(WadliwyElement, false);
            query.SetEventValue(A1, false);
            query.SetEventValue(A2, false);
            query.SetEventValue(A3, false);
            query.SetEventValue(A4, false);
            query.Execute();

            Console.WriteLine(query.ToString());
        }
예제 #22
0
        /// <summary>
        /// Obtain the arguments for an event.
        /// </summary>
        /// <param name="e">The event.</param>
        /// <returns>The arguments for that event, based on the other event values.</returns>
        private int[] ObtainArgs(BayesianEvent e)
        {
            var result = new int[e.Parents.Count];

            int index = 0;

            foreach (BayesianEvent parentEvent in e.Parents)
            {
                EventState state = GetEventState(parentEvent);
                if (!state.IsCalculated)
                {
                    return(null);
                }
                result[index++] = state.Value;
            }
            return(result);
        }
예제 #23
0
        /// <summary>
        /// Resolve the event to an actual value.
        /// </summary>
        /// <param name="actualEvent">The actual event.</param>
        /// <returns>The value.</returns>
        public int ResolveValue(BayesianEvent actualEvent)
        {
            int result = 0;

            if (this.Value == null)
            {
                throw new BayesianError("Value is undefined for " + this.label + " should express a value with +, - or =.");
            }

            foreach (BayesianChoice choice in actualEvent.Choices)
            {
                if (this.Value.Equals(choice.Label))
                {
                    return(result);
                }
                result++;
            }

            // resolve true/false if not found, probably came from +/- notation
            if (String.Compare(Value, "true", true) == 0)
            {
                return(0);
            }
            else if (String.Compare(Value, "false", true) == 0)
            {
                return(1);
            }

            // try to resolve numeric index
            try
            {
                int i = int.Parse(this.Value);
                if (i < actualEvent.Choices.Count)
                {
                    return(i);
                }
            }
            catch (FormatException ex)
            {
                // well, we tried
            }

            // error out if nothing found
            throw new BayesianError("Can'f find choice " + this.Value + " in the event " + this.label);
        }
        /// <summary>
        /// Resolve the event to an actual value.
        /// </summary>
        /// <param name="actualEvent">The actual event.</param>
        /// <returns>The value.</returns>
        public int ResolveValue(BayesianEvent actualEvent)
        {
            int result = 0;

            if (this.Value == null)
            {
                throw new BayesianError("Value is undefined for " + this.label + " should express a value with +, - or =.");
            }

            foreach (BayesianChoice choice in actualEvent.Choices)
            {
                if (this.Value.Equals(choice.Label))
                {
                    return result;
                }
                result++;
            }

            // resolve true/false if not found, probably came from +/- notation
            if (String.Compare(Value, "true", true) == 0)
            {
                return 0;
            }
            else if (String.Compare(Value, "false", true) == 0)
            {
                return 1;
            }

            // try to resolve numeric index
            try
            {
                int i = int.Parse(this.Value);
                if (i < actualEvent.Choices.Count)
                {
                    return i;
                }
            }
            catch (FormatException ex)
            {
                // well, we tried
            }

            // error out if nothing found
            throw new BayesianError("Can'f find choice " + this.Value + " in the event " + this.label);
        }
예제 #25
0
        public void TestIndependant2()
        {
            BayesianNetwork network = new BayesianNetwork();
            BayesianEvent   a       = network.CreateEvent("a");
            BayesianEvent   b       = network.CreateEvent("b");
            BayesianEvent   c       = network.CreateEvent("c");
            BayesianEvent   d       = network.CreateEvent("d");

            network.CreateDependency(a, b, c);
            network.CreateDependency(b, d);
            network.CreateDependency(c, d);
            network.FinalizeStructure();

            Assert.IsFalse(network.IsCondIndependent(b, c));
            Assert.IsFalse(network.IsCondIndependent(b, c, d));
            Assert.IsTrue(network.IsCondIndependent(a, c, a));
            Assert.IsFalse(network.IsCondIndependent(a, c, a, d));
        }
        public void Execute(IExampleInterface app)
        {
            BayesianNetwork network     = new BayesianNetwork();
            BayesianEvent   grass       = network.CreateEvent("grass");
            BayesianEvent   sprinkler   = network.CreateEvent("sprinkler");
            BayesianEvent   rain        = network.CreateEvent("rain");
            BayesianEvent   DidRain     = network.CreateEvent("did_rain");
            BayesianEvent   SprinklerOn = network.CreateEvent("sprinkler_on");

            network.CreateDependency(rain, DidRain);
            network.CreateDependency(sprinkler, SprinklerOn);
            network.FinalizeStructure();

            // build the truth tales
            rain.Table.AddLine(0.35, true);
            // 80% of the time they were right
            DidRain.Table.AddLine(0.80, false, true);
            // 20% of the time they were wrong
            DidRain.Table.AddLine(0.20, true, true);

            sprinkler.Table.AddLine(.65, true);
            // 60% of the time they were right
            SprinklerOn.Table.AddLine(.40, true, true);
            // 40% of the time they were wrong
            SprinklerOn.Table.AddLine(.60, false, true);

            // validate the network
            network.Validate();
            // display basic stats
            Console.WriteLine(network.ToString());
            Console.WriteLine("Parameter count: " + network.CalculateParameterCount());
            EnumerationQuery query = new EnumerationQuery(network);

            //SamplingQuery query = new SamplingQuery(network);

            query.DefineEventType(SprinklerOn, EventType.Evidence);
            query.DefineEventType(sprinkler, EventType.Outcome);
            query.DefineEventType(DidRain, EventType.Evidence);
            query.DefineEventType(rain, EventType.Outcome);

            query.Execute();
            Console.WriteLine(query.ToString());
        }
예제 #27
0
        /// <summary>
        /// Init to Naive Bayes.
        /// </summary>
        private void InitNaiveBayes()
        {
            // clear out anything from before
            _network.RemoveAllRelations();

            // locate the classification target event
            BayesianEvent classificationTarget = _network
                                                 .ClassificationTargetEvent;

            // now link everything to this event
            foreach (BayesianEvent e in _network.Events)
            {
                if (e != classificationTarget)
                {
                    _network.CreateDependency(classificationTarget, e);
                }
            }

            _network.FinalizeStructure();
        }
예제 #28
0
        public void TestEnumeration1()
        {
            BayesianNetwork network = new BayesianNetwork();
            BayesianEvent   a       = network.CreateEvent("a");
            BayesianEvent   b       = network.CreateEvent("b");

            network.CreateDependency(a, b);
            network.FinalizeStructure();
            a.Table.AddLine(0.5, true);        // P(A) = 0.5
            b.Table.AddLine(0.2, true, true);  // p(b|a) = 0.2
            b.Table.AddLine(0.8, true, false); // p(b|~a) = 0.8
            network.Validate();

            EnumerationQuery query = new EnumerationQuery(network);

            query.DefineEventType(a, EventType.Evidence);
            query.DefineEventType(b, EventType.Outcome);
            query.SetEventValue(b, true);
            query.SetEventValue(a, true);
            query.Execute();
            TestPercent(query.Probability, 20);
        }
예제 #29
0
        /// <summary>
        /// Roll the enumeration events forward by one.
        /// </summary>
        /// <param name="enumerationEvents">The events to roll.</param>
        /// <param name="args">The arguments to roll.</param>
        /// <returns>False if there are no more values to roll into, which means we're
        ///         done.</returns>
        public static bool Roll(IList <BayesianEvent> enumerationEvents, int[] args)
        {
            int  currentIndex = 0;
            bool done         = false;
            bool eof          = false;

            if (enumerationEvents.Count == 0)
            {
                done = true;
                eof  = true;
            }

            while (!done)
            {
                BayesianEvent e = enumerationEvents[currentIndex];
                int           v = args[currentIndex];
                v++;
                if (v >= e.Choices.Count)
                {
                    args[currentIndex] = 0;
                }
                else
                {
                    args[currentIndex] = v;
                    break;
                }

                currentIndex++;

                if (currentIndex >= args.Length)
                {
                    done = true;
                    eof  = true;
                }
            }

            return(!eof);
        }
 /// <summary>
 /// Construct an event state for the specified event. 
 /// </summary>
 /// <param name="theEvent">The event to create a state for.</param>
 public EventState(BayesianEvent theEvent)
 {
     _event = theEvent;
     CurrentEventType = EventType.Hidden;
     IsCalculated = false;
 }
예제 #31
0
 /// <inheritdoc/>
 public void SetEventValue(BayesianEvent theEvent, bool b)
 {
     SetEventValue(theEvent, b ? 0 : 1);
 }
예제 #32
0
        /// <summary>
        /// Obtain the arguments for an event. 
        /// </summary>
        /// <param name="e">The event.</param>
        /// <returns>The arguments for that event, based on the other event values.</returns>
        private int[] ObtainArgs(BayesianEvent e)
        {
            var result = new int[e.Parents.Count];

            int index = 0;
            foreach (BayesianEvent parentEvent in e.Parents)
            {
                EventState state = GetEventState(parentEvent);
                if (!state.IsCalculated)
                    return null;
                result[index++] = state.Value;
            }
            return result;
        }
예제 #33
0
        /// <summary>
        /// Calculate the value N, which is the number of cases, from the training data, where the
        /// desiredValue matches the training data.  Only cases where the parents match the specifed
        /// parent instance are considered.
        /// </summary>
        /// <param name="network">The network to calculate for.</param>
        /// <param name="e">The event we are calculating for. (variable i)</param>
        /// <param name="parents">The parents of the specified event we are considering.</param>
        /// <param name="parentInstance">The parent instance we are looking for.</param>
        /// <returns>The value N. </returns>
        public int CalculateN(BayesianNetwork network, BayesianEvent e,
                              IList<BayesianEvent> parents, int[] parentInstance)
        {
            int result = 0;

            foreach (IMLDataPair pair in _data)
            {
                int[] d = _network.DetermineClasses(pair.Input);

                bool reject = false;

                for (int i = 0; i < parentInstance.Length; i++)
                {
                    BayesianEvent parentEvent = parents[i];
                    int parentIndex = network.GetEventIndex(parentEvent);
                    if (parentInstance[i] != (d[parentIndex]))
                    {
                        reject = true;
                        break;
                    }
                }

                if (!reject)
                {
                    result++;
                }
            }
            return result;
        }
예제 #34
0
        /// <summary>
        /// Obtain the arguments for an event.
        /// </summary>
        /// <param name="theEvent">The event.</param>
        /// <returns>The arguments.</returns>
        private int[] ObtainArgs(BayesianEvent theEvent)
        {
            var result = new int[theEvent.Parents.Count];

            int index = 0;
            foreach (BayesianEvent parentEvent in theEvent.Parents)
            {
                EventState state = GetEventState(parentEvent);
                result[index++] = state.Value;
            }
            return result;
        }
예제 #35
0
 /// <inheritdoc/>
 public EventType GetEventType(BayesianEvent theEvent)
 {
     return(GetEventState(theEvent).CurrentEventType);
 }
 /// <inheritdoc/>
 public void SetEventValue(BayesianEvent theEvent, bool b)
 {
     SetEventValue(theEvent, b ? 0 : 1);
 }
 /// <inheritdoc/>
 public EventState GetEventState(BayesianEvent theEvent)
 {
     if (!_events.ContainsKey(theEvent))
         return null;
     return _events[theEvent];
 }
예제 #38
0
        /// <summary>
        /// Find the value for z.
        /// </summary>
        /// <param name="e">The event that we are clauclating for.</param>
        /// <param name="n">The value for n.</param>
        /// <param name="old">The old value.</param>
        /// <returns>The new value for z.</returns>
        private BayesianEvent FindZ(BayesianEvent e, int n, double old)
        {
            BayesianEvent result = null;
            double maxChildP = double.NegativeInfinity;
            //System.out.println("Finding parent for: " + event.toString());
            for (int i = 0; i < n; i++)
            {
                BayesianEvent trialParent = _nodeOrdering[i];
                IList<BayesianEvent> parents = new List<BayesianEvent>();
                parents.CopyTo(e.Parents.ToArray(), 0);
                parents.Add(trialParent);
                //System.out.println("Calculating adding " + trialParent.toString() + " to " + event.toString());
                _lastCalculatedP = CalculateG(_network, e, parents);
                //System.out.println("lastP:" + this.lastCalculatedP);
                //System.out.println("old:" + old);
                if (_lastCalculatedP > old && _lastCalculatedP > maxChildP)
                {
                    result = trialParent;
                    maxChildP = _lastCalculatedP;
                    //System.out.println("Current best is: " + result.toString());
                }
            }

            _lastCalculatedP = maxChildP;
            return result;
        }
 /// <inheritdoc/>
 public void DefineEventType(BayesianEvent theEvent, EventType et)
 {
     GetEventState(theEvent).CurrentEventType = et;
 }
예제 #40
0
 /// <summary>
 /// Construct a Bayes truth table.
 /// </summary>
 /// <param name="theEvent">The lines of the truth table.</param>
 public BayesianTable(BayesianEvent theEvent)
 {
     _event = theEvent;
     Reset();
 }
 /// <inheritdoc/>
 public EventType GetEventType(BayesianEvent theEvent)
 {
     return GetEventState(theEvent).CurrentEventType;
 }
예제 #42
0
 /// <summary>
 /// Construct an event state for the specified event.
 /// </summary>
 /// <param name="theEvent">The event to create a state for.</param>
 public EventState(BayesianEvent theEvent)
 {
     _event           = theEvent;
     CurrentEventType = EventType.Hidden;
     IsCalculated     = false;
 }
        /// <inheritdoc/>
        public void SetEventValue(BayesianEvent theEvent, int d)
        {
            if (GetEventType(theEvent) == EventType.Hidden)
            {
                throw new BayesianError("You may only set the value of an evidence or outcome event.");
            }

            GetEventState(theEvent).CompareValue = d;
            GetEventState(theEvent).Value = d;
        }
예제 #44
0
 /// <inheritdoc/>
 public void DefineEventType(BayesianEvent theEvent, EventType et)
 {
     GetEventState(theEvent).CurrentEventType = et;
 }