001 /* 002 * Created on Apr 9, 2005 003 * 004 */ 005 package aima.learning.framework; 006 007 /** 008 * @author Ravi Mohan 009 * 010 */ 011 import java.util.Hashtable; 012 013 public class Example { 014 Hashtable<String, Attribute> attributes; 015 016 private Attribute targetAttribute; 017 018 public Example(Hashtable<String, Attribute> attributes, 019 Attribute targetAttribute) { 020 this.attributes = attributes; 021 this.targetAttribute = targetAttribute; 022 } 023 024 public String getAttributeValueAsString(String attributeName) { 025 return attributes.get(attributeName).valueAsString(); 026 } 027 028 public double getAttributeValueAsDouble(String attributeName) { 029 Attribute attribute = attributes.get(attributeName); 030 if (attribute == null || !(attribute instanceof NumericAttribute)) { 031 throw new RuntimeException( 032 "cannot return numerical value for non numeric attribute"); 033 } 034 return ((NumericAttribute) attribute).valueAsDouble(); 035 } 036 037 @Override 038 public String toString() { 039 return attributes.toString(); 040 } 041 042 public String targetValue() { 043 return getAttributeValueAsString(targetAttribute.name()); 044 } 045 046 @Override 047 public boolean equals(Object o) { 048 if (this == o) { 049 return true; 050 } 051 if ((o == null) || (this.getClass() != o.getClass())) { 052 return false; 053 } 054 Example other = (Example) o; 055 return attributes.equals(other.attributes); 056 } 057 058 @Override 059 public int hashCode() { 060 return attributes.hashCode(); 061 } 062 063 public Example numerize( 064 Hashtable<String, Hashtable<String, Integer>> attrValueToNumber) { 065 Hashtable<String, Attribute> numerizedExampleData = new Hashtable<String, Attribute>(); 066 for (String key : attributes.keySet()) { 067 Attribute attribute = attributes.get(key); 068 if (attribute instanceof StringAttribute) { 069 int correspondingNumber = attrValueToNumber.get(key).get( 070 attribute.valueAsString()); 071 NumericAttributeSpecification spec = new NumericAttributeSpecification( 072 key); 073 numerizedExampleData.put(key, new NumericAttribute( 074 correspondingNumber, spec)); 075 } else {// Numeric Attribute 076 numerizedExampleData.put(key, attribute); 077 } 078 } 079 return new Example(numerizedExampleData, numerizedExampleData 080 .get(targetAttribute.name())); 081 } 082 }