001 package aima.learning.learners; 002 003 import java.util.ArrayList; 004 import java.util.List; 005 006 import aima.learning.framework.DataSet; 007 import aima.learning.framework.Example; 008 import aima.learning.framework.Learner; 009 import aima.learning.knowledge.CurrentBestLearning; 010 import aima.learning.knowledge.FOLDataSetDomain; 011 import aima.learning.knowledge.FOLExample; 012 import aima.learning.knowledge.Hypothesis; 013 import aima.logic.fol.inference.FOLOTTERLikeTheoremProver; 014 import aima.logic.fol.inference.InferenceResult; 015 import aima.logic.fol.kb.FOLKnowledgeBase; 016 017 /** 018 * @author Ciaran O'Reilly 019 * 020 */ 021 public class CurrentBestLearner implements Learner { 022 private String trueGoalValue = null; 023 private FOLDataSetDomain folDSDomain = null; 024 private FOLKnowledgeBase kb = null; 025 private Hypothesis currentBestHypothesis = null; 026 027 // 028 // PUBLIC METHODS 029 // 030 public CurrentBestLearner(String trueGoalValue) { 031 this.trueGoalValue = trueGoalValue; 032 } 033 034 // 035 // START-Learner 036 public void train(DataSet ds) { 037 folDSDomain = new FOLDataSetDomain(ds.specification, trueGoalValue); 038 List<FOLExample> folExamples = new ArrayList<FOLExample>(); 039 int egNo = 1; 040 for (Example e : ds.examples) { 041 folExamples.add(new FOLExample(folDSDomain, e, egNo)); 042 egNo++; 043 } 044 045 // Setup a KB to be used for learning 046 kb = new FOLKnowledgeBase(folDSDomain, new FOLOTTERLikeTheoremProver( 047 1000, false)); 048 049 CurrentBestLearning cbl = new CurrentBestLearning(folDSDomain, kb); 050 051 currentBestHypothesis = cbl.currentBestLearning(folExamples); 052 } 053 054 public String predict(Example e) { 055 String prediction = "~" + e.targetValue(); 056 if (null != currentBestHypothesis) { 057 FOLExample etp = new FOLExample(folDSDomain, e, 0); 058 kb.clear(); 059 kb.tell(etp.getDescription()); 060 kb.tell(currentBestHypothesis.getHypothesis()); 061 InferenceResult ir = kb.ask(etp.getClassification()); 062 if (ir.isTrue()) { 063 if (trueGoalValue.equals(e.targetValue())) { 064 prediction = e.targetValue(); 065 } 066 } else if (ir.isPossiblyFalse() || ir.isUnknownDueToTimeout()) { 067 if (!trueGoalValue.equals(e.targetValue())) { 068 prediction = e.targetValue(); 069 } 070 } 071 } 072 073 return prediction; 074 } 075 076 public int[] test(DataSet ds) { 077 int[] results = new int[] { 0, 0 }; 078 079 for (Example e : ds.examples) { 080 if (e.targetValue().equals(predict(e))) { 081 results[0] = results[0] + 1; 082 } else { 083 results[1] = results[1] + 1; 084 } 085 } 086 return results; 087 } 088 // END-Learner 089 // 090 }