public void Train(DataSet ds) { folDSDomain = new FOLDataSetDomain(ds.specification, trueGoalValue); ICollection <FOLExample> folExamples = CollectionFactory.CreateQueue <FOLExample>(); int egNo = 1; foreach (Example e in ds.examples) { folExamples.Add(new FOLExample(folDSDomain, e, egNo)); egNo++; } // Setup a KB to be used for learning kb = new FOLKnowledgeBase(folDSDomain, new FOLOTTERLikeTheoremProver(1000, false)); CurrentBestLearning cbl = new CurrentBestLearning(folDSDomain, kb); currentBestHypothesis = cbl.currentBestLearning(folExamples); }
private ICollection <double> convertCategoryToListOfDoubles(string plant_category_string) { if (plant_category_string.Equals("setosa")) { return(CollectionFactory.CreateQueue <double>(new[] { 0.0, 0.0, 1.0 })); } else if (plant_category_string.Equals("versicolor")) { return(CollectionFactory.CreateQueue <double>(new[] { 0.0, 1.0, 0.0 })); } else if (plant_category_string.Equals("virginica")) { return(CollectionFactory.CreateQueue <double>(new[] { 1.0, 0.0, 0.0 })); } else { throw new RuntimeException("invalid plant category"); } }
public void testNormalize() { ICollection <Page> pages = CollectionFactory.CreateQueue <Page>(); Page p1 = new Page(""); Page p2 = new Page(""); Page p3 = new Page(""); Page p4 = new Page(""); p1.hub = 3; p1.authority = 2; p2.hub = 2; p2.authority = 3; p3.hub = 1; p1.authority = 4; p4.hub = 0; p4.authority = 10; pages.Add(p1); pages.Add(p2); pages.Add(p3); pages.Add(p4); // hub total will be 9 + 4 + 1 + 0 = 14 // authority total will 4 + 9 + 16 + 100 = 129 double p1HubNorm = 0.214285; double p2HubNorm = 0.142857; hits.normalize(pages); Assert.AreEqual(p1HubNorm, pages.Get(0).hub, 0.02); Assert.AreEqual(pages.Get(1).hub, p2HubNorm, 0.02); }
public void testSimpleClauseExamples() { FOLDomain domain = new FOLDomain(); domain.addConstant("A"); domain.addConstant("B"); domain.addConstant("C"); domain.addConstant("D"); domain.addConstant("E"); domain.addPredicate("P"); domain.addPredicate("Q"); domain.addPredicate("W"); domain.addFunction("F"); domain.addFunction("G"); domain.addFunction("H"); domain.addFunction("J"); FOLParser parser = new FOLParser(domain); ICollection <Literal> lits = CollectionFactory.CreateQueue <Literal>(); Predicate p1 = (Predicate)parser.parse("Q(z, G(D,B))"); Predicate p2 = (Predicate)parser.parse("P(x, G(A,C))"); Predicate p3 = (Predicate)parser.parse("W(z,x,u,w,y)"); lits.Add(new Literal(p1)); lits.Add(new Literal(p2)); lits.Add(new Literal(p3)); Clause clExpression = new Clause(lits); TermEquality assertion = (TermEquality)parser.parse("G(x,y) = x"); Clause altClExpression = demodulation.apply(assertion, clExpression); Assert.AreEqual("[P(x,G(A,C)), Q(z,D), W(z,x,u,w,y)]", altClExpression.ToString()); altClExpression = demodulation.apply(assertion, altClExpression); Assert.AreEqual("[P(x,A), Q(z,D), W(z,x,u,w,y)]", altClExpression.ToString()); }
public Clause apply(TermEquality assertion, Clause clExpression) { Clause altClExpression = null; foreach (Literal l1 in clExpression.getLiterals()) { AtomicSentence altExpression = apply(assertion, l1.getAtomicSentence()); if (null != altExpression) { // I have an alternative, create a new clause // with the alternative and return ICollection <Literal> newLits = CollectionFactory.CreateQueue <Literal>(); foreach (Literal l2 in clExpression.getLiterals()) { if (l1.Equals(l2)) { newLits.Add(l1.newInstance(altExpression)); } else { newLits.Add(l2); } } // Only apply demodulation at most once on // each call. altClExpression = new Clause(newLits); altClExpression.setProofStep(new ProofStepClauseDemodulation(altClExpression, clExpression, assertion)); if (clExpression.isImmutable()) { altClExpression.setImmutable(); } if (!clExpression.isStandardizedApartCheckRequired()) { altClExpression.setStandardizedApartCheckNotRequired(); } break; } } return(altClExpression); }
public static ICollection <double> normalizeFromMeanAndStdev(ICollection <double> values, double mean, double stdev) { ICollection <double> obj = CollectionFactory.CreateQueue <double>(); foreach (double d in values) { if (d == mean) { mean = d - EPSILON; } if (0 == stdev) { stdev = EPSILON; } obj.Add((d - mean) / stdev); } return(obj); // return values.stream().map(d-> (d - mean) / stdev).collect(Collectors.toList()); }
/** * Constructs a map CSP for the principal states and territories of * Australia, with the colors Red, Green, and Blue. */ public MapCSP() : base(CollectionFactory.CreateQueue <Variable>(new[] { NSW, WA, NT, Q, SA, V, T })) { Domain <string> colors = new Domain <string>(RED, GREEN, BLUE); foreach (Variable var in getVariables()) { setDomain(var, colors); } addConstraint(new NotEqualConstraint <Variable, string>(WA, NT)); addConstraint(new NotEqualConstraint <Variable, string>(WA, SA)); addConstraint(new NotEqualConstraint <Variable, string>(NT, SA)); addConstraint(new NotEqualConstraint <Variable, string>(NT, Q)); addConstraint(new NotEqualConstraint <Variable, string>(SA, Q)); addConstraint(new NotEqualConstraint <Variable, string>(SA, NSW)); addConstraint(new NotEqualConstraint <Variable, string>(SA, V)); addConstraint(new NotEqualConstraint <Variable, string>(Q, NSW)); addConstraint(new NotEqualConstraint <Variable, string>(NSW, V)); }
/** Returns variables from <code>vars</code> which are the best with respect to MRV. */ public ICollection <VAR> apply(CSP <VAR, VAL> csp, ICollection <VAR> vars) { ICollection <VAR> result = CollectionFactory.CreateQueue <VAR>(); int mrv = int.MaxValue; foreach (VAR var in vars) { int rv = csp.getDomain(var).size(); if (rv <= mrv) { if (rv < mrv) { result.Clear(); mrv = rv; } result.Add(var); } } return(result); }
/** Returns variables from <code>vars</code> which are the best with respect to DEG. */ public ICollection <VAR> apply(CSP <VAR, VAL> csp, ICollection <VAR> vars) { ICollection <VAR> result = CollectionFactory.CreateQueue <VAR>(); int maxDegree = -1; foreach (VAR var in vars) { int degree = csp.getConstraints(var).Size(); if (degree >= maxDegree) { if (degree > maxDegree) { result.Clear(); maxDegree = degree; } result.Add(var); } } return(result); }
public ICollection <IAction> apply(AgentPosition state) { ICollection <IAction> actions = CollectionFactory.CreateQueue <IAction>(); ICollection <AgentPosition> linkedPositions = cave.getLocationsLinkedTo(state); foreach (AgentPosition linkPos in linkedPositions) { if (linkPos.getX() != state.getX() || linkPos.getY() != state.getY()) { actions.Add(new Forward(state)); } } actions.Add(new TurnLeft(state.getOrientation())); actions.Add(new TurnRight(state.getOrientation())); return(actions); }
public object visitFunction(Function function, object arg) { if (!replaced) { if (toReplace.Equals(function)) { replaced = true; return(replaceWith); } } ICollection <Term> newTerms = CollectionFactory.CreateQueue <Term>(); foreach (Term t in function.getTerms()) { Term subsTerm = (Term)t.accept(this, arg); newTerms.Add(subsTerm); } return(new Function(function.getFunctionName(), newTerms)); }
public void testSimpleVariableUnification() { Variable var1 = new Variable("x"); ICollection <Term> terms1 = CollectionFactory.CreateQueue <Term>(); terms1.Add(var1); Predicate p1 = new Predicate("King", terms1); // King(x) ICollection <Term> terms2 = CollectionFactory.CreateQueue <Term>(); terms2.Add(new Constant("John")); Predicate p2 = new Predicate("King", terms2); // King(John) IMap <Variable, Term> result = unifier.unify(p1, p2, theta); Assert.AreEqual(theta, result); Assert.AreEqual(1, theta.GetKeys().Size()); Assert.IsTrue(theta.GetKeys().Contains(new Variable("x"))); // x = Assert.AreEqual(new Constant("John"), theta.Get(var1)); // John }
public void testIsHornClause() { Clause c1 = new Clause(); Assert.IsFalse(c1.isHornClause()); c1.addNegativeLiteral(new Predicate("Pred1", CollectionFactory.CreateQueue <Term>())); Assert.IsTrue(c1.isHornClause()); c1.addPositiveLiteral(new Predicate("Pred2", CollectionFactory.CreateQueue <Term>())); Assert.IsTrue(c1.isHornClause()); c1.addNegativeLiteral(new Predicate("Pred3", CollectionFactory.CreateQueue <Term>())); Assert.IsTrue(c1.isHornClause()); c1.addNegativeLiteral(new Predicate("Pred4", CollectionFactory.CreateQueue <Term>())); Assert.IsTrue(c1.isHornClause()); c1.addPositiveLiteral(new Predicate("Pred5", CollectionFactory.CreateQueue <Term>())); Assert.IsFalse(c1.isHornClause()); }
static void fOL_Paramodulation() { System.Console.WriteLine("-------------------"); System.Console.WriteLine("Paramodulation Demo"); System.Console.WriteLine("-------------------"); FOLDomain domain = new FOLDomain(); domain.addConstant("A"); domain.addConstant("B"); domain.addPredicate("P"); domain.addPredicate("Q"); domain.addPredicate("R"); domain.addFunction("F"); FOLParser parser = new FOLParser(domain); ICollection <Literal> lits = CollectionFactory.CreateQueue <Literal>(); AtomicSentence a1 = (AtomicSentence)parser.parse("P(F(x,B),x)"); AtomicSentence a2 = (AtomicSentence)parser.parse("Q(x)"); lits.Add(new Literal(a1)); lits.Add(new Literal(a2)); Clause c1 = new Clause(lits); lits.Clear(); a1 = (AtomicSentence)parser.parse("F(A,y) = y"); a2 = (AtomicSentence)parser.parse("R(y)"); lits.Add(new Literal(a1)); lits.Add(new Literal(a2)); Clause c2 = new Clause(lits); Paramodulation paramodulation = new Paramodulation(); ISet <Clause> paras = paramodulation.apply(c1, c2); System.Console.WriteLine("Paramodulate '" + c1 + "' with '" + c2 + "' to give"); System.Console.WriteLine(paras.ToString()); System.Console.WriteLine(""); }
public void testPlanRoute() { HybridWumpusAgent hwa = new HybridWumpusAgent(4); // Should be a NoOp plan as we are already at the goal. Assert.AreEqual(CollectionFactory.CreateQueue <IAction>(), hwa.planRoute(new AgentPosition(1, 1, AgentPosition.Orientation.FACING_EAST), CollectionFactory.CreateSet <Room>(new Room(1, 1)), allRooms(4) )); Assert.AreEqual(CollectionFactory.CreateQueue <IAction>( new TurnLeft(AgentPosition.Orientation.FACING_EAST), new TurnLeft(AgentPosition.Orientation.FACING_NORTH), new Forward(new AgentPosition(2, 1, AgentPosition.Orientation.FACING_WEST)) ), hwa.planRoute(new AgentPosition(2, 1, AgentPosition.Orientation.FACING_EAST), CollectionFactory.CreateSet <Room>(new Room(1, 1)), allRooms(4) )); ISet <Room> impl = CollectionFactory.CreateSet <Room>(allRooms(4)); impl.Remove(new Room(2, 1)); impl.Remove(new Room(2, 2)); Assert.AreEqual(CollectionFactory.CreateQueue <IAction>( new TurnLeft(AgentPosition.Orientation.FACING_EAST), new Forward(new AgentPosition(3, 1, AgentPosition.Orientation.FACING_NORTH)), new Forward(new AgentPosition(3, 2, AgentPosition.Orientation.FACING_NORTH)), new TurnLeft(AgentPosition.Orientation.FACING_NORTH), new Forward(new AgentPosition(3, 3, AgentPosition.Orientation.FACING_WEST)), new Forward(new AgentPosition(2, 3, AgentPosition.Orientation.FACING_WEST)), new TurnLeft(AgentPosition.Orientation.FACING_WEST), new Forward(new AgentPosition(1, 3, AgentPosition.Orientation.FACING_SOUTH)), new Forward(new AgentPosition(1, 2, AgentPosition.Orientation.FACING_SOUTH)) ), hwa.planRoute(new AgentPosition(3, 1, AgentPosition.Orientation.FACING_EAST), CollectionFactory.CreateSet <Room>(new Room(1, 1)), impl)); }
public virtual ICollection <DecisionListTest> createDLTestsWithAttributeCount(DataSet ds, int i) { if (i != 1) { throw new RuntimeException("For now DLTests with only 1 attribute can be craeted , not" + i); } ICollection <string> nonTargetAttributes = ds.getNonTargetAttributes(); ICollection <DecisionListTest> tests = CollectionFactory.CreateQueue <DecisionListTest>(); foreach (string ntAttribute in nonTargetAttributes) { ICollection <string> ntaValues = ds.getPossibleAttributeValues(ntAttribute); foreach (string ntaValue in ntaValues) { DecisionListTest test = new DecisionListTest(); test.add(ntAttribute, ntaValue); tests.Add(test); } } return(tests); }
public void testAdaBoostEnablesCollectionOfStumpsToClassifyDataSetAccurately() { DataSet ds = DataSetFactory.getRestaurantDataSet(); ICollection <DecisionTree> stumps = DecisionTree.getStumpsFor(ds, YES, "No"); ICollection <ILearner> learners = CollectionFactory.CreateQueue <ILearner>(); foreach (object stump in stumps) { DecisionTree sl = (DecisionTree)stump; StumpLearner stumpLearner = new StumpLearner(sl, "No"); learners.Add(stumpLearner); } AdaBoostLearner learner = new AdaBoostLearner(learners, ds); learner.Train(ds); int[] result = learner.Test(ds); Assert.AreEqual(12, result[0]); Assert.AreEqual(0, result[1]); }
// // PRIVATE METHODS // private IFactor makeFactor(IRandomVariable var, AssignmentProposition[] e, IBayesianNetwork bn) { INode n = bn.GetNode(var); if (!(n is IFiniteNode)) { throw new IllegalArgumentException("Elimination-Ask only works with finite Nodes."); } IFiniteNode fn = (IFiniteNode)n; ICollection <AssignmentProposition> evidence = CollectionFactory.CreateQueue <AssignmentProposition>(); foreach (AssignmentProposition ap in e) { if (fn.GetCPT().Contains(ap.getTermVariable())) { evidence.Add(ap); } } return(fn.GetCPT().GetFactorFor(evidence.ToArray())); }
public static ICollection <DecisionTree> getStumpsFor(DataSet ds, string returnValueIfMatched, string returnValueIfUnmatched) { ICollection <string> attributes = ds.getNonTargetAttributes(); ICollection <DecisionTree> trees = CollectionFactory.CreateQueue <DecisionTree>(); foreach (string attribute in attributes) { ICollection <string> values = ds.getPossibleAttributeValues(attribute); foreach (string value in values) { ICollection <string> unmatchedValues = Util.removeFrom(ds.getPossibleAttributeValues(attribute), value); DecisionTree tree = getStumpFor(ds, attribute, value, returnValueIfMatched, unmatchedValues, returnValueIfUnmatched); trees.Add(tree); } } return(trees); }
/** * A more restrictive phrase-structure grammar, used in testing and demonstrating * the CYK Algorithm. * Note: It is complemented by the "trivial lexicon" in LexiconExamples.java * @return */ public static ProbCNFGrammar buildTrivialGrammar() { ProbCNFGrammar g = new ProbCNFGrammar(); ICollection <Rule> rules = CollectionFactory.CreateQueue <Rule>(); rules.Add(new Rule("S", "NP,VP", (float)1.0)); rules.Add(new Rule("NP", "ARTICLE,NOUN", (float)0.50)); rules.Add(new Rule("NP", "PRONOUN,ADVERB", (float)0.5)); rules.Add(new Rule("VP", "VERB,NP", (float)1.0)); // add terminal rules Lexicon trivLex = LexiconExamples.buildTrivialLexicon(); ICollection <Rule> terminalRules = CollectionFactory.CreateQueue <Rule>(trivLex.getAllTerminalRules()); rules.AddAll(terminalRules); // Add all these rules into the grammar if (!g.addRules(rules)) { return(null); } return(g); }
/** * Returns a set of substitutions * * @param KB * a knowledge base * @param query * goals, a list of conjuncts forming a query * * @return a set of substitutions */ public InferenceResult ask(FOLKnowledgeBase KB, Sentence query) { // Assertions on the type queries this Inference procedure // supports if (!(query is AtomicSentence)) { throw new IllegalArgumentException("Only Atomic Queries are supported."); } ICollection <Literal> goals = CollectionFactory.CreateQueue <Literal>(); goals.Add(new Literal((AtomicSentence)query)); BCAskAnswerHandler ansHandler = new BCAskAnswerHandler(); ICollection <ICollection <ProofStepBwChGoal> > allProofSteps = folbcask(KB, ansHandler, goals, CollectionFactory.CreateInsertionOrderedMap <Variable, Term>()); ansHandler.setAllProofSteps(allProofSteps); return(ansHandler); }
private IMap <string, ICollection <Literal> > collectLikeLiterals(ISet <Literal> literals) { IMap <string, ICollection <Literal> > likeLiterals = CollectionFactory.CreateInsertionOrderedMap <string, ICollection <Literal> >(); foreach (Literal l in literals) { // Want to ensure P(a, b) is considered different than P(a, b, c) // i.e. consider an atom's arity P/#. string literalName = (l.isNegativeLiteral() ? "~" : "") + l.getAtomicSentence().getSymbolicName() + "/" + l.getAtomicSentence().getArgs().Size(); ICollection <Literal> like = likeLiterals.Get(literalName); if (null == like) { like = CollectionFactory.CreateQueue <Literal>(); likeLiterals.Put(literalName, like); } like.Add(l); } return(likeLiterals); }
protected void testDefiniteClauseKBKingsQueryKingXReturnsJohnAndRichardSucceeds(InferenceProcedure infp) { FOLKnowledgeBase kkb = FOLKnowledgeBaseFactory.createKingsKnowledgeBase(infp); ICollection <Term> terms = CollectionFactory.CreateQueue <Term>(); terms.Add(new Variable("x")); Predicate query = new Predicate("King", terms); InferenceResult answer = kkb.ask(query); Assert.IsTrue(null != answer); Assert.IsFalse(answer.isPossiblyFalse()); Assert.IsTrue(answer.isTrue()); Assert.IsFalse(answer.isUnknownDueToTimeout()); Assert.IsFalse(answer.isPartialResultDueToTimeout()); Assert.IsTrue(2 == answer.getProofs().Size()); Assert.IsTrue(1 == answer.getProofs().Get(0).getAnswerBindings().Size()); Assert.IsTrue(1 == answer.getProofs().Get(1).getAnswerBindings().Size()); bool gotJohn, gotRichard; gotJohn = gotRichard = false; Constant cJohn = new Constant("John"); Constant cRichard = new Constant("Richard"); foreach (Proof p in answer.getProofs()) { IMap <Variable, Term> ans = p.getAnswerBindings(); Assert.AreEqual(1, ans.Size()); if (cJohn.Equals(ans.Get(new Variable("x")))) { gotJohn = true; } if (cRichard.Equals(ans.Get(new Variable("x")))) { gotRichard = true; } } Assert.IsTrue(gotJohn); Assert.IsTrue(gotRichard); }
/** * PL-RESOLUTION(KB, α)<br> * A simple resolution algorithm for propositional logic. * * @param kb * the knowledge base, a sentence in propositional logic. * @param alpha * the query, a sentence in propositional logic. * @return true if KB |= α, false otherwise. */ public bool plResolution(KnowledgeBase kb, Sentence alpha) { // clauses <- the set of clauses in the CNF representation // of KB & ~alpha ISet <Clause> clauses = setOfClausesInTheCNFRepresentationOfKBAndNotAlpha(kb, alpha); // new <- {} ISet <Clause> newClauses = CollectionFactory.CreateSet <Clause>(); // loop do do { // for each pair of clauses C_i, C_j in clauses do ICollection <Clause> clausesAsList = CollectionFactory.CreateQueue <Clause>(clauses); for (int i = 0; i < clausesAsList.Size() - 1; ++i) { Clause ci = clausesAsList.Get(i); for (int j = i + 1; j < clausesAsList.Size(); j++) { Clause cj = clausesAsList.Get(j); // resolvents <- PL-RESOLVE(C_i, C_j) ISet <Clause> resolvents = plResolve(ci, cj); // if resolvents contains the empty clause then return true if (resolvents.Contains(Clause.EMPTY)) { return(true); } // new <- new U resolvents newClauses.AddAll(resolvents); } } // if new is subset of clauses then return false if (clauses.ContainsAll(newClauses)) { return(false); } // clauses <- clauses U new clauses.AddAll(newClauses); } while (true); }
// Returns c if no cancellation occurred private Chain tryCancellation(Chain c) { Literal head = c.getHead(); if (null != head && !(head is ReducedLiteral)) { foreach (Literal l in c.getTail()) { if (l is ReducedLiteral) { // if they can be resolved if (head.isNegativeLiteral() != l.isNegativeLiteral()) { IMap <Variable, Term> subst = unifier .unify(head.getAtomicSentence(), l.getAtomicSentence()); if (null != subst) { // I have a cancellation // Need to apply subst to all of the // literals in the cancellation ICollection <Literal> cancLits = CollectionFactory.CreateQueue <Literal>(); foreach (Literal lfc in c.getTail()) { AtomicSentence a = (AtomicSentence)substVisitor .subst(subst, lfc.getAtomicSentence()); cancLits.Add(lfc.newInstance(a)); } Chain cancellation = new Chain(cancLits); cancellation .setProofStep(new ProofStepChainCancellation( cancellation, c, subst)); return(cancellation); } } } } } return(c); }
protected void testEqualityAndSubstitutionNoAxiomsKBabcdPFFASucceeds(InferenceProcedure infp, bool expectedToFail) { FOLKnowledgeBase akb = FOLKnowledgeBaseFactory.createABCDEqualityAndSubstitutionKnowledgeBase(infp, false); ICollection <Term> terms = CollectionFactory.CreateQueue <Term>(); terms.Add(new Constant("A")); Function fa = new Function("F", terms); terms = CollectionFactory.CreateQueue <Term>(); terms.Add(fa); Function ffa = new Function("F", terms); terms = CollectionFactory.CreateQueue <Term>(); terms.Add(ffa); Predicate query = new Predicate("P", terms); InferenceResult answer = akb.ask(query); Assert.IsTrue(null != answer); if (expectedToFail) { Assert.IsTrue(answer.isPossiblyFalse()); Assert.IsFalse(answer.isTrue()); Assert.IsFalse(answer.isUnknownDueToTimeout()); Assert.IsFalse(answer.isPartialResultDueToTimeout()); Assert.IsTrue(0 == answer.getProofs().Size()); } else { Assert.IsFalse(answer.isPossiblyFalse()); Assert.IsTrue(answer.isTrue()); Assert.IsFalse(answer.isUnknownDueToTimeout()); Assert.IsFalse(answer.isPartialResultDueToTimeout()); Assert.IsTrue(1 == answer.getProofs().Size()); Assert.IsTrue(0 == answer.getProofs().Get(0) .getAnswerBindings().Size()); } }
/** * Changes each component in the representation by random. The maximum * change is +- (maximum - minimum) / 4, but smaller changes have a higher * likelihood. */ protected override Individual <double> mutate(Individual <double> child) { ICollection <double> rep = child.getRepresentation(); ICollection <double> newRep = CollectionFactory.CreateQueue <double>(); foreach (double numIter in rep) { double num = numIter; double r = random.NextDouble() - 0.5; num += r * r * r * (maximum - minimum) / 2; if (num < minimum) { num = minimum; } else if (num > maximum) { num = maximum; } newRep.Add(num); } return(new Individual <double>(newRep)); }
/** * Template method controlling search. It returns the best individual in the * specified population, according to the specified FITNESS-FN and goal * test. * * @param initPopulation * a set of individuals * @param fitnessFn * a function that measures the fitness of an individual * @param goalTest * test determines whether a given individual is fit enough to * return. Can be used in subclasses to implement additional * termination criteria, e.g. maximum number of iterations. * @param maxTimeMilliseconds * the maximum time in milliseconds that the algorithm is to run * for (approximate). Only used if > 0L. * @return the best individual in the specified population, according to the * specified FITNESS-FN and goal test. */ // function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual // inputs: population, a set of individuals // FITNESS-FN, a function that measures the fitness of an individual public virtual Individual <A> geneticAlgorithm(ICollection <Individual <A> > initPopulation, IFitnessFunction <A> fitnessFn, GoalTest <Individual <A> > goalTest, long maxTimeMilliseconds) { Individual <A> bestIndividual = null; // Create a local copy of the population to work with ICollection <Individual <A> > population = CollectionFactory.CreateQueue <Individual <A> >(initPopulation); // Validate the population and setup the instrumentation validatePopulation(population); updateMetrics(population, 0, 0L); IStopWatch sw = CommonFactory.CreateStopWatch(); // repeat int itCount = 0; do { population = nextGeneration(population, fitnessFn); bestIndividual = retrieveBestIndividual(population, fitnessFn); updateMetrics(population, ++itCount, sw.GetElapsedMilliseconds()); // until some individual is fit enough, or enough time has elapsed if (maxTimeMilliseconds > 0L && sw.GetElapsedMilliseconds() > maxTimeMilliseconds) { break; } if (currIsCancelled) { break; } } while (!goalTest(bestIndividual)); notifyProgressTrackers(itCount, population); // return the best individual in population, according to FITNESS-FN return(bestIndividual); }
private void calcualteProofSteps() { proofSteps = CollectionFactory.CreateQueue <ProofStep>(); addToProofSteps(finalStep); // Move all premises to the front of the // list of steps int to = 0; for (int i = 0; i < proofSteps.Size(); ++i) { if (proofSteps.Get(i) is ProofStepPremise) { ProofStep m = proofSteps.Get(i); proofSteps.Remove(m); proofSteps.Insert(to, m); to++; } } // Move the Goals after the premises for (int i = 0; i < proofSteps.Size(); ++i) { if (proofSteps.Get(i) is ProofStepGoal) { ProofStep m = proofSteps.Get(i); proofSteps.Remove(m); proofSteps.Insert(to, m); to++; } } // Assign the step #s now that all the proof // steps have been unwound for (int i = 0; i < proofSteps.Size(); ++i) { proofSteps.Get(i).setStepNumber(i + 1); } }
/// <summary> /// create Example instances from a normalized data "table". /// </summary> private void createExamples() { dataset = CollectionFactory.CreateQueue <NeuralNetworkExample>(); foreach (ICollection <double> dataLine in nds) { ICollection <double> input = CollectionFactory.CreateQueue <double>(); ICollection <double> target = CollectionFactory.CreateQueue <double>(); for (int i = 0; i < dataLine.Size(); ++i) { if (targetColumnNumbers.Contains(i)) { target.Add(dataLine.Get(i)); } else { input.Add(dataLine.Get(i)); } } dataset.Add(new NeuralNetworkExample(input, target)); } RefreshDataset();// to populate the preentlyProcessed dataset }