001 /*
002 * Copyright (C) 2008-2009 Holger Arndt, A. Naegele and M. Bundschus
003 *
004 * This file is part of the Java Data Mining Package (JDMP).
005 * See the NOTICE file distributed with this work for additional
006 * information regarding copyright ownership and licensing.
007 *
008 * JDMP is free software; you can redistribute it and/or modify
009 * it under the terms of the GNU Lesser General Public License as
010 * published by the Free Software Foundation; either version 2
011 * of the License, or (at your option) any later version.
012 *
013 * JDMP is distributed in the hope that it will be useful,
014 * but WITHOUT ANY WARRANTY; without even the implied warranty of
015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016 * GNU Lesser General Public License for more details.
017 *
018 * You should have received a copy of the GNU Lesser General Public
019 * License along with JDMP; if not, write to the
020 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
021 * Boston, MA 02110-1301 USA
022 */
023
024 package org.jdmp.mallet.sample;
025
026 import org.jdmp.core.sample.ClassificationSample;
027 import org.jdmp.core.sample.Sample;
028 import org.jdmp.mallet.matrix.MalletInputMatrix;
029 import org.jdmp.mallet.matrix.MalletOutputMatrix;
030 import org.ujmp.core.interfaces.Wrapper;
031
032 import cc.mallet.types.FeatureVector;
033 import cc.mallet.types.FeatureVectorSequence;
034 import cc.mallet.types.Instance;
035 import cc.mallet.types.LabelSequence;
036
037 public class Instance2Sample extends ClassificationSample implements Wrapper<Instance> {
038 private static final long serialVersionUID = 3834503288309969345L;
039
040 private Instance instance = null;
041
042 private int index = 0;
043
044 public Instance2Sample(Instance instance, int index) {
045 this.instance = instance;
046 this.index = index;
047 Object data = instance.getData();
048 if (data instanceof FeatureVectorSequence) {
049 FeatureVectorSequence fvs = (FeatureVectorSequence) data;
050 setMatrix(INPUT, new MalletInputMatrix(fvs.getFeatureVector(index)));
051 }
052 LabelSequence labelSequence = (LabelSequence) instance.getTarget();
053 setMatrix(Sample.TARGET, new MalletOutputMatrix(labelSequence, index));
054 }
055
056 public Instance getWrappedObject() {
057 return instance;
058 }
059
060 @Override
061 public String getLabel() {
062 Object data = instance.getData();
063 if (data instanceof FeatureVectorSequence) {
064 FeatureVectorSequence fvs = (FeatureVectorSequence) data;
065 FeatureVector fv = fvs.getFeatureVector(index);
066 for (int i = fv.numLocations() - 1; i != -1; i--) {
067 String word = (String) fv.getAlphabet().lookupObject(fv.getIndices()[i]);
068 if (word.startsWith("W=")) {
069 if (!word.matches(".*[0-9]$")) {
070 return word.substring(2);
071 }
072 }
073 }
074 }
075 return null;
076 }
077
078 public void setWrappedObject(Instance object) {
079 this.instance = object;
080 }
081 }