weka.classifiers.AbstractClassifier Java Examples

The following examples show how to use weka.classifiers.AbstractClassifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MLExperimentTester.java    From AILibs with GNU Affero General Public License v3.0 7 votes vote down vote up
@Override
public void evaluate(final ExperimentDBEntry experimentEntry, final IExperimentIntermediateResultProcessor processor) throws ExperimentEvaluationFailedException {
	try {
		if (config.getDatasetFolder() == null || (!config.getDatasetFolder().exists())) {
			throw new IllegalArgumentException("config specifies invalid dataset folder " + config.getDatasetFolder());
		}
		Map<String, String> description = experimentEntry.getExperiment().getValuesOfKeyFields();
		Classifier c = AbstractClassifier.forName(description.get("classifier"), null);
		Instances data = new Instances(new BufferedReader(new FileReader(new File(config.getDatasetFolder() + File.separator + description.get("dataset") + ".arff"))));
		data.setClassIndex(data.numAttributes() - 1);
		int seed = Integer.parseInt(description.get("seed"));

		logger.info("Testing classifier {}", c.getClass().getName());
		Map<String, Object> results = new HashMap<>();

		ILabeledDataset<? extends ILabeledInstance> dataset = new WekaInstances(data);
		SingleRandomSplitClassifierEvaluator eval = new SingleRandomSplitClassifierEvaluator(dataset, .7, new Random(seed));
		double loss = eval.evaluate(new WekaClassifier(c));

		results.put("loss", loss);
		processor.processResults(results);
		this.conductedExperiment = true;
	} catch (Exception e) {
		throw new ExperimentEvaluationFailedException(e);
	}
}
 
Example #2
Source File: HASEL.java    From meka with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void buildClassifier(Instances D) throws Exception {

	int L = D.classIndex();
	int N = D.numInstances();

	// Get partition from dataset hierarchy
	kMap = SuperLabelUtils.getPartitionFromDatasetHierarchy(D); 
	m_M = kMap.length;
	m_Classifiers = AbstractClassifier.makeCopies(m_Classifier,m_M);
	m_InstancesTemplates = new Instances[m_M];

	for(int i = 0; i < m_M; i++) {

		if (getDebug()) 
			System.out.println("Building model "+(i+1)+"/"+m_M+": "+Arrays.toString(kMap[i]));
		Instances D_i = SuperLabelUtils.makePartitionDataset(D,kMap[i]);
		m_Classifiers[i].buildClassifier(D_i);
		m_InstancesTemplates[i] = new Instances(D_i,0);
	}

}
 
Example #3
Source File: TransformEnsembles.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
public void findCVWeights() throws Exception {
	cvWeights=new double[nosTransforms];
	int folds=numInstances;
	if(folds>THRESHOLD1){
			folds=10;
	}
	System.out.print("\n Finding CV Accuracy: ");
	for(int i=0;i<nosTransforms;i++){
		 Evaluation evaluation = new Evaluation(train.get(i));
                        if(i==0)
                           evaluation.crossValidateModel(AbstractClassifier.makeCopy(baseTime), train.get(i), folds, new Random());
                        else
                            evaluation.crossValidateModel(AbstractClassifier.makeCopy(base), train.get(i), folds, new Random());
		 cvWeights[i]=1-evaluation.errorRate();
		 System.out.print(","+cvWeights[i]);
	}
	 System.out.print("\n");
}
 
Example #4
Source File: WekaClassifierTest.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testFit() throws Exception {
	WekaClassifier classifier = new WekaClassifier("weka.classifiers.trees.RandomForest", new String[] {});
	Classifier oClassifier = AbstractClassifier.forName("weka.classifiers.trees.RandomForest", null);

	/* fit both classifiers */
	IWekaInstances dataset = new WekaInstances(ArffDatasetAdapter.readDataset(new File("testrsc/dataset/arff/numeric_only_with_classindex.arff")));
	classifier.fit(dataset);
	oClassifier.buildClassifier(dataset.getInstances());

	/* test that predictions are identical */
	ISingleLabelClassificationPredictionBatch yHat = classifier.predict(dataset);
	int n = yHat.size();
	assertEquals(dataset.size(), n);
	for (int i = 0; i < n; i++) {
		assertEquals(oClassifier.classifyInstance(dataset.get(i).getElement()), yHat.get(i));
	}
}
 
Example #5
Source File: NBTreeNoSplit.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Utility method for fast 5-fold cross validation of a naive bayes
  * model
  *
  * @param fullModel a <code>NaiveBayesUpdateable</code> value
  * @param trainingSet an <code>Instances</code> value
  * @param r a <code>Random</code> value
  * @return a <code>double</code> value
  * @exception Exception if an error occurs
  */
 public static double crossValidate(NaiveBayesUpdateable fullModel,
		       Instances trainingSet,
		       Random r) throws Exception {
   // make some copies for fast evaluation of 5-fold xval
   Classifier [] copies = AbstractClassifier.makeCopies(fullModel, 5);
   Evaluation eval = new Evaluation(trainingSet);
   // make some splits
   for (int j = 0; j < 5; j++) {
     Instances test = trainingSet.testCV(5, j);
     // unlearn these test instances
     for (int k = 0; k < test.numInstances(); k++) {
test.instance(k).setWeight(-test.instance(k).weight());
((NaiveBayesUpdateable)copies[j]).updateClassifier(test.instance(k));
// reset the weight back to its original value
test.instance(k).setWeight(-test.instance(k).weight());
     }
     eval.evaluateModel(copies[j], test);
   }
   return eval.incorrect();
 }
 
Example #6
Source File: CR.java    From meka with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void buildClassifier(Instances D) throws Exception {
  	testCapabilities(D);
  	
	int L = D.classIndex();

	if(getDebug()) System.out.print("Creating "+L+" models ("+m_Classifier.getClass().getName()+"): ");
	m_MultiClassifiers = AbstractClassifier.makeCopies(m_Classifier,L);
	m_Templates = new Instances[L];

	for(int j = 0; j < L; j++) {

		//Select only class attribute 'j'
		m_Templates[j] = MLUtils.keepAttributesAt(new Instances(D),new int[]{j},L);
		m_Templates[j].setClassIndex(0);

		//Build the classifier for that class
		m_MultiClassifiers[j].buildClassifier(m_Templates[j]);
		if(getDebug()) System.out.print(" " + (m_Templates[j].classAttribute().name()));

		m_Templates[j] = new Instances(m_Templates[j], 0);
	}
}
 
Example #7
Source File: AbstractMultiSearch.java    From meka with GNU General Public License v3.0 6 votes vote down vote up
/**
 * the default constructor.
 */
public AbstractMultiSearch() {
	super();

	m_Factory           = newFactory();
	m_Metrics           = m_Factory.newMetrics();
	m_Evaluation        = m_Metrics.getDefaultMetric();
	m_Classifier        = defaultClassifier();
	m_DefaultParameters = defaultSearchParameters();
	m_Parameters        = defaultSearchParameters();
	m_Algorithm         = defaultAlgorithm();
	m_Trace             = new ArrayList<Entry<Integer, Performance>>();

	try {
		m_BestClassifier = new SearchResult();
		m_BestClassifier.classifier = AbstractClassifier.makeCopy(m_Classifier);
	}
	catch (Exception e) {
		System.err.println("Failed to create copy of default classifier!");
		e.printStackTrace();
	}
}
 
Example #8
Source File: CDN.java    From meka with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void buildClassifier(Instances D) throws Exception {
	testCapabilities(D);

	int N = D.numInstances();
	int L = D.classIndex();
	h = new Classifier[L];
	m_R = new Random(m_S);
	D_templates = new Instances[L];

	// Build L probabilistic models, each to predict Y_i | X, Y_{-y}; save the templates.
	for(int j = 0; j < L; j++) {
		// X = [Y[0],...,Y[j-1],Y[j+1],...,Y[L],X]
		D_templates[j] = new Instances(D);
		D_templates[j].setClassIndex(j);
		// train H[j] : X -> Y
		h[j] = AbstractClassifier.forName(getClassifier().getClass().getName(),((AbstractClassifier)getClassifier()).getOptions());
		h[j].buildClassifier(D_templates[j]);
	}
}
 
Example #9
Source File: BR.java    From meka with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void buildClassifier(Instances D) throws Exception {
	testCapabilities(D);
  	
	int L = D.classIndex();

	if(getDebug()) System.out.print("Creating "+L+" models ("+m_Classifier.getClass().getName()+"): ");
	m_MultiClassifiers = AbstractClassifier.makeCopies(m_Classifier,L);
	m_InstancesTemplates = new Instances[L];

	for(int j = 0; j < L; j++) {

		//Select only class attribute 'j'
		Instances D_j = F.keepLabels(new Instances(D),L,new int[]{j});
		D_j.setClassIndex(0);

		//Build the classifier for that class
		m_MultiClassifiers[j].buildClassifier(D_j);
		if(getDebug()) System.out.print(" " + (D_j.classAttribute().name()));

		m_InstancesTemplates[j] = new Instances(D_j, 0);
	}
}
 
Example #10
Source File: Tuner.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
public ClassifierResults evaluateParameterSet(AbstractClassifier baseClassifier, Instances trainSet, ParameterSet parameterSet) throws Exception { 
    Instances data = cloneDataIfNeeded(trainSet);
    AbstractClassifier classifier = cloneClassifierIfNeeded(baseClassifier); 
        
    String[] options = parameterSet.toOptionsList();
    classifier.setOptions(options);

    ClassifierResults results = evaluator.evaluate(classifier, data);
    results.setClassifierName("TunedClassifier:"+classifierName);
    results.setDatasetName(datasetName);
    results.setFoldID(seed);
    results.setSplit("train");
    results.setParas(parameterSet.toClassifierResultsParaLine(includeMarkersInParaLine));
    
    return results;
}
 
Example #11
Source File: Tuner.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
public ClassifierResults evaluateParameterSetByIndex(AbstractClassifier baseClassifier, Instances trainSet, ParameterSpace parameterSpace, int parameterIndex) throws Exception { 
    classifierName = baseClassifier.getClass().getSimpleName();
    datasetName = trainSet.relationName();
    
    searcher.setParameterSpace(parameterSpace);
    Iterator<ParameterSet> iter = searcher.iterator();
    
    //iterate up to the specified parameter
    int id = 0;
    while (iter.hasNext()) {
        ParameterSet pset = iter.next();
        if (id++ == parameterIndex) {
            //para found, evaluate it and return the results
            ClassifierResults results = evaluateParameterSet(baseClassifier, trainSet, pset);
            return results;
        }
    }
    
    return null; //todo, this should probs be an exception throw instead, tbd
}
 
Example #12
Source File: RAkEL.java    From meka with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void buildClassifier(Instances D) throws Exception {
	testCapabilities(D);

	int L = D.classIndex();
	Random random = new Random(m_S);


	if (getDebug())
		System.out.println("Building "+m_M+" models of "+m_K+" random subsets:");

	m_InstancesTemplates = new Instances[m_M];
	kMap = new int[m_M][m_K];
	m_Classifiers = AbstractClassifier.makeCopies(m_Classifier,m_M);
	for(int i = 0; i < m_M; i++) {
		kMap[i] = SuperLabelUtils.get_k_subset(L,m_K,random);
		if (getDebug()) 
			System.out.println("\tmodel "+(i+1)+"/"+m_M+": "+Arrays.toString(kMap[i])+", P="+m_P+", N="+m_N);
		Instances D_i = SuperLabelUtils.makePartitionDataset(D,kMap[i],m_P,m_N);
		m_Classifiers[i].buildClassifier(D_i);
		m_InstancesTemplates[i] = new Instances(D_i,0);
	}
}
 
Example #13
Source File: IndependentDimensionEnsemble.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
protected void initialiseModules() throws Exception{
    classifiers = AbstractClassifier.makeCopies(original_model, numChannels);
    classifierNames = new String[numChannels];
    
    //one module for each channel.
    this.modules = new EnsembleModule[numChannels];
    for (int m = 0; m < numChannels; m++){
        classifierNames[m] = classifiers[m].getClass().getSimpleName() +"_"+m;
        modules[m] = new EnsembleModule(classifierNames[m], classifiers[m], "");
        if(priorWeights != null)
            modules[m].priorWeight = priorWeights[m];
    }
    
    weightingScheme.defineWeightings(modules, numClasses);
    votingScheme.trainVotingScheme(modules, numClasses);
}
 
Example #14
Source File: NestedDichotomyUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ClassSplit<String> createGeneralRPNDBasedSplit(final Collection<String> classes, final Collection<String> s1, final Collection<String> s2, final Random rand, final String classifierName, final Instances data) {
	try {
		RPNDSplitter splitter = new RPNDSplitter(rand, AbstractClassifier.forName(classifierName, new String[] {}));
		Collection<Collection<String>> splitAsCollection = null;

		splitAsCollection = splitter.split(classes, s1, s2, data);
		Iterator<Collection<String>> it = splitAsCollection.iterator();
		return new ClassSplit<>(classes, it.next(), it.next());
	} catch (Exception e) {
		logger.error("Unexpected exception occurred while creating an RPND split", e);
	}
	return null;
}
 
Example #15
Source File: CCUpdateable.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
public ULink(int chain[], int j, Instances train) throws Exception {
	this.j = j;

	this.index = chain[j];

	// sort out excludes [4|5,1,0,2,3]
	this.excld = Arrays.copyOfRange(chain,j+1,chain.length); 
	// sort out excludes [0,1,2,3,5]
	Arrays.sort(this.excld); 

	this.classifier = (AbstractClassifier)AbstractClassifier.forName(getClassifier().getClass().getName(),((AbstractClassifier)getClassifier()).getOptions());

	Instances new_train = new Instances(train);

	// delete all except one (leaving a binary problem)
	if(getDebug()) System.out.print(" "+this.index);
	new_train.setClassIndex(-1); 
	// delete all the attributes (and track where our index ends up)
	this.value = chain[j];
	int c_index = value; 
	for(int i = excld.length-1; i >= 0; i--) {
		new_train.deleteAttributeAt(excld[i]);
		if (excld[i] < this.index)
			c_index--; 
	}
	new_train.setClassIndex(c_index); 

	_template = new Instances(new_train,0);

	this.classifier.buildClassifier(new_train);
	new_train = null;

	if(j+1 < chain.length) 
		next = new ULink(chain, ++j, train);
}
 
Example #16
Source File: WekaUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Classifier cloneClassifier(final Classifier c) throws Exception {
	Method cloneMethod = MethodUtils.getAccessibleMethod(c.getClass(), "clone");
	if (cloneMethod != null) {
		return (Classifier) cloneMethod.invoke(c);
	}
	return AbstractClassifier.makeCopy(c);
}
 
Example #17
Source File: StrUtils.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
public static AbstractClassifier classifierFromClassName(String name) {
    try {
        return fromOptionValue(name, AbstractClassifier.class);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #18
Source File: RankingByPairwiseComparison.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public void fit(final Instances dataset, final int labels) throws Exception {
	this.labelIndices = getLabelIndices(labels, dataset);
	this.labelIndices.stream().map(x -> dataset.attribute(x).name()).forEach(this.labelSet::add);
	Instances plainPWDataset = this.applyFiltersToDataset(dataset);

	try {
		for (int i = 0; i < this.labelIndices.size() - 1; i++) {
			for (int j = i + 1; j < this.labelIndices.size(); j++) {

				PairWiseClassifier pwc = new PairWiseClassifier();
				pwc.a = dataset.attribute(this.labelIndices.get(i)).name();
				pwc.b = dataset.attribute(this.labelIndices.get(j)).name();

				pwc.c = AbstractClassifier.forName(this.config.getBaseLearner(), null);

				Instances pwDataset = new Instances(plainPWDataset);

				for (int k = 0; k < pwDataset.size(); k++) {
					String value;
					if (dataset.get(k).value(this.labelIndices.get(i)) > dataset.get(k).value(this.labelIndices.get(j))) {
						value = "true";
					} else {
						value = "false";
					}
					pwDataset.get(k).setValue(pwDataset.numAttributes() - 1, value);
				}
				pwDataset.setClassIndex(pwDataset.numAttributes() - 1);

				pwc.c.buildClassifier(pwDataset);
				this.pwClassifiers.add(pwc);
			}
		}
	} catch (Exception e) {
		throw new TrainingException("Could not build ranker", e);
	}
}
 
Example #19
Source File: WekaClassifier.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static WekaClassifier createPipeline(final String searcher, final List<String> searcherOptions, final String evaluator, final List<String> evaluatorOptions, final String classifier, final List<String> classifierOptions)
		throws Exception {
	ASSearch search = ASSearch.forName(searcher, searcherOptions.toArray(new String[0]));
	ASEvaluation eval = ASEvaluation.forName(evaluator, evaluatorOptions.toArray(new String[0]));
	Classifier c = AbstractClassifier.forName(classifier, classifierOptions.toArray(new String[0]));
	return new WekaClassifier(new MLPipeline(search, eval, c));
}
 
Example #20
Source File: WekaClassifier.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public WekaClassifier(final String name, final String[] options) {
	this.name = name;
	try {
		this.wrappedClassifier = AbstractClassifier.forName(name, options);
	} catch (Exception e) {
		throw new IllegalArgumentException("Could not find classifier for name " + name + " or could not set its options to " + Arrays.toString(options), e);
	}
}
 
Example #21
Source File: RAkELd.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void buildClassifier(Instances D) throws Exception {

	int L = D.classIndex();
	int N = D.numInstances();
	Random random = new Random(m_S);

	// Note: a slightly roundabout way of doing it:
	int num = (int)Math.ceil(L / m_K);
	kMap = SuperLabelUtils.generatePartition(A.make_sequence(L),num,random,true);
	m_M = kMap.length;
	m_Classifiers = AbstractClassifier.makeCopies(m_Classifier,m_M);
	m_InstancesTemplates = new Instances[m_M];

	if (getDebug())
		System.out.println("Building "+m_M+" models of "+m_K+" partitions:");

	for(int i = 0; i < m_M; i++) {

		if (getDebug()) 
			System.out.println("\tpartitioning model "+(i+1)+"/"+m_M+": "+Arrays.toString(kMap[i])+", P="+m_P+", N="+m_N);
		Instances D_i = SuperLabelUtils.makePartitionDataset(D,kMap[i],m_P,m_N);
		if (getDebug()) 
			System.out.println("\tbuilding model "+(i+1)+"/"+m_M+": "+Arrays.toString(kMap[i]));

		m_Classifiers[i].buildClassifier(D_i);
		m_InstancesTemplates[i] = new Instances(D_i,0);

	}

}
 
Example #22
Source File: AdvancedCollective.java    From collective-classification-weka-package with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set the base learner. Creates copies of the given classifier for the two
 * classifiers used internally. <br/>
 * Note: also unsets the flag whether the classifier has been built so far.
 *
 * @param newClassifier the classifier to use.
 * @see #m_ClassifierBuilt
 */
public void setClassifier(Classifier newClassifier) {
  super.setClassifier(newClassifier);

  try {
    m_Classifier2 = AbstractClassifier.makeCopies(newClassifier, 1)[0];
  }
  catch (Exception e) {
    e.printStackTrace();
    m_Classifier  = new weka.classifiers.trees.J48();
    m_Classifier2 = new weka.classifiers.trees.J48();
  }
}
 
Example #23
Source File: Evaluation.java    From collective-classification-weka-package with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Evaluates a classifier with the options given in an array of strings.
 * 
 * @param classifierString class of machine learning classifier as a string
 * @param options the array of string containing the options
 * @throws Exception if model could not be evaluated successfully
 * @return a string describing the results
 */
public static String evaluateModel(String classifierString, String[] options) throws Exception {
  Classifier classifier;

  try {
    classifier = AbstractClassifier.forName(classifierString, null);
  } 
  catch (Exception e) {
    throw new Exception("Can't find class with name " + classifierString + '.');
  }

  return evaluateModel(classifier, options);
}
 
Example #24
Source File: CCp.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
public Link(int chain[], int j, Instances train) throws Exception {
	this.j = j;

	this.index = chain[j];

	// sort out excludes [4|5,1,0,2,3]
	this.excld = Arrays.copyOfRange(chain,j+1,chain.length); 
	// sort out excludes [0,1,2,3,5]
	Arrays.sort(this.excld); 

	this.classifier = (AbstractClassifier)AbstractClassifier.forName(getClassifier().getClass().getName(),((AbstractClassifier)getClassifier()).getOptions());

	Instances new_train = new Instances(train);

	// delete all except one (leaving a binary problem)
	if(getDebug()) System.out.print(" "+this.index);
	new_train.setClassIndex(-1); 
	// delete all the attributes (and track where our index ends up)
	int c_index = chain[j]; 
	for(int i = excld.length-1; i >= 0; i--) {
		new_train.deleteAttributeAt(excld[i]);
		if (excld[i] < this.index)
			c_index--; 
	}
	new_train.setClassIndex(c_index); 

	_template = new Instances(new_train,0);

	this.classifier.buildClassifier(new_train);
	new_train = null;

	if(j+1 < chain.length) 
		next = new meka.classifiers.multitarget.CCp.Link(chain, ++j, train);
}
 
Example #25
Source File: AbstractMultiSearch.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set the base learner.
 *
 * @param newClassifier 	the classifier to use.
 */
@Override
public void setClassifier(Classifier newClassifier) {
	super.setClassifier(newClassifier);
	try {
		m_BestClassifier.classifier = AbstractClassifier.makeCopy(m_Classifier);
	}
	catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #26
Source File: MBR.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void buildClassifier(Instances data) throws Exception {
  	testCapabilities(data);
  	
	int c = data.classIndex();

	// Base BR

	if (getDebug()) System.out.println("Build BR Base ("+c+" models)");
	m_BASE = (BR)AbstractClassifier.forName(getClassifier().getClass().getName(),((AbstractClassifier)getClassifier()).getOptions());
	m_BASE.buildClassifier(data);

	// Meta BR

	if (getDebug()) System.out.println("Prepare Meta data           ");
	Instances meta_data = new Instances(data);

	FastVector BinaryClass = new FastVector(c);
	BinaryClass.addElement("0");
	BinaryClass.addElement("1");

	for(int i = 0; i < c; i++) {
		meta_data.insertAttributeAt(new Attribute("metaclass"+i,BinaryClass),c);
	}

	for(int i = 0; i < data.numInstances(); i++) {
		double cfn[] = m_BASE.distributionForInstance(data.instance(i));
		for(int a = 0; a < cfn.length; a++) {
			meta_data.instance(i).setValue(a+c,cfn[a]);
		}
	}

	meta_data.setClassIndex(c);
	m_InstancesTemplate = new Instances(meta_data, 0);

	if (getDebug()) System.out.println("Build BR Meta ("+c+" models)");

	m_META = (BR)AbstractClassifier.forName(getClassifier().getClass().getName(),((AbstractClassifier)getClassifier()).getOptions());
	m_META.buildClassifier(meta_data);
}
 
Example #27
Source File: CNode.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Build - Create transformation for this node, and train classifier of type H upon it.
 * The dataset should have class as index 'j', and remove all indices less than L *not* in paY.
 */
public void build(Instances D, Classifier H) throws Exception {
	// transform data
	T = transform(D);
	// build SLC 'h'
	h = AbstractClassifier.makeCopy(H);
	h.buildClassifier(T);
	// save templates
	//t_ = new SparseInstance(T.numAttributes());
	//t_.setDataset(T);
	//t_.setClassMissing();								// [?,x,x,x]
	T.clear();
}
 
Example #28
Source File: PMCC.java    From meka with GNU General Public License v3.0 5 votes vote down vote up
/**
 * RebuildCC - rebuild a classifier chain 'h_old' to have a new sequence 's_new'.
 */
protected CC rebuildCC(CC h_old, int s_new[], Instances D) throws Exception {

	// make a deep copy
	CC h = (CC)AbstractClassifier.makeCopy(h_old);

	// rebuild this chain
	h.rebuildClassifier(s_new,new Instances(D));
	return h;
}
 
Example #29
Source File: Util.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<Map<String, Object>> conductSingleOneStepReductionExperiment(final ReductionExperiment experiment) throws Exception {
	/* load data */
	Instances data = new Instances(new BufferedReader(new FileReader(experiment.getDataset())));
	data.setClassIndex(data.numAttributes() - 1);

	/* prepare basis for experiments */
	int seed = experiment.getSeed();
	Classifier classifierForRPNDSplit = AbstractClassifier.forName(experiment.getNameOfInnerClassifier(), null);
	Classifier leftClassifier = AbstractClassifier.forName(experiment.getNameOfLeftClassifier(), null);
	Classifier innerClassifier = AbstractClassifier.forName(experiment.getNameOfInnerClassifier(), null);
	Classifier rightClassifier = AbstractClassifier.forName(experiment.getNameOfRightClassifier(), null);

	RPNDSplitter splitter = new RPNDSplitter(new Random(seed), classifierForRPNDSplit);

	/* conduct experiments */
	List<Map<String, Object>> results = new ArrayList<>();
	for (int k = 0; k < 10; k++) {
		List<Collection<String>> classSplit;
		try {
			classSplit = new ArrayList<>(splitter.split(data));
		} catch (Exception e) {
			throw new RuntimeException("Could not create RPND split.", e);
		}
		MCTreeNodeReD classifier = new MCTreeNodeReD(innerClassifier, classSplit.get(0), leftClassifier, classSplit.get(1), rightClassifier);
		long start = System.currentTimeMillis();
		Map<String, Object> result = new HashMap<>();
		List<Instances> dataSplit = WekaUtil.getStratifiedSplit(data, (seed + k), .7);
		classifier.buildClassifier(dataSplit.get(0));
		long time = System.currentTimeMillis() - start;
		Evaluation eval = new Evaluation(dataSplit.get(0));
		eval.evaluateModel(classifier, dataSplit.get(1));
		double loss = (100 - eval.pctCorrect()) / 100f;
		logger.info("Conducted experiment {} with split {}/{}. Loss: {}. Time: {}ms.", k, classSplit.get(0), classSplit.get(1), loss, time);
		result.put("errorRate", loss);
		result.put(LABEL_TRAIN_TIME, time);
		results.add(result);
	}
	return results;
}
 
Example #30
Source File: StackingC.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process options setting meta classifier.
 * 
 * @param options the meta options to parse
 * @throws Exception if parsing fails
 */
protected void processMetaOptions(String[] options) throws Exception {

  String classifierString = Utils.getOption('M', options);
  String [] classifierSpec = Utils.splitOptions(classifierString);
  if (classifierSpec.length != 0) {
    String classifierName = classifierSpec[0];
    classifierSpec[0] = "";
    setMetaClassifier(AbstractClassifier.forName(classifierName, classifierSpec));
  } else {
      ((LinearRegression)(getMetaClassifier())).
 setAttributeSelectionMethod(new 
   weka.core.SelectedTag(1,LinearRegression.TAGS_SELECTION));
  }
}