repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/tui/Clusterings2Clusterer.java
package cc.mallet.cluster.tui; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.logging.Logger; import cc.mallet.classify.Classifier; import cc.mallet.classify.MaxEntTrainer; import cc.mallet.classify.Trial; import cc.mallet.cluster.Clusterer; import cc.mallet.cluster.Clustering; import cc.mallet.cluster.Clusterings; import cc.mallet.cluster.GreedyAgglomerativeByDensity; import cc.mallet.cluster.Record; import cc.mallet.cluster.evaluate.AccuracyEvaluator; import cc.mallet.cluster.evaluate.BCubedEvaluator; import cc.mallet.cluster.evaluate.ClusteringEvaluator; import cc.mallet.cluster.evaluate.ClusteringEvaluators; import cc.mallet.cluster.evaluate.MUCEvaluator; import cc.mallet.cluster.evaluate.PairF1Evaluator; import cc.mallet.cluster.iterator.PairSampleIterator; import cc.mallet.cluster.neighbor_evaluator.AgglomerativeNeighbor; import cc.mallet.cluster.neighbor_evaluator.NeighborEvaluator; import cc.mallet.cluster.neighbor_evaluator.PairwiseEvaluator; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.InfoGain; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import cc.mallet.types.LabelAlphabet; import cc.mallet.util.CommandOption; import cc.mallet.util.MalletLogger; import cc.mallet.util.PropertyList; import cc.mallet.util.Randoms; import cc.mallet.util.Strings; //In progress public class Clusterings2Clusterer { private static Logger logger = MalletLogger.getLogger(Clusterings2Clusterer.class.getName()); public static void main(String[] args) throws Exception { CommandOption.setSummary(Clusterings2Clusterer.class, "A tool to train and test a Clusterer."); CommandOption.process(Clusterings2Clusterer.class, args); // TRAIN Randoms random = new Randoms(123); Clusterer clusterer = null; if (!loadClusterer.value.exists()) { Clusterings training = readClusterings(trainingFile.value); Alphabet fieldAlphabet = ((Record) training.get(0).getInstances() .get(0).getData()).fieldAlphabet(); Pipe pipe = new ClusteringPipe(string2ints(exactMatchFields.value, fieldAlphabet), string2ints(approxMatchFields.value, fieldAlphabet), string2ints(substringMatchFields.value, fieldAlphabet)); InstanceList trainingInstances = new InstanceList(pipe); for (int i = 0; i < training.size(); i++) { PairSampleIterator iterator = new PairSampleIterator(training .get(i), random, 0.5, training.get(i).getNumInstances()); while(iterator.hasNext()) { Instance inst = iterator.next(); trainingInstances.add(pipe.pipe(inst)); } } logger.info("generated " + trainingInstances.size() + " training instances"); Classifier classifier = new MaxEntTrainer().train(trainingInstances); logger.info("InfoGain:\n"); new InfoGain(trainingInstances).printByRank(System.out); logger.info("pairwise training accuracy=" + new Trial(classifier, trainingInstances).getAccuracy()); NeighborEvaluator neval = new PairwiseEvaluator(classifier, "YES", new PairwiseEvaluator.Average(), true); clusterer = new GreedyAgglomerativeByDensity( training.get(0).getInstances().getPipe(), neval, 0.5, false, random); training = null; trainingInstances = null; } else { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(loadClusterer.value)); clusterer = (Clusterer) ois.readObject(); } // TEST Clusterings testing = readClusterings(testingFile.value); ClusteringEvaluator evaluator = (ClusteringEvaluator) clusteringEvaluatorOption.value; if (evaluator == null) evaluator = new ClusteringEvaluators( new ClusteringEvaluator[] { new BCubedEvaluator(), new PairF1Evaluator(), new MUCEvaluator(), new AccuracyEvaluator() }); ArrayList<Clustering> predictions = new ArrayList<Clustering>(); for (int i = 0; i < testing.size(); i++) { Clustering clustering = testing.get(i); Clustering predicted = clusterer.cluster(clustering.getInstances()); predictions.add(predicted); logger.info(evaluator.evaluate(clustering, predicted)); } logger.info(evaluator.evaluateTotals()); // WRITE OUTPUT ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(saveClusterer.value)); oos.writeObject(clusterer); oos.close(); if (outputClusterings.value != null) { BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputClusterings.value))); writer.write(predictions.toString()); writer.flush(); writer.close(); } } public static int[] string2ints(String[] ss, Alphabet alph) { int[] ret = new int[ss.length]; for (int i = 0; i < ss.length; i++) ret[i] = alph.lookupIndex(ss[i]); return ret; } public static Clusterings readClusterings(String f) throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream( new File(f))); return (Clusterings) ois.readObject(); } static CommandOption.File loadClusterer = new CommandOption.File( Clusterings2Clusterer.class, "load-clusterer", "FILE", false, null, "The file from which to read the clusterer.", null); static CommandOption.File saveClusterer = new CommandOption.File( Clusterings2Clusterer.class, "save-clusterer", "FILE", false, new File("clusterer.mallet"), "The filename in which to write the clusterer after it has been trained.", null); static CommandOption.String outputClusterings = new CommandOption.String( Clusterings2Clusterer.class, "output-clusterings", "FILENAME", false, "predictions", "The filename in which to write the predicted clusterings.", null); static CommandOption.String trainingFile = new CommandOption.String( Clusterings2Clusterer.class, "train", "FILENAME", false, "text.clusterings.train", "Read the training set Clusterings from this file. " + "If this is specified, the input file parameter is ignored", null); static CommandOption.String testingFile = new CommandOption.String( Clusterings2Clusterer.class, "test", "FILENAME", false, "text.clusterings.test", "Read the test set Clusterings from this file. " + "If this option is specified, the training-file parameter must be specified and " + " the input-file parameter is ignored", null); static CommandOption.Object clusteringEvaluatorOption = new CommandOption.Object( Clusterings2Clusterer.class, "clustering-evaluator", "CONSTRUCTOR", true, null, "Java code for constructing a ClusteringEvaluator object", null); static CommandOption.SpacedStrings exactMatchFields = new CommandOption.SpacedStrings( Clusterings2Clusterer.class, "exact-match-fields", "STRING...", false, null, "The field names to be checked for exactly matching values", null); static CommandOption.SpacedStrings approxMatchFields = new CommandOption.SpacedStrings( Clusterings2Clusterer.class, "approx-match-fields", "STRING...", false, null, "The field names to be checked for approx matching values", null); static CommandOption.SpacedStrings substringMatchFields = new CommandOption.SpacedStrings( Clusterings2Clusterer.class, "substring-match-fields", "STRING...", false, null, "The field names to be checked for substring matching values. Note that values fewer than 3 characters are ignored.", null); public static class ClusteringPipe extends Pipe { private static final long serialVersionUID = 1L; int[] exactMatchFields; int[] approxMatchFields; int[] substringMatchFields; double approxMatchThreshold; public ClusteringPipe(int[] exactMatchFields, int[] approxMatchFields, int[] substringMatchFields) { super(new Alphabet(), new LabelAlphabet()); this.exactMatchFields = exactMatchFields; this.approxMatchFields = approxMatchFields; this.substringMatchFields = substringMatchFields; } private Record[] array2Records(int[] a, InstanceList list) { ArrayList<Record> records = new ArrayList<Record>(); for (int i = 0; i < a.length; i++) records.add((Record) list.get(a[i]).getData()); return (Record[]) records.toArray(new Record[] {}); } public Instance pipe(Instance carrier) { AgglomerativeNeighbor neighbor = (AgglomerativeNeighbor) carrier .getData(); Clustering original = neighbor.getOriginal(); int[] cluster1 = neighbor.getOldClusters()[0]; int[] cluster2 = neighbor.getOldClusters()[1]; InstanceList list = original.getInstances(); int[] mergedIndices = neighbor.getNewCluster(); Record[] records = array2Records(mergedIndices, list); Alphabet fieldAlph = records[0].fieldAlphabet(); Alphabet valueAlph = records[0].valueAlphabet(); PropertyList features = null; features = addExactMatch(records, fieldAlph, valueAlph, features); features = addApproxMatch(records, fieldAlph, valueAlph, features); features = addSubstringMatch(records, fieldAlph, valueAlph, features); carrier .setData(new FeatureVector(getDataAlphabet(), features, true)); LabelAlphabet ldict = (LabelAlphabet) getTargetAlphabet(); String label = (original.getLabel(cluster1[0]) == original .getLabel(cluster2[0])) ? "YES" : "NO"; carrier.setTarget(ldict.lookupLabel(label)); return carrier; } private PropertyList addExactMatch(Record[] records, Alphabet fieldAlph, Alphabet valueAlph, PropertyList features) { for (int fi = 0; fi < exactMatchFields.length; fi++) { int matches = 0; int comparisons = 0; for (int i = 0; i < records.length && exactMatchFields.length > 0; i++) { FeatureVector valsi = records[i] .values(exactMatchFields[fi]); for (int j = i + 1; j < records.length && valsi != null; j++) { FeatureVector valsj = records[j] .values(exactMatchFields[fi]); if (valsj != null) { comparisons++; for (int ii = 0; ii < valsi.numLocations(); ii++) { if (valsj.contains(valueAlph.lookupObject(valsi .indexAtLocation(ii)))) { matches++; break; } } } } if (matches == comparisons && comparisons > 1) features = PropertyList.add(fieldAlph .lookupObject(exactMatchFields[fi]) + "_all_match", 1.0, features); if (matches > 0) features = PropertyList.add(fieldAlph .lookupObject(exactMatchFields[fi]) + "_exists_match", 1.0, features); } } return features; } private PropertyList addApproxMatch(Record[] records, Alphabet fieldAlph, Alphabet valueAlph, PropertyList features) { for (int fi = 0; fi < approxMatchFields.length; fi++) { int matches = 0; int comparisons = 0; for (int i = 0; i < records.length && approxMatchFields.length > 0; i++) { FeatureVector valsi = records[i] .values(approxMatchFields[fi]); for (int j = i + 1; j < records.length && valsi != null; j++) { FeatureVector valsj = records[j] .values(approxMatchFields[fi]); if (valsj != null) { comparisons++; for (int ii = 0; ii < valsi.numLocations(); ii++) { String si = (String) valueAlph .lookupObject(valsi.indexAtLocation(ii)); for (int jj = 0; jj < valsj.numLocations(); jj++) { String sj = (String) valueAlph .lookupObject(valsj .indexAtLocation(jj)); if (Strings.levenshteinDistance(si, sj) < approxMatchThreshold) { matches++; break; } } } } } if (matches == comparisons && comparisons > 1) features = PropertyList.add(fieldAlph .lookupObject(approxMatchFields[fi]) + "_all_approx_match", 1.0, features); if (matches > 0) features = PropertyList.add(fieldAlph .lookupObject(approxMatchFields[fi]) + "_exists_approx_match", 1.0, features); } } return features; } private PropertyList addSubstringMatch(Record[] records, Alphabet fieldAlph, Alphabet valueAlph, PropertyList features) { for (int fi = 0; fi < substringMatchFields.length; fi++) { int matches = 0; int comparisons = 0; for (int i = 0; i < records.length && substringMatchFields.length > 0; i++) { FeatureVector valsi = records[i] .values(substringMatchFields[fi]); for (int j = i + 1; j < records.length && valsi != null; j++) { FeatureVector valsj = records[j] .values(substringMatchFields[fi]); if (valsj != null) { comparisons++; for (int ii = 0; ii < valsi.numLocations(); ii++) { String si = (String) valueAlph .lookupObject(valsi.indexAtLocation(ii)); if (si.length() < 2) break; for (int jj = 0; jj < valsj.numLocations(); jj++) { String sj = (String) valueAlph .lookupObject(valsj .indexAtLocation(jj)); if (sj.length() > 2 && (si.contains(si) || sj.contains(si))) { matches++; break; } } } } } if (matches == comparisons && comparisons > 1) features = PropertyList.add(fieldAlph .lookupObject(exactMatchFields[fi]) + "_all_substring_match", 1.0, features); if (matches > 0) features = PropertyList.add(fieldAlph .lookupObject(exactMatchFields[fi]) + "_exists_substring_match", 1.0, features); } } return features; } } }
13,666
33.953964
127
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/tui/Clusterings2Clusterings.java
package cc.mallet.cluster.tui; import gnu.trove.TIntHashSet; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.logging.Logger; import cc.mallet.cluster.Clustering; import cc.mallet.cluster.Clusterings; import cc.mallet.cluster.util.ClusterUtils; import cc.mallet.pipe.Noop; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import cc.mallet.types.LabelAlphabet; import cc.mallet.util.CommandOption; import cc.mallet.util.MalletLogger; import cc.mallet.util.Randoms; // In progress public class Clusterings2Clusterings { private static Logger logger = MalletLogger.getLogger(Clusterings2Clusterings.class.getName()); public static void main (String[] args) { CommandOption .setSummary(Clusterings2Clusterings.class, "A tool to manipulate Clusterings."); CommandOption.process(Clusterings2Clusterings.class, args); Clusterings clusterings = null; try { ObjectInputStream iis = new ObjectInputStream(new FileInputStream(inputFile.value)); clusterings = (Clusterings) iis.readObject(); } catch (Exception e) { System.err.println("Exception reading clusterings from " + inputFile.value + " " + e); e.printStackTrace(); } logger.info("number clusterings=" + clusterings.size()); // Prune clusters based on size. if (minClusterSize.value > 1) { for (int i = 0; i < clusterings.size(); i++) { Clustering clustering = clusterings.get(i); InstanceList oldInstances = clustering.getInstances(); Alphabet alph = oldInstances.getDataAlphabet(); LabelAlphabet lalph = (LabelAlphabet) oldInstances.getTargetAlphabet(); if (alph == null) alph = new Alphabet(); if (lalph == null) lalph = new LabelAlphabet(); Pipe noop = new Noop(alph, lalph); InstanceList newInstances = new InstanceList(noop); for (int j = 0; j < oldInstances.size(); j++) { int label = clustering.getLabel(j); Instance instance = oldInstances.get(j); if (clustering.size(label) >= minClusterSize.value) newInstances.add(noop.pipe(new Instance(instance.getData(), lalph.lookupLabel(new Integer(label)), instance.getName(), instance.getSource()))); } clusterings.set(i, createSmallerClustering(newInstances)); } if (outputPrefixFile.value != null) { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outputPrefixFile.value)); oos.writeObject(clusterings); oos.close(); } catch (Exception e) { logger.warning("Exception writing clustering to file " + outputPrefixFile.value + " " + e); e.printStackTrace(); } } } // Split into training/testing if (trainingProportion.value > 0) { if (clusterings.size() > 1) throw new IllegalArgumentException("Expect one clustering to do train/test split, not " + clusterings.size()); Clustering clustering = clusterings.get(0); int targetTrainSize = (int)(trainingProportion.value * clustering.getNumInstances()); TIntHashSet clustersSampled = new TIntHashSet(); Randoms random = new Randoms(123); LabelAlphabet lalph = new LabelAlphabet(); InstanceList trainingInstances = new InstanceList(new Noop(null, lalph)); while (trainingInstances.size() < targetTrainSize) { int cluster = random.nextInt(clustering.getNumClusters()); if (!clustersSampled.contains(cluster)) { clustersSampled.add(cluster); InstanceList instances = clustering.getCluster(cluster); for (int i = 0; i < instances.size(); i++) { Instance inst = instances.get(i); trainingInstances.add(new Instance(inst.getData(), lalph.lookupLabel(new Integer(cluster)), inst.getName(), inst.getSource())); } } } trainingInstances.shuffle(random); Clustering trainingClustering = createSmallerClustering(trainingInstances); InstanceList testingInstances = new InstanceList(null, lalph); for (int i = 0; i < clustering.getNumClusters(); i++) { if (!clustersSampled.contains(i)) { InstanceList instances = clustering.getCluster(i); for (int j = 0; j < instances.size(); j++) { Instance inst = instances.get(j); testingInstances.add(new Instance(inst.getData(), lalph.lookupLabel(new Integer(i)), inst.getName(), inst.getSource())); } } } testingInstances.shuffle(random); Clustering testingClustering = createSmallerClustering(testingInstances); logger.info(outputPrefixFile.value + ".train : " + trainingClustering.getNumClusters() + " objects"); logger.info(outputPrefixFile.value + ".test : " + testingClustering.getNumClusters() + " objects"); if (outputPrefixFile.value != null) { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(outputPrefixFile.value + ".train"))); oos.writeObject(new Clusterings(new Clustering[]{trainingClustering})); oos.close(); oos = new ObjectOutputStream(new FileOutputStream(new File(outputPrefixFile.value + ".test"))); oos.writeObject(new Clusterings(new Clustering[]{testingClustering})); oos.close(); } catch (Exception e) { logger.warning("Exception writing clustering to file " + outputPrefixFile.value + " " + e); e.printStackTrace(); } } } } private static Clustering createSmallerClustering (InstanceList instances) { Clustering c = ClusterUtils.createSingletonClustering(instances); return ClusterUtils.mergeInstancesWithSameLabel(c); } static CommandOption.String inputFile = new CommandOption.String( Clusterings2Clusterings.class, "input", "FILENAME", true, "text.clusterings", "The filename from which to read the list of instances.", null); static CommandOption.String outputPrefixFile = new CommandOption.String( Clusterings2Clusterings.class, "output-prefix", "FILENAME", false, "text.clusterings", "The filename prefix to write output. Suffices 'train' and 'test' appended.", null); static CommandOption.Integer minClusterSize = new CommandOption.Integer(Clusterings2Clusterings.class, "min-cluster-size", "INTEGER", false, 1, "Remove clusters with fewer than this many Instances.", null); static CommandOption.Double trainingProportion = new CommandOption.Double(Clusterings2Clusterings.class, "training-proportion", "DOUBLE", false, 0.0, "Split into training and testing, with this percentage of instances reserved for training.", null); }
7,214
38.211957
149
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/AccuracyEvaluator.java
package cc.mallet.cluster.evaluate; import cc.mallet.cluster.Clustering; /** * Accuracy of a clustering is (truePositive + trueNegative) / (numberPairwiseComparisons) * @author culotta * */ public class AccuracyEvaluator extends ClusteringEvaluator { int correctTotal; int comparisonsTotal; public AccuracyEvaluator () { correctTotal = comparisonsTotal = 0; } public String evaluate (Clustering truth, Clustering predicted) { return "accuracy=" + String.valueOf(getEvaluationScores(truth, predicted)[0]); } public String evaluateTotals () { return ("accuracy=" + ((double)correctTotal / comparisonsTotal)); } @Override public double[] getEvaluationScores(Clustering truth, Clustering predicted) { int correct = 0; int comparisons = 0; for (int i = 0; i < truth.getNumInstances(); i++) for (int j = i + 1; j < truth.getNumInstances(); j++) { if ((truth.getLabel(i) == truth.getLabel(j)) == (predicted.getLabel(i) == predicted.getLabel(j))) correct++; comparisons++; } this.correctTotal += correct; this.comparisonsTotal += comparisons; return new double[]{(double)correct / comparisons}; } }
1,163
23.765957
90
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/ClusteringEvaluators.java
package cc.mallet.cluster.evaluate; import cc.mallet.cluster.Clustering; /** * A list of {@link ClusteringEvaluators}. * * @author "Aron Culotta" <[email protected]> * @version 1.0 * @since 1.0 */ public class ClusteringEvaluators extends ClusteringEvaluator { ClusteringEvaluator[] evaluators; public ClusteringEvaluators (ClusteringEvaluator[] evaluators) { this.evaluators = evaluators; } /** * * @param truth * @param predicted * @return A String summarizing the evaluation metric. */ public String evaluate (Clustering truth, Clustering predicted) { String results = ""; for (int i = 0; i < evaluators.length; i++) { String name = evaluators[i].getClass().getName(); results += name.substring(name.lastIndexOf('.') + 1) + ": " + evaluators[i].evaluate(truth, predicted) + "\n"; } return results; } /** * * @return If the ClusteringEvaluator maintains state between calls * to evaluate, this method will return the total evaluation metric * since the first evaluation. */ public String evaluateTotals () { String results = ""; for (int i = 0; i < evaluators.length; i++) { String name = evaluators[i].getClass().getName(); results += name.substring(name.lastIndexOf('.') + 1) + ": " + evaluators[i].evaluateTotals() + "\n"; } return results; } public int size () { return evaluators.length; } @Override public double[] getEvaluationScores(Clustering truth, Clustering predicted) { throw new UnsupportedOperationException("Not yet implemented"); } }
1,563
25.066667
78
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/ClusteringEvaluator.java
package cc.mallet.cluster.evaluate; import cc.mallet.cluster.Clusterer; import cc.mallet.cluster.Clustering; /** * Evaluates a predicted Clustering against a true Clustering. * * @author "Aron Culotta" <[email protected]> * @version 1.0 * @since 1.0 */ public abstract class ClusteringEvaluator { /** * * @param truth * @param predicted * @return A String summarizing the evaluation metric. */ public abstract String evaluate (Clustering truth, Clustering predicted); public String evaluate (Clustering[] truth, Clustering[] predicted) { for (int i = 0; i < truth.length; i++) evaluate(truth[i], predicted[i]); return evaluateTotals(); } public String evaluate (Clustering[] truth, Clusterer clusterer) { for (int i = 0; i < truth.length; i++) evaluate(truth[i], clusterer.cluster(truth[i].getInstances())); return evaluateTotals(); } public abstract double[] getEvaluationScores (Clustering truth, Clustering predicted); /** * * @return If the ClusteringEvaluator maintains state between calls * to evaluate, this method will return the total evaluation metric * since the first evaluation. */ public abstract String evaluateTotals (); }
1,206
25.822222
87
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/MUCEvaluator.java
package cc.mallet.cluster.evaluate; import java.util.HashSet; import cc.mallet.cluster.Clustering; /** * Evaluate a Clustering using the MUC evaluation metric. See Marc * Vilain, John Burger, John Aberdeen, Dennis Connolly, and Lynette * Hirschman. 1995. A model-theoretic coreference scoring scheme. In * Proceedings fo the 6th Message Understanding Conference * (MUC6). 45--52. Morgan Kaufmann. * * Note that MUC more or less ignores singleton clusters. * * @author "Aron Culotta" <[email protected]> * @version 1.0 * @since 1.0 * @see ClusteringEvaluator */ public class MUCEvaluator extends ClusteringEvaluator { int precisionNumerator; int precisionDenominator; int recallNumerator; int recallDenominator; public MUCEvaluator () { precisionNumerator = precisionDenominator = recallNumerator = recallDenominator = 0; } public String evaluate (Clustering truth, Clustering predicted) { double[] vals = getEvaluationScores(truth, predicted); return "pr=" + vals[0] + " re=" + vals[1] + " f1=" + vals[2]; } public String evaluateTotals () { double precision = (double)precisionNumerator / precisionDenominator; double recall = (double)recallNumerator / recallDenominator; return "pr=" + precision + " re=" + recall + " f1=" + (2 * precision * recall / (precision + recall)); } @Override public double[] getEvaluationScores(Clustering truth, Clustering predicted) { // Precision = \sum_i [ |siprime| - |pOfsiprime| ] / \sum_i [ |siprime| - 1 ] // where siprime is a predicted cluster, pOfsiprime is the set of // true clusters that contain elements of siprime. int numerator = 0; int denominator = 0; for (int i = 0; i < predicted.getNumClusters(); i++) { int[] siprime = predicted.getIndicesWithLabel(i); HashSet<Integer> pOfsiprime = new HashSet<Integer>(); for (int j = 0; j < siprime.length; j++) pOfsiprime.add(truth.getLabel(siprime[j])); numerator += siprime.length - pOfsiprime.size(); denominator += siprime.length - 1; } precisionNumerator += numerator; precisionDenominator += denominator; double precision = (double)numerator / denominator; // Recall = \sum_i [ |si| - |pOfsi| ] / \sum_i [ |si| - 1 ] // where si is a true cluster, pOfsi is the set of predicted // clusters that contain elements of si. numerator = denominator = 0; for (int i = 0; i < truth.getNumClusters(); i++) { int[] si = truth.getIndicesWithLabel(i); HashSet<Integer> pOfsi = new HashSet<Integer>(); for (int j = 0; j < si.length; j++) pOfsi.add(new Integer(predicted.getLabel(si[j]))); numerator += si.length - pOfsi.size(); denominator += si.length - 1; } recallNumerator += numerator; recallDenominator += denominator; double recall = (double)numerator / denominator; return new double[]{precision,recall,(2 * precision * recall / (precision + recall))}; } }
2,892
34.716049
106
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/BCubedEvaluator.java
package cc.mallet.cluster.evaluate; import cc.mallet.cluster.Clustering; import cc.mallet.types.InstanceList; /** * Evaluate a Clustering using the B-Cubed evaluation metric. See * Bagga & Baldwin, "Algorithms for scoring coreference chains." * * Unlike other metrics, this evaluation awards points to correct * singleton clusters. * * @author "Aron Culotta" <[email protected]> * @version 1.0 * @since 1.0 * @see ClusteringEvaluator */ public class BCubedEvaluator extends ClusteringEvaluator { double macroPrecision; double macroRecall; int macroNumInstances; public BCubedEvaluator () { macroPrecision = macroRecall = 0.0; macroNumInstances = 0; } public String evaluate (Clustering truth, Clustering predicted) { double[] vals = getEvaluationScores(truth, predicted); return "pr=" + vals[0] + " re=" + vals[1] + " f1=" + vals[2]; } public String evaluateTotals () { double pr = macroPrecision / macroNumInstances; double re = macroRecall / macroNumInstances; double f1 = (2 * pr * re) / (pr + re); return "pr=" + pr + " re=" + re + " f1=" + f1; } @Override public double[] getEvaluationScores(Clustering truth, Clustering predicted) { double precision = 0.0; double recall = 0.0; InstanceList instances = truth.getInstances(); for (int i = 0; i < instances.size(); i++) { int trueLabel = truth.getLabel(i); int predLabel = predicted.getLabel(i); int[] trueIndices = truth.getIndicesWithLabel(trueLabel); int[] predIndices = predicted.getIndicesWithLabel(predLabel); int correct = 0; for (int j = 0; j < predIndices.length; j++) { for (int k = 0; k < trueIndices.length; k++) if (trueIndices[k] == predIndices[j]) correct++; } precision += (double)correct / predIndices.length; recall += (double)correct / trueIndices.length; } macroPrecision += precision; macroRecall += recall; macroNumInstances += instances.size(); precision /= instances.size(); recall /= instances.size(); return new double[]{precision, recall, (2 * precision * recall / (precision + recall))}; } }
2,105
27.849315
90
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/PairF1Evaluator.java
package cc.mallet.cluster.evaluate; import cc.mallet.cluster.Clustering; /** * Evaluates two clustering using pairwise comparisons. For each pair * of Instances, compute false positives and false negatives as in * classification performance, determined by whether the pair should * be in the same cluster or not. * * @author "Aron Culotta" <[email protected]> * @version 1.0 * @since 1.0 * @see ClusteringEvaluator */ public class PairF1Evaluator extends ClusteringEvaluator { int tpTotal, fnTotal, fpTotal; public PairF1Evaluator () { tpTotal = fnTotal = fpTotal = 0; } public String evaluate (Clustering truth, Clustering predicted) { double[] vals = getEvaluationScores(truth, predicted); return "pr=" + vals[0] + " re=" + vals[1] + " f1=" + vals[2]; } public String evaluateTotals () { double prTotal = (double)tpTotal / (tpTotal+fpTotal); double recTotal = (double)tpTotal / (tpTotal+fnTotal); double f1Total = 2*prTotal*recTotal/(prTotal+recTotal); return "pr=" + prTotal + " re=" + recTotal + " f1=" + f1Total; } @Override public double[] getEvaluationScores(Clustering truth, Clustering predicted) { int tp, fn, fp; tp = fn = fp = 0; for (int i = 0; i < predicted.getNumClusters(); i++) { int[] predIndices = predicted.getIndicesWithLabel(i); for (int j = 0; j < predIndices.length; j++) for (int k = j + 1; k < predIndices.length; k++) if (truth.getLabel(predIndices[j]) == truth.getLabel(predIndices[k])) tp++; else fp++; } for (int i = 0; i < truth.getNumClusters(); i++) { int[] trueIndices = truth.getIndicesWithLabel(i); for (int j = 0; j < trueIndices.length; j++) for (int k = j + 1; k < trueIndices.length; k++) if (predicted.getLabel(trueIndices[j]) != predicted.getLabel(trueIndices[k])) fn++; } double pr = (double)tp / (tp+fp); double rec = (double)tp / (tp+fn); double f1 = 2*pr*rec/(pr+rec); this.tpTotal += tp; this.fpTotal += fp; this.fnTotal += fn; return new double[]{pr, rec, f1}; } }
2,059
28.428571
82
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/cluster/evaluate/tests/TestClusteringEvaluators.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.cluster.evaluate.tests; import cc.mallet.cluster.Clustering; import cc.mallet.cluster.evaluate.*; import cc.mallet.types.InstanceList; import cc.mallet.util.Randoms; import junit.framework.*; /** * Examples drawn from Luo, "On Coreference Resolution Performance * Metrics", HLT 2005. * * @author "Aron Culotta" <[email protected]> * @version 1.0 * @since 1.0 * @see TestCase */ public class TestClusteringEvaluators extends TestCase { public TestClusteringEvaluators (String name) { super (name); } private Clustering generateTruth (InstanceList instances) { int[] labels = new int[]{0,0,0,0,0,1,1,2,2,2,2,2}; return new Clustering(instances, 3, labels); } private Clustering[] generatePredicted (InstanceList instances) { Clustering[] clusterings = new Clustering[4]; clusterings[0] = new Clustering(instances, 2, new int[]{0,0,0,0,0,1,1,1,1,1,1,1}); clusterings[1] = new Clustering(instances, 2, new int[]{0,0,0,0,0,1,1,0,0,0,0,0}); clusterings[2] = new Clustering(instances, 1, new int[]{0,0,0,0,0,0,0,0,0,0,0,0}); clusterings[3] = new Clustering(instances, 12, new int[]{0,1,2,3,4,5,6,7,8,9,10,11}); return clusterings; } public void testEvaluators () { InstanceList instances = new InstanceList(new Randoms(1), 100, 2).subList(0,12); System.err.println(instances.size() + " instances"); Clustering truth = generateTruth(instances); System.err.println("truth=" + truth); Clustering[] predicted = generatePredicted(instances); ClusteringEvaluator pweval = new PairF1Evaluator(); ClusteringEvaluator bceval = new BCubedEvaluator(); ClusteringEvaluator muceval = new MUCEvaluator(); for (int i = 0; i < predicted.length; i++) { System.err.println("\npred" + i + "=" + predicted[i]); System.err.println("pairs: " + pweval.evaluate(truth, predicted[i])); System.err.println("bcube: " + bceval.evaluate(truth, predicted[i])); System.err.println(" muc: " + muceval.evaluate(truth, predicted[i])); } System.err.println("totals:"); System.err.println("pairs: " + pweval.evaluateTotals()); System.err.println("bcube: " + bceval.evaluateTotals()); System.err.println(" muc: " + muceval.evaluateTotals()); assertTrue(pweval.evaluateTotals().matches(".*f1=0\\.5550.*")); assertTrue(bceval.evaluateTotals().matches(".*f1=0\\.7404.*")); assertTrue(muceval.evaluateTotals().matches(".*f1=0\\.8059.*")); } public static Test suite () { return new TestSuite (TestClusteringEvaluators.class); } protected void setUp () { } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } }
3,055
32.217391
87
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/AugmentableFeatureVectorAddConjunctions.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.*; import java.io.*; import cc.mallet.types.*; /** * Add specified conjunctions to each instance. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class AugmentableFeatureVectorAddConjunctions extends Pipe implements Serializable { FeatureConjunction.List conjunctions; public AugmentableFeatureVectorAddConjunctions () { conjunctions = new FeatureConjunction.List (); } public AugmentableFeatureVectorAddConjunctions addConjunction (String name, Alphabet v, int[] features, boolean[] negations) { conjunctions.add (new FeatureConjunction (name, v, features, negations)); return this; } public Instance pipe (Instance carrier) { AugmentableFeatureVector afv = (AugmentableFeatureVector) carrier.getData(); conjunctions.addTo (afv, 1.0); return carrier; } }
1,341
26.958333
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Array2FeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.logging.*; import java.lang.reflect.Array; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; import cc.mallet.types.Labeling; import cc.mallet.util.MalletLogger; /** Converts a Java array of numerical types to a FeatureVector, where the Alphabet is the data array index wrapped in an Integer object. @author Jerod Weinman <A HREF="mailto:[email protected]">[email protected]</A> */ public class Array2FeatureVector extends Pipe { private static Logger logger = MalletLogger.getLogger(Array2FeatureVector.class.getName()); public Array2FeatureVector(int capacity) { this.dataAlphabet = new Alphabet(capacity); } public Array2FeatureVector() { this(1000); } /** Construct a pipe based on the dimensions of the data and target. */ public Array2FeatureVector( Alphabet dataAlphabet, Alphabet targetAlphabet ) { this.dataAlphabet = dataAlphabet; this.targetAlphabet = targetAlphabet; } /** Convert the data in an <CODE>Instance</CODE> from an array to a <CODE>FeatureVector</CODE> leaving other fields unchanged. <CODE>Instance.getData()</CODE> must return a numeric array, and it is cast to <CODE>double[]</CODE> @throws IllegalStateException If <CODE>Instance.getTarget()</CODE> is not a Labeling */ public Instance pipe( Instance carrier ) throws IllegalStateException { int dataLength = Array.getLength( carrier.getData() ); if ( dataLength > dataAlphabet.size() ) for (int k=dataAlphabet.size() ; k<dataLength ; k++ ) dataAlphabet.lookupIndex( new Integer(k) , true ); // 'add' FeatureVector fv = new FeatureVector( dataAlphabet, (double[])carrier.getData() ); // Check if we've set the target alphabet member if (targetAlphabet == null) { if (carrier.getTarget() instanceof Labeling) targetAlphabet = ((Labeling)carrier.getTarget()).getLabelAlphabet(); else throw new IllegalStateException ("Instance target is not a " + "Labeling; it is a " + carrier.getTarget().getClass().getName()); } carrier.setData( fv ); return carrier; /*return new Instance( fv, carrier.getTarget(), carrier.getName(), carrier.getSource(), this );*/ } /** Current size of the Vocabulary */ public int size() { return dataAlphabet.size(); } }
2,805
26.782178
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SGML2TokenSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import java.net.URI; import java.util.regex.*; import java.util.logging.Logger; import cc.mallet.extract.StringSpan; import cc.mallet.extract.StringTokenization; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.Lexer; import cc.mallet.util.MalletLogger; /** Converts a string containing simple SGML tags into a dta TokenSequence of words, paired with a target TokenSequence containing the SGML tags in effect for each word. It does not handle nested SGML tags, nor gracefully handle malformed SGML. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class SGML2TokenSequence extends Pipe implements Serializable { private static Logger logger = MalletLogger.getLogger (SGML2TokenSequence.class.getName()); Pattern sgmlPattern = Pattern.compile ("</?([^>]*)>"); CharSequenceLexer lexer; String backgroundTag; private boolean saveSource = true; public SGML2TokenSequence (CharSequenceLexer lexer, String backgroundTag, boolean saveSource) { this.lexer = lexer; this.backgroundTag = backgroundTag; this.saveSource = saveSource; } public SGML2TokenSequence (CharSequenceLexer lexer, String backgroundTag) { this.lexer = lexer; this.backgroundTag = backgroundTag; } public SGML2TokenSequence (String regex, String backgroundTag) { this.lexer = new CharSequenceLexer (regex); this.backgroundTag = backgroundTag; } public SGML2TokenSequence () { this (new CharSequenceLexer(), "O"); } public Instance pipe (Instance carrier) { CharSequence string = (CharSequence) carrier.getData(); StringTokenization dataTokens = new StringTokenization (string); TokenSequence targetTokens = new TokenSequence (); String tag = backgroundTag; String nextTag = backgroundTag; Matcher m = sgmlPattern.matcher (string); int textStart = 0; int textEnd = 0; int nextStart = 0; boolean done = false; logger.fine(sgmlPattern.pattern()); logger.finer(string.toString()); while (!done) { done = !(m.find()); if (done) textEnd = string.length(); // culotta: changed from string.length()-1 else { String sgml = m.group(); logger.finer ("SGML = "+sgml); int groupCount = m.groupCount(); logger.finer(Integer.toString (groupCount)); if (sgml.charAt(1) == '/') nextTag = backgroundTag; else{ //nextTag = m.group(0); nextTag = sgml.substring(1, sgml.length()-1); } logger.finer("nextTag: " + nextTag); nextStart = m.end(); // m.end returns one beyond index of last match char textEnd = m.start(); // String.subtring does not include index end logger.finer ("Text start/end "+textStart+" "+textEnd); } if (textEnd - textStart > 0) { logger.finer ("Tag = "+tag); logger.finer ("Target = "+string.subSequence (textStart, textEnd)); lexer.setCharSequence (string.subSequence (textStart, textEnd)); while (lexer.hasNext()) { lexer.next (); int tokStart = textStart + lexer.getStartOffset (); int tokEnd = textStart + lexer.getEndOffset (); dataTokens.add (new StringSpan (string, tokStart, tokEnd)); targetTokens.add (new Token (tag)); } } textStart = nextStart; tag = nextTag; } carrier.setData(dataTokens); carrier.setTarget(targetTokens); if (saveSource) carrier.setSource(dataTokens); return carrier; } public static void main (String[] args) { try { Pipe p = new SerialPipes (new Pipe[] { new Input2CharSequence (), new SGML2TokenSequence() // new SGML2TokenSequence (new CharSequenceLexer (Pattern.compile (".")), "O") }); for (int i = 0; i < args.length; i++) { Instance carrier = p.instanceFrom(new Instance (new File(args[i]), null, null, null)); TokenSequence data = (TokenSequence) carrier.getData(); TokenSequence target = (TokenSequence) carrier.getTarget(); logger.finer ("==="); logger.info (args[i]); for (int j = 0; j < data.size(); j++) logger.info (target.get(j).getText()+" "+data.get(j).getText()); } } catch (Exception e) { System.out.println (e); e.printStackTrace(); } } // Serialization private static final long serialVersionUID = 1; // Version history // 1: add save source private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(sgmlPattern); out.writeObject(lexer); out.writeObject(backgroundTag); out.writeBoolean(saveSource); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); sgmlPattern = (Pattern) in.readObject(); lexer = (CharSequenceLexer) in.readObject(); backgroundTag = (String) in.readObject(); if (version == 0) saveSource = true; } }
5,444
28.917582
95
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequenceRemoveNonAlpha.java
package cc.mallet.pipe; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import cc.mallet.types.FeatureSequenceWithBigrams; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.CharSequenceLexer; /* Copyright (C) 2005 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** Remove tokens that contain non-alphabetic characters. * This class is used in conjunction wtih CharSequenceLexer.LEX_NON_WHITESPACE_CLASSES * and FeatureSequenceWithBigrams, which in turn is used by TopicalNGrams. * @author <a href="mailto:[email protected]">Andrew McCallum</a> */ public class TokenSequenceRemoveNonAlpha extends Pipe { boolean markDeletions = false; public TokenSequenceRemoveNonAlpha (boolean markDeletions) { this.markDeletions = markDeletions; } public TokenSequenceRemoveNonAlpha () { this (false); } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); // xxx This doesn't seem so efficient. Perhaps have TokenSequence // use a LinkedList, and remove Tokens from it? -? // But a LinkedList implementation of TokenSequence would be quite inefficient -AKM TokenSequence ret = new TokenSequence (); Token prevToken = null; for (int i = 0; i < ts.size(); i++) { Token t = ts.get(i); String s = t.getText(); if (CharSequenceLexer.LEX_ALPHA.matcher(s).matches()) { ret.add (t); prevToken = t; } else if (markDeletions && prevToken != null) prevToken.setProperty (FeatureSequenceWithBigrams.deletionMark, t.getText()); } carrier.setData(ret); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeBoolean(markDeletions); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); markDeletions = in.readBoolean(); } }
2,475
32.013333
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureValueString2FeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** Convert a String containing space-separated feature-name floating-point-value pairs into a FeatureVector. For example: <pre>length=12 width=1.75 blue temperature=-17.2</pre> Features without a corresponding value (ie those not including the character "=", such as the feature <code>blue</code> here) will be set to 1.0. <p>If a feature occurs more than once in the input string, the values of each occurrence will be added.</p> @author David Mimno and Andrew McCallum */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.FeatureVector; public class FeatureValueString2FeatureVector extends Pipe implements Serializable { public FeatureValueString2FeatureVector (Alphabet dataDict) { super (dataDict, null); } public FeatureValueString2FeatureVector () { super(new Alphabet(), null); } public Instance pipe (Instance carrier) { String[] fields = carrier.getData().toString().split("\\s+"); int numFields = fields.length; Object[] featureNames = new Object[numFields]; double[] featureValues = new double[numFields]; for (int i = 0; i < numFields; i++) { if (fields[i].contains("=")) { String[] subFields = fields[i].split("="); featureNames[i] = subFields[0]; featureValues[i] = Double.parseDouble(subFields[1]); } else { featureNames[i] = fields[i]; featureValues[i] = 1.0; } } carrier.setData(new FeatureVector(getDataAlphabet(), featureNames, featureValues)); return carrier; } }
1,994
27.5
85
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SaveDataInSource.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Instance; /** * Set the source field of each instance to its data field. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class SaveDataInSource extends Pipe implements Serializable { public SaveDataInSource () { } public Instance pipe (Instance carrier) { carrier.setSource (carrier.getData()); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,273
25
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequence2TokenInstances.java
package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; import cc.mallet.types.Instance; import cc.mallet.types.LabelSequence; import cc.mallet.types.TokenSequence; public class TokenSequence2TokenInstances extends Pipe { private class TokenInstanceIterator implements Iterator<Instance> { Iterator<Instance> source; Instance currentInstance = null; TokenSequence currentTokenSequence; int currentIndex; public TokenInstanceIterator (Iterator<Instance> source) { if (source.hasNext()) { currentInstance = source.next(); currentTokenSequence = (TokenSequence) currentInstance.getData(); } currentIndex = 0; } public Instance next () { if (currentIndex >= currentTokenSequence.size()) { currentInstance = source.next(); currentTokenSequence = (TokenSequence) currentInstance.getData(); } Instance ret = new Instance (currentTokenSequence.get(currentIndex), ((LabelSequence)currentInstance.getTarget()).getLabelAtPosition(currentIndex), null, null); currentIndex++; return ret; } public boolean hasNext () { return currentInstance != null && (currentIndex < currentTokenSequence.size() || source.hasNext()); } public void remove () { throw new IllegalStateException ("This iterator does not support remove()."); } } public Iterator<Instance> newIteratorFrom (Iterator<Instance> source) { return new TokenInstanceIterator (source); } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,889
28.53125
105
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SimpleTokenizer.java
package cc.mallet.pipe; import cc.mallet.types.*; import java.util.HashSet; import java.util.ArrayList; import java.io.*; /** * A simple unicode tokenizer that accepts sequences of letters * as tokens. */ public class SimpleTokenizer extends Pipe { public static final int USE_EMPTY_STOPLIST = 0; public static final int USE_DEFAULT_ENGLISH_STOPLIST = 1; protected HashSet<String> stoplist; public SimpleTokenizer(int languageFlag) { stoplist = new HashSet<String>(); if (languageFlag == USE_DEFAULT_ENGLISH_STOPLIST) { // articles stop("the"); stop("a"); stop("an"); // conjunctions stop("and"); stop("or"); // prepositions stop("of"); stop("for"); stop("in"); stop("on"); stop("to"); stop("with"); stop("by"); // definite pronouns stop("this"); stop("that"); stop("these"); stop("those"); stop("some"); stop("other"); // personal pronouns stop("it"); stop("its"); stop("we"); stop("our"); // conjuctions stop("as"); stop("but"); stop("not"); // verbs stop("do"); stop("does"); stop("is"); stop("be"); stop("are"); stop("can"); stop("was"); stop("were"); } } public SimpleTokenizer(File stopfile) { stoplist = new HashSet<String>(); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(stopfile), "UTF-8")); String word = null; while ((word = in.readLine()) != null) { stop(word); } in.close(); } catch (Exception e) { System.err.println("problem loading stoplist: " + e); } } public SimpleTokenizer(HashSet<String> stoplist) { this.stoplist = stoplist; } public SimpleTokenizer deepClone() { return new SimpleTokenizer((HashSet<String>) stoplist.clone()); } public void stop(String word) { stoplist.add(word); } public Instance pipe(Instance instance) { if (instance.getData() instanceof CharSequence) { CharSequence characters = (CharSequence) instance.getData(); ArrayList<String> tokens = new ArrayList<String>(); int[] tokenBuffer = new int[1000]; int length = -1; // Using code points instead of chars allows us // to support extended Unicode, and has no significant // efficiency costs. int totalCodePoints = Character.codePointCount(characters, 0, characters.length()); for (int i=0; i < totalCodePoints; i++) { int codePoint = Character.codePointAt(characters, i); int codePointType = Character.getType(codePoint); if (codePointType == Character.LOWERCASE_LETTER || codePointType == Character.UPPERCASE_LETTER) { length++; tokenBuffer[length] = codePoint; } else if (codePointType == Character.SPACE_SEPARATOR || codePointType == Character.LINE_SEPARATOR || codePointType == Character.PARAGRAPH_SEPARATOR || codePointType == Character.END_PUNCTUATION || codePointType == Character.DASH_PUNCTUATION || codePointType == Character.CONNECTOR_PUNCTUATION || codePointType == Character.START_PUNCTUATION || codePointType == Character.INITIAL_QUOTE_PUNCTUATION || codePointType == Character.FINAL_QUOTE_PUNCTUATION || codePointType == Character.OTHER_PUNCTUATION) { // Things that delimit words if (length != -1) { String token = new String(tokenBuffer, 0, length + 1); if (! stoplist.contains(token)) { tokens.add(token); } length = -1; } } else if (codePointType == Character.COMBINING_SPACING_MARK || codePointType == Character.ENCLOSING_MARK || codePointType == Character.NON_SPACING_MARK || codePointType == Character.TITLECASE_LETTER || codePointType == Character.MODIFIER_LETTER || codePointType == Character.OTHER_LETTER) { // Obscure things that are technically part of words. // Marks are especially useful for Indic scripts. length++; tokenBuffer[length] = codePoint; } else { // Character.DECIMAL_DIGIT_NUMBER // Character.CONTROL // Character.MATH_SYMBOL //System.out.println("type " + codePointType); } } if (length != -1) { String token = new String(tokenBuffer, 0, length + 1); if (! stoplist.contains(token)) { tokens.add(token); } } instance.setData(tokens); } else { throw new IllegalArgumentException("Looking for a CharSequence, found a " + instance.getData().getClass()); } return instance; } static final long serialVersionUID = 1; }
4,545
24.829545
86
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequenceRemoveUUEncodedBlocks.java
package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import cc.mallet.pipe.Pipe; import cc.mallet.types.Instance; public class CharSequenceRemoveUUEncodedBlocks extends Pipe { /** Given a string, remove lines that begin with M and are 61 characters long. Note that there are some UUEncoded blocks that do not match this. I have seen some that are 64 characters long, and have no regular prefix character, but this filter gets most of them in 20 Newsgroups. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public static final Pattern UU_ENCODED_LINE= Pattern.compile ("^M.{60}$"); public CharSequenceRemoveUUEncodedBlocks () { } public Instance pipe (Instance carrier) { String string = ((CharSequence)carrier.getData()).toString(); Matcher m = UU_ENCODED_LINE.matcher(string); carrier.setData(m.replaceAll ("")); return carrier; } //Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { @SuppressWarnings("unused") int version = in.readInt (); } }
1,445
27.352941
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SvmLight2FeatureVectorAndLabel.java
/* Copyright (C) 2010 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; import cc.mallet.types.Label; import cc.mallet.types.LabelAlphabet; /** * This Pipe converts a line in SVMLight format to * a Mallet instance with FeatureVector data and * Label target. The expected format is * * target feature:value feature:value ... * * targets and features can be indices, as in * SVMLight, or Strings. * * Note that if targets and features are indices, * their indices in the data and target Alphabets * may be different, though the data will be * equivalent. * * @author Gregory Druck * */ public class SvmLight2FeatureVectorAndLabel extends Pipe { private static final long serialVersionUID = 1L; public SvmLight2FeatureVectorAndLabel () { super (new Alphabet(), new LabelAlphabet()); } // There is no guarantee that the feature indices in the text // file will be the same as in the pipe. The data should be // exactly the same, however, just permuted. @Override public Instance pipe(Instance carrier) { // we expect the data for each instance to be // a line from the SVMLight format text file String dataStr = (String)carrier.getData(); // ignore comments at the end if (dataStr.contains("#")) { dataStr = dataStr.substring(0, dataStr.indexOf('#')); } String[] terms = dataStr.split("\\s+"); String classStr = terms[0]; // In SVMLight +1 and 1 are the same label. // Adding a special case to normalize... if (classStr.equals("+1")) { classStr = "1"; } Label label = ((LabelAlphabet)getTargetAlphabet()).lookupLabel(classStr, true); carrier.setTarget(label); // the rest are feature-value pairs int numFeatures = terms.length - 1; int[] indices = new int[numFeatures]; double[] values = new double[numFeatures]; for (int termIndex = 1; termIndex < terms.length; termIndex++) { if (!terms[termIndex].equals("")) { String[] s = terms[termIndex].split(":"); String feature = s[0]; indices[termIndex-1] = getDataAlphabet().lookupIndex(feature, true); values[termIndex-1] = Double.parseDouble(s[1]); } } FeatureVector fv = new FeatureVector(getDataAlphabet(), indices, values); carrier.setData(fv); return carrier; } }
2,848
32.916667
83
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureSequenceConvolution.java
/** * */ package cc.mallet.pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureSequence; import cc.mallet.types.Instance; import cc.mallet.types.TokenSequence; /** * @author lmyao * Convert Feature sequence */ public class FeatureSequenceConvolution extends Pipe { /** * */ public FeatureSequenceConvolution() { // TODO Auto-generated constructor stub super(new Alphabet(), null); } /** * construct word co-occurrence features from the original sequence * do combinatoric, n choose 2, can be extended to n choose 3 public void convolution() { int fi = -1; int pre = -1; int i,j; int curLen = length; for(i = 0; i < curLen-1; i++) { for(j = i + 1; j < curLen; j++) { pre = features[i]; fi = features[j]; Object preO = dictionary.lookupObject(pre); Object curO = dictionary.lookupObject(fi); Object coO = preO.toString() + "_" + curO.toString(); add(coO); } } }*/ public Instance pipe (Instance carrier) { FeatureSequence fseq = (FeatureSequence) carrier.getData(); FeatureSequence ret = new FeatureSequence ((Alphabet)getDataAlphabet()); int i,j, curLen; curLen=fseq.getLength(); //first add fseq to ret for(i = 0; i < curLen; i++) { ret.add(fseq.getObjectAtPosition(i)); } //second word co-occurrence int pre, cur; Object coO; for(i = 0; i < curLen-1; i++) { for(j = i + 1; j < curLen; j++) { pre = fseq.getIndexAtPosition(i); cur = fseq.getIndexAtPosition(j); coO = pre + "_" + cur; ret.add(coO); } } if(carrier.isLocked()) { carrier.unLock(); } carrier.setData(ret); return carrier; } }
1,651
20.736842
68
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Directory2FileIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.net.URI; import java.util.Iterator; import java.util.ArrayList; import cc.mallet.pipe.iterator.*; import cc.mallet.types.Instance; import cc.mallet.util.RegexFileFilter; /** * Convert a File object representing a directory into a FileIterator which * iterates over files in the directory matching a pattern and which extracts * a label from each file path to become the target field of the instance. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Directory2FileIterator extends Pipe { FileFilter fileFilter = null; Pattern labelPattern = null; public Directory2FileIterator (FileFilter fileFilter, Pattern labelRegex) { this.fileFilter = fileFilter; this.labelPattern = labelRegex; } public Directory2FileIterator (Pattern absolutePathRegex, Pattern filenameRegex, Pattern labelRegex) { this (new RegexFileFilter (absolutePathRegex, filenameRegex), labelRegex); } public Directory2FileIterator (String filenameRegex) { this (new RegexFileFilter (filenameRegex), null); } public Directory2FileIterator () { // Leave fileFilter == null } public Instance pipe (Instance carrier) { File directory = (File) carrier.getData(); carrier.setData(new FileIterator (directory, fileFilter, labelPattern)); return carrier; } public Iterator pipe (File directory) { return new FileIterator (directory, fileFilter, labelPattern); } public Iterator pipe (URI directory) { return pipe (new File (directory)); } public Iterator pipe (String directory) { return pipe (new File (directory)); } }
2,182
24.682353
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSubsequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.regex.*; import java.io.*; import cc.mallet.types.Instance; /** Given a string, return only the portion of the string inside a regex parenthesized group. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class CharSubsequence extends Pipe implements Serializable { Pattern regex; int groupIndex; // xxx Yipes, this only works for UNIX-style newlines. // Anyone want to generalize it to Windows, etc? public static final Pattern SKIP_HEADER = Pattern.compile ("\\n\\n(.*)\\z", Pattern.DOTALL); public CharSubsequence (Pattern regex, int groupIndex) { this.regex = regex; this.groupIndex = groupIndex; } public CharSubsequence (Pattern regex) { this (regex, 1); } public Instance pipe (Instance carrier) { CharSequence string = (CharSequence) carrier.getData(); Matcher m = regex.matcher(string); if (m.find()) { //System.out.println ("CharSubsequence found match"); carrier.setData(m.group(groupIndex)); return carrier; } else { //System.out.println ("CharSubsequence found no match"); carrier.setData(""); return carrier; } } //Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(regex); out.writeInt(groupIndex); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); regex = (Pattern) in.readObject(); groupIndex = in.readInt(); } }
2,094
26.565789
93
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/BranchingPipe.java
package cc.mallet.pipe; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import cc.mallet.pipe.iterator.EmptyInstanceIterator; import cc.mallet.types.Instance; /** A Pipe that works like a rule list. Evaluate predicate() on each Pipe in the array; * the first one that returns true, call that one ("the called Pipe"), and ignore the * remainder in the array. The called Pipe will then get control of the source * InstanceIterator until it produces an Instance---in other words it will be able to call * next() on the source Pipe as often as necessary to produce an Instance. * You must be very careful that none of the iterators from Pipes in the rule list buffer * any Instances---in other words they shouldn't call next() to pre-gather any Instances * they they themselves don't consume and process immediately. Otherwise, Instances * that should have been processed by some other constituent Pipe could get lost in * this buffering process. * @author Andrew McCallum <[email protected]> */ @ Deprecated //Implementation not yet complete, and seems quite dangerous and error-prone. public class BranchingPipe extends Pipe { ArrayList<Pipe> pipes; public BranchingPipe () { this.pipes = new ArrayList<Pipe> (); } public BranchingPipe (Pipe[] pipes) { this.pipes = new ArrayList<Pipe> (pipes.length); for (int i = 0; i < pipes.length; i++) this.pipes.add (pipes[i]); } public BranchingPipe (Collection<Pipe> pipeList) { pipes = new ArrayList<Pipe> (pipeList); } private class PeekingInstanceIterator implements Iterator<Instance> { Iterator<Instance> source; Instance nextInstance = null; public PeekingInstanceIterator (Iterator<Instance> source) { this.source = source; } public boolean hasNext () { return source.hasNext(); } public Instance peekNext () { if (nextInstance == null && !hasNext()) return null; else if (nextInstance == null) nextInstance = next(); return nextInstance; } public Instance next () { if (nextInstance != null) { Instance tmp = nextInstance; nextInstance = null; return tmp; } else { return source.next(); } } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } } private class GateKeepingInstanceIterator implements Iterator<Instance> { PeekingInstanceIterator source; Pipe testingPipe; public GateKeepingInstanceIterator (PeekingInstanceIterator source, Pipe testingPipe) { this.source = source; this.testingPipe = testingPipe; } public Instance next () { // Make sure this is not an Instance we were supposed to skip. assert (testingPipe.precondition(source.peekNext())); return source.next(); } public boolean hasNext () { return source.hasNext() && testingPipe.precondition(source.peekNext()); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } } private class BranchingInstanceIterator implements Iterator<Instance> { PeekingInstanceIterator source; ArrayList<Iterator<Instance>> iterators; public BranchingInstanceIterator (PeekingInstanceIterator source) { this.source = new PeekingInstanceIterator (source); this.iterators = new ArrayList<Iterator<Instance>>(pipes.size()); for (Pipe p : pipes) iterators.add (new GateKeepingInstanceIterator (source, p)); } public boolean hasNext () { return source.hasNext(); } public Instance next() { Instance input = source.peekNext(); for (int i = 0; i < pipes.size(); i++) { if (pipes.get(i).precondition(input)) { return iterators.get(i).next(); } } throw new IllegalStateException ("Next Instance satisfied none of the branches' preconditions."); } /** Return the @link{Pipe} that processes @link{Instance}s going through this iterator. */ public Pipe getPipe () { return null; } public Iterator<Instance> getSourceIterator () { return source; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } } public Iterator<Instance> newIteratorFrom (Iterator<Instance> source) { if (pipes.size() == 0) return source; Iterator<Instance> ret = pipes.get(0).newIteratorFrom(source); for (int i = 1; i < pipes.size(); i++) ret = pipes.get(i).newIteratorFrom(ret); return ret; } private static void test () { new BranchingPipe (new Pipe[] { new CharSequence2TokenSequence("\\w*") { public boolean skipIfFalse (Instance inst) { return ! (inst instanceof CharSequence); } } }); } }
4,644
33.154412
115
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequence2TokenSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import java.net.URI; import java.util.regex.Pattern; import cc.mallet.extract.StringSpan; import cc.mallet.extract.StringTokenization; import cc.mallet.types.Instance; import cc.mallet.types.SingleInstanceIterator; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.Lexer; /** * Pipe that tokenizes a character sequence. Expects a CharSequence * in the Instance data, and converts the sequence into a token * sequence using the given regex or CharSequenceLexer. * (The regex / lexer should specify what counts as a token.) */ public class CharSequence2TokenSequence extends Pipe implements Serializable { CharSequenceLexer lexer; public CharSequence2TokenSequence (CharSequenceLexer lexer) { this.lexer = lexer; } public CharSequence2TokenSequence (String regex) { this.lexer = new CharSequenceLexer (regex); } public CharSequence2TokenSequence (Pattern regex) { this.lexer = new CharSequenceLexer (regex); } public CharSequence2TokenSequence () { this (new CharSequenceLexer()); } public Instance pipe (Instance carrier) { CharSequence string = (CharSequence) carrier.getData(); lexer.setCharSequence (string); TokenSequence ts = new StringTokenization (string); while (lexer.hasNext()) { lexer.next(); ts.add (new StringSpan (string, lexer.getStartOffset (), lexer.getEndOffset ())); } carrier.setData(ts); return carrier; } public static void main (String[] args) { try { for (int i = 0; i < args.length; i++) { Instance carrier = new Instance (new File(args[i]), null, null, null); SerialPipes p = new SerialPipes (new Pipe[] { new Input2CharSequence (), new CharSequence2TokenSequence(new CharSequenceLexer())}); carrier = p.newIteratorFrom (new SingleInstanceIterator(carrier)).next(); TokenSequence ts = (TokenSequence) carrier.getData(); System.out.println ("==="); System.out.println (args[i]); System.out.println (ts.toString()); } } catch (Exception e) { System.out.println (e); e.printStackTrace(); } } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(lexer); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); lexer = (CharSequenceLexer) in.readObject(); } }
3,139
27.035714
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TargetRememberLastLabel.java
/* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import cc.mallet.types.*; /** * For each position in the target, remember the last non-background * label. Assumes that the target of piped instances is a LabelSequence. * Replaces the target with a LabelsSequence where row 0 is the original * labels, and row 1 is the last label. * * @author Charles Sutton * @version $Id: TargetRememberLastLabel.java,v 1.1 2007/10/22 21:37:39 mccallum Exp $ */ public class TargetRememberLastLabel extends Pipe { private String backgroundLabel; private boolean offset; public TargetRememberLastLabel () { this ("O", true); } /** offset determines how the memory and base sequences will be * aligned. If true, they'll be aligned like this: * <pre> * MEM O O S S S E L * BASE O S S O E L O * </pre> * otherwise, they'll be aligned like this: * <pre> * MEM O S S S E E L * BASE O S S O E L O * </pre> */ public TargetRememberLastLabel (String backgroundLabel, boolean offset) { this.backgroundLabel = backgroundLabel; this.offset = offset; } public Instance pipe(Instance carrier) { LabelSequence lblseq = (LabelSequence) carrier.getTarget (); Labels[] lbls = new Labels [lblseq.size()]; Label lastLabel = lblseq.getLabelAtPosition(0); for (int i = 0; i < lblseq.size(); i++) { Label thisLabel = lblseq.getLabelAtPosition (i); if (offset) lbls [i] = new Labels (new Label[] { thisLabel, lastLabel }); if (!thisLabel.toString().equals (backgroundLabel)) lastLabel = thisLabel; if (!offset) lbls [i] = new Labels (new Label[] { thisLabel, lastLabel }); } carrier.setTarget (new LabelsSequence (lbls)); return carrier; } }
2,169
30
87
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Csv2FeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.logging.*; import java.util.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; import cc.mallet.types.Labeling; import cc.mallet.util.MalletLogger; /** * Converts a string of the form * <tt>feature_1:val_1 feature_2:val_2 ... feature_k:val_k</tt> * into a (sparse) FeatureVector. * * Features with no ":" character are assumed to have value 1.0. * * @author Gary Huang */ public class Csv2FeatureVector extends Pipe { private static Logger logger = MalletLogger.getLogger(Csv2FeatureVector.class.getName()); public Csv2FeatureVector(int capacity) { this.dataAlphabet = new Alphabet(capacity); } public Csv2FeatureVector() { this(1000); } /** * Convert the data in the given <tt>Instance</tt> from a <tt>CharSequence</tt> * of sparse feature-value pairs to a <tt>FeatureVector</tt> */ public Instance pipe(Instance carrier) { CharSequence c = (CharSequence) carrier.getData(); String[] pairs = c.toString().trim().split("\\s+"); int[] keys = new int[pairs.length]; double[] values = new double[pairs.length]; for (int i = 0; i < pairs.length; i++) { int delimIndex = pairs[i].lastIndexOf(":"); if (delimIndex <= 0 || delimIndex == (pairs[i].length()-1)) { keys[i] = dataAlphabet.lookupIndex(pairs[i], true); values[i] = 1.0; } else { keys[i] = dataAlphabet.lookupIndex(pairs[i].substring(0, delimIndex), true); values[i] = Double.parseDouble(pairs[i].substring(delimIndex+1)); } } // [removed code that sorted indices but NOT values -DM] FeatureVector fv = new FeatureVector(dataAlphabet, keys, values); carrier.setData( fv ); return carrier; } }
2,293
30
93
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SimpleTaggerSentence2StringTokenization.java
/* Copyright (C) 2003 University of Pennsylvania. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta */ package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import cc.mallet.extract.StringSpan; import cc.mallet.extract.StringTokenization; import cc.mallet.types.*; /** * This extends {@link SimpleTaggerSentence2TokenSequence} to use * {Slink StringTokenizations} for use with the extract package. */ public class SimpleTaggerSentence2StringTokenization extends SimpleTaggerSentence2TokenSequence{ /** * Creates a new * <code>SimpleTaggerSentence2StringTokenization</code> instance. * By default we include tokens as features. */ public SimpleTaggerSentence2StringTokenization () { super (); } /** * creates a new <code>SimpleTaggerSentence2StringTokenization</code> instance * which includes tokens as features iff the supplied argument is true. */ public SimpleTaggerSentence2StringTokenization (boolean inc) { super (inc); } /** * Takes an instance with data of type String or String[][] and creates * an Instance of type StringTokenization. Each Token in the sequence is * gets the test of the line preceding it and once feature of value 1 * for each "Feature" in the line. For example, if the String[][] is * {{a,b},{c,d,e}} (and target processing is off) then the text would be * "a b" for the first token and "c d e" for the second. Also, the * features "a" and "b" would be set for the first token and "c", "d" and * "e" for the second. The last element in the String[] for the current * token is taken as the target (label), so in the previous example "b" * would have been the label of the first sequence. */ public Instance pipe(Instance carrier) { Object inputData = carrier.getData(); LabelAlphabet labels; LabelSequence target = null; String[][] tokens; StringBuffer source = new StringBuffer(); StringTokenization ts = new StringTokenization(source); if (inputData instanceof String) tokens = parseSentence((String) inputData); else if (inputData instanceof String[][]) tokens = (String[][]) inputData; else throw new IllegalArgumentException("Not a String; got " + inputData); if (isTargetProcessing()) { labels = (LabelAlphabet) getTargetAlphabet(); target = new LabelSequence(labels, tokens.length); } for (int l = 0; l < tokens.length; l++) { int nFeatures; if (isTargetProcessing()) { if (tokens[l].length < 1) throw new IllegalStateException("Missing label at line " + l + " instance " + carrier.getName()); nFeatures = tokens[l].length - 1; target.add(tokens[l][nFeatures]); } else nFeatures = tokens[l].length; int start = source.length(); String word = makeText(tokens[l]); source.append(word + " "); Token tok = new StringSpan(source, start, source.length() - 1); if (setTokensAsFeatures) { for (int f = 0; f < nFeatures; f++) tok.setFeatureValue(tokens[l][f], 1.0); } else { for (int f = 1; f < nFeatures; f++) tok.setFeatureValue(tokens[l][f], 1.0); } ts.add(tok); } carrier.setData(ts); if (isTargetProcessing()) carrier.setTarget(target); return carrier; } // Serialization garbage private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject (ObjectOutputStream out) throws IOException { out.defaultWriteObject (); out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject (); int version = in.readInt (); } }
4,048
30.632813
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequence2FeatureVectorSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.FeatureVectorSequence; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Convert the token sequence in the data field of each instance to a feature vector sequence. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequence2FeatureVectorSequence extends Pipe implements Serializable { boolean augmentable; // Create AugmentableFeatureVector's in the sequence boolean binary; // Create binary (Augmentable)FeatureVector's in the sequence boolean growAlphabet = true; public TokenSequence2FeatureVectorSequence (Alphabet dataDict, boolean binary, boolean augmentable) { super (dataDict, null); this.augmentable = augmentable; this.binary = binary; } public TokenSequence2FeatureVectorSequence (Alphabet dataDict) { this (dataDict, false, false); } public TokenSequence2FeatureVectorSequence (boolean binary, boolean augmentable) { super (new Alphabet(), null); this.augmentable = augmentable; this.binary = binary; } public TokenSequence2FeatureVectorSequence () { this (false, false); } public Instance pipe (Instance carrier) { carrier.setData(new FeatureVectorSequence ((Alphabet)getDataAlphabet(), (TokenSequence)carrier.getData(), binary, augmentable, growAlphabet)); return carrier; } public void setGrowAlphabet(boolean growAlphabet) { this.growAlphabet = growAlphabet; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeBoolean(augmentable); out.writeBoolean(binary); out.writeBoolean(growAlphabet); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); augmentable = in.readBoolean(); binary = in.readBoolean(); // growAlphabet = true; growAlphabet = in.readBoolean(); } }
2,718
28.554348
94
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/PrintInput.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Instance; /** * Print the data field of each instance. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class PrintInput extends Pipe implements Serializable { String prefix = null; PrintStream stream = System.out; public PrintInput (String prefix) { this.prefix = prefix; } public PrintInput () { } public PrintInput (PrintStream out) { stream = out; } public PrintInput(String prefix, PrintStream out) { this.prefix = prefix; stream = out; } public Instance pipe (Instance carrier) { if (prefix != null) stream.print (prefix); stream.println (carrier.getData().toString()); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); prefix = null; stream = System.out; } }
1,620
22.157143
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Filename2CharSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.util.CharSequenceLexer; /** * Given a filename contained in a string, read in contents of file into a CharSequence. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Filename2CharSequence extends Pipe implements Serializable { public Filename2CharSequence () { } public Instance pipe (Instance carrier) { String filename = (String)carrier.getData(); try { carrier.setData(pipe (new BufferedReader (new FileReader (filename)))); } catch (java.io.IOException e) { throw new IllegalArgumentException ("IOException"); } return carrier; } public CharSequence pipe (Reader reader) throws java.io.IOException { final int BUFSIZE = 2048; char[] buf = new char[BUFSIZE]; int count; StringBuffer sb = new StringBuffer (BUFSIZE); do { count = reader.read (buf, 0, BUFSIZE); if (count == -1) break; //System.out.println ("count="+count); sb.append (buf, 0, count); } while (count == BUFSIZE); return sb; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,905
25.84507
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequence2CharNGrams.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.TokenSequence; /** * Transform a character sequence into a token sequence of character N grams. * @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class CharSequence2CharNGrams extends Pipe implements Serializable { int n; boolean distinguishBorders = false; static char startBorderChar = '>'; static char endBorderChar = '<'; public CharSequence2CharNGrams (int n, boolean distinguishBorders) { this.n = n; this.distinguishBorders = distinguishBorders; } protected String[] ngramify (CharSequence s) { if (distinguishBorders) s = new StringBuffer().append(startBorderChar).append(s).append(endBorderChar).toString(); int count = s.length() - n; String[] ngrams = new String[count]; for (int i = 0; i < count; i++) ngrams[i] = s.subSequence (i, i+n).toString(); return ngrams; } public Instance pipe (Instance carrier) { if (carrier.getData() instanceof CharSequence) carrier.setData(new TokenSequence (ngramify ((CharSequence)carrier.getData()))); else if (carrier.getData() instanceof TokenSequence) { TokenSequence ts = (TokenSequence) carrier.getData(); TokenSequence ret = new TokenSequence (); for (int i = 0; i < ts.size(); i++) ret.add (ngramify (ts.get(i).getText()).toString()); carrier.setData(ret); } else throw new IllegalArgumentException ("Unhandled type "+carrier.getData().getClass()); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeInt(n); out.writeBoolean(distinguishBorders); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); n = in.readInt(); distinguishBorders = in.readBoolean(); } }
2,563
29.52381
94
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequenceParseFeatureString.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.logging.*; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.MalletLogger; /** Convert the string in each field <code>Token.text</code> to a list of Strings (space delimited). Add each string as a feature to the token. If <code>realValued</code> is true, then treat the position in the list as the feature name and the value as a double. Otherwise, the feature name is the string itself and the value is 1.0. <p> Modified to allow feature names and values to be specified.eg: featureName1=featureValue1 featureName2=featureValue2 ... The name/value separator (here '=') can be specified. <p> * If your data consists of feature/value pairs (eg <code>height=10.7 width=3.6 length=1.7</code>), * use <code>new TokenSequenceParseFeatureString(true, true, "=")</code>. This * format is typically used for sparse data, in which most features are equal to 0 in * any given instance. * <p> * If your data consists only of values, and the position determines which feature * the value is for (eg <code>10.7 3.6 1.7</code>), * use <code>new TokenSequenceParseFeatureString(true)</code>. * This format is typically used for data that has a small number of features * that all have non-zero values most of the time. * <p> * If your data is in the form of named binary indicator variables * (eg <code>yellow quacks has_webbed_feet</code>), use the constructor * <code>new TokenSequenceParseFeatureString(false)</code>. Each token will be * interpreted as the name of a feature, whose value is 1.0. @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequenceParseFeatureString extends Pipe implements Serializable { boolean realValued; // are these real-valued features? boolean specifyFeatureNames; // are the feature names given as well? String nameValueSeparator; // what separates the name from the value? (CAN'T BE WHITESPACE!) /** * @param _realValued interpret each data token as a double, and associate it with a * feature called "Feature#K" where K is the order of the token, starting with 0. * Note that this option is currently ignored if <code>_specifyFeatureNames</code> is true. * @param _specifyFeatureNames interpret each data token as a feature name/value pair, * separated by some delimiter, which is the equals sign ("=") unless otherwise specified. * @param _nameValueSeparator use a string other than = to separate name/value pairs. Colon (":") is * a common choice. Note that this string cannot consist of any whitespace, as the tokens stream * will already have been split. */ public TokenSequenceParseFeatureString (boolean _realValued, boolean _specifyFeatureNames, String _nameValueSeparator) { this.realValued = _realValued; if (_nameValueSeparator.trim().length()==0) { throw new IllegalArgumentException ("nameValueSeparator can't be whitespace"); } nameValueSeparator = _nameValueSeparator; this.specifyFeatureNames = _specifyFeatureNames; } public TokenSequenceParseFeatureString (boolean _realValued, boolean _specifyFeatureNames) { this (_realValued, _specifyFeatureNames, "="); } public TokenSequenceParseFeatureString (boolean _realValued) { this (_realValued, false, "="); } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData (); for (int i=0; i < ts.size(); i++) { Token t = ts.get (i); String[] values = t.getText().split("\\s+"); for (int j=0; j < values.length; j++) { if (specifyFeatureNames) { String[] nameAndValue = values[j].split(nameValueSeparator); if (nameAndValue.length != 2) { // no feature name. use token as feature. t.setFeatureValue ("Token="+values[j], 1.0); } else { t.setFeatureValue (nameAndValue[0], Double.parseDouble (nameAndValue[1])); } } else if (realValued) { t.setFeatureValue ("Feature#" + j, Double.parseDouble (values[j])); } else t.setFeatureValue (values[j], 1.0); } } carrier.setData (ts); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeBoolean (realValued); out.writeBoolean (specifyFeatureNames); out.writeObject (nameValueSeparator); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); realValued = in.readBoolean (); if (version >= CURRENT_SERIAL_VERSION) { specifyFeatureNames = in.readBoolean(); nameValueSeparator = (String)in.readObject(); } } }
5,425
38.897059
121
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SourceLocation2TokenSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.Lexer; /** * Read from File or BufferedRead in the data field and produce a TokenSequence. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class SourceLocation2TokenSequence extends Pipe implements Serializable { CharSequenceLexer lexer; public SourceLocation2TokenSequence (CharSequenceLexer lexer) { this.lexer = lexer; } public Instance pipe (Instance carrier) { try { if (carrier.getData() instanceof File) carrier.setData(pipe ((File)carrier.getData())); else if (carrier.getData() instanceof BufferedReader) carrier.setData(pipe ((BufferedReader)carrier.getData())); else throw new IllegalArgumentException ("Doesn't handle class "+carrier.getClass()); } catch (IOException e) { throw new IllegalArgumentException ("IOException"); } return carrier; } public TokenSequence pipe (File file) throws java.io.FileNotFoundException, java.io.IOException { return pipe (new BufferedReader (new FileReader (file))); } public TokenSequence pipe (BufferedReader br) throws java.io.IOException { final int BUFSIZE = 2048; char[] buf = new char[BUFSIZE]; int count; StringBuffer sb = new StringBuffer (BUFSIZE); do { count = br.read (buf, 0, BUFSIZE); sb.append (buf); } while (count == BUFSIZE); lexer.setCharSequence ((CharSequence)sb); TokenSequence ts = new TokenSequence (); while (lexer.hasNext()) ts.add (new Token ((String) lexer.next())); return ts; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
2,503
27.454545
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/PrintInputAndTarget.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Instance; /** * Print the data and target fields of each instance. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class PrintInputAndTarget extends Pipe implements Serializable { String prefix = null; public PrintInputAndTarget (String prefix) { this.prefix = prefix; } public PrintInputAndTarget () { } public Instance pipe (Instance carrier) { if (prefix != null) System.out.print (prefix); String targetString = "<null>"; if (carrier.getTarget() != null) targetString = carrier.getTarget().toString(); System.out.println ("name: " + carrier.getName() + "\ntarget: " + targetString + "\ninput: " + carrier.getData() // Swapping order, since data often has a newline at the end -DM ); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(prefix); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); prefix = (String) in.readObject(); } }
1,784
26.045455
104
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/AugmentableFeatureVectorLogScale.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.AugmentableFeatureVector; import cc.mallet.types.Instance; /** Given an AugmentableFeatureVector, set those values greater than or equal to 1 to log(value)+1. This is useful when multiple counts should not be treated as independent evidence. */ public class AugmentableFeatureVectorLogScale extends Pipe { public AugmentableFeatureVectorLogScale () { super ((Alphabet)null, null); } public Instance pipe (Instance carrier) { AugmentableFeatureVector afv = (AugmentableFeatureVector)carrier.getData(); double v; for (int i = afv.numLocations() - 1; i >= 0; i--) { v = afv.valueAtLocation (i); if (v >= 1) afv.setValueAtLocation (i, Math.log(v)+1); } return carrier; } }
1,310
28.133333
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/StringAddNewLineDelimiter.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import java.net.URI; import cc.mallet.types.Instance; import cc.mallet.util.CharSequenceLexer; /** * Pipe that can adds special text between lines to explicitly * represent line breaks. */ public class StringAddNewLineDelimiter extends Pipe implements Serializable { String delim; public StringAddNewLineDelimiter (String delim) { this.delim = delim; } public Instance pipe (Instance carrier) { if (!(carrier.getData() instanceof String)) throw new IllegalArgumentException ("Expecting String, got " + carrier.getData().getClass().getName()); String s = (String) carrier.getData(); String newline = System.getProperty ("line.separator"); s = s.replaceAll (newline, delim); carrier.setData (s); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject (delim); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); this.delim = (String) in.readObject (); } }
1,750
28.183333
108
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Target2LabelSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; /** * convert a token sequence in the target field into a label sequence in the target field. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Target2LabelSequence extends Pipe implements Serializable { public Target2LabelSequence () { super (null, new LabelAlphabet()); } public Instance pipe (Instance carrier) { //Object in = carrier.getData(); Object target = carrier.getTarget(); if (target == null) // Do nothing ; else if (target instanceof LabelSequence) ; // Nothing to do else if (target instanceof FeatureSequence) { LabelAlphabet dict = (LabelAlphabet) getTargetAlphabet (); FeatureSequence fs = (FeatureSequence) target; Label[] lbls = new Label[fs.size()]; for (int i = 0; i < fs.size (); i++) { lbls[i] = dict.lookupLabel (fs.getObjectAtPosition (i)); } carrier.setTarget (new LabelSequence (lbls)); } else if (target instanceof TokenSequence) { Alphabet v = getTargetAlphabet (); TokenSequence ts = (TokenSequence) target; int indices[] = new int[ts.size()]; for (int i = 0; i < ts.size(); i++) indices[i] = v.lookupIndex (ts.get(i).getText()); LabelSequence ls = new LabelSequence ((LabelAlphabet)getTargetAlphabet(), indices); carrier.setTarget(ls); } else if (target instanceof LabelsSequence) { LabelAlphabet dict = (LabelAlphabet) getTargetAlphabet (); LabelsSequence lblseq = (LabelsSequence) target; Label[] labelArray = new Label [lblseq.size()]; for (int i = 0; i < lblseq.size(); i++) { Labels lbls = lblseq.getLabels (i); if (lbls.size () != 1) throw new IllegalArgumentException ("Cannot convert Labels at position "+i+" : "+lbls); labelArray[i] = dict.lookupLabel (lbls.get (0).getEntry ()); } LabelSequence ls = new LabelSequence (labelArray); carrier.setTarget (ls); } else { throw new IllegalArgumentException ("Unrecognized target type: "+target); } return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
2,968
31.988889
97
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Token2FeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; /** * convert the property list on a token into a feature vector @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Token2FeatureVector extends Pipe implements Serializable { boolean augmentable; // Create AugmentableFeatureVector's in the sequence boolean binary; // Create binary (Augmentable)FeatureVector's in the sequence public Token2FeatureVector (Alphabet dataDict, boolean binary, boolean augmentable) { super (dataDict, null); this.augmentable = augmentable; this.binary = binary; } public Token2FeatureVector (Alphabet dataDict) { this (dataDict, false, false); } public Token2FeatureVector (boolean binary, boolean augmentable) { super (new Alphabet(), null); this.augmentable = augmentable; this.binary = binary; } public Token2FeatureVector () { this (false, false); } public Instance pipe (Instance carrier) { if (augmentable) carrier.setData(new AugmentableFeatureVector ((Alphabet)getDataAlphabet(), ((Token)carrier.getData()).getFeatures(), binary)); else carrier.setData(new FeatureVector ((Alphabet)getDataAlphabet(), ((Token)carrier.getData()).getFeatures(), binary)); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeBoolean(augmentable); out.writeBoolean(binary); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); augmentable = in.readBoolean(); binary = in.readBoolean(); } }
2,339
27.536585
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequenceNGrams.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Convert the token sequence in the data field to a token sequence of ngrams. @author Don Metzler <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequenceNGrams extends Pipe implements Serializable { int [] gramSizes = null; public TokenSequenceNGrams (int [] sizes) { this.gramSizes = sizes; } public Instance pipe (Instance carrier) { String newTerm = null; TokenSequence tmpTS = new TokenSequence(); TokenSequence ts = (TokenSequence) carrier.getData(); for (int i = 0; i < ts.size(); i++) { Token t = ts.get(i); for(int j = 0; j < gramSizes.length; j++) { int len = gramSizes[j]; if (len <= 0 || len > (i+1)) continue; if (len == 1) { tmpTS.add(t); continue; } newTerm = new String(t.getText()); for(int k = 1; k < len; k++) newTerm = ts.get(i-k).getText() + "_" + newTerm; tmpTS.add(newTerm); } } carrier.setData(tmpTS); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeInt (gramSizes.length); for (int i = 0; i < gramSizes.length; i++) out.writeInt (gramSizes[i]); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); int size = in.readInt(); gramSizes = new int[size]; for (int i = 0; i < size; i++) gramSizes[i] = in.readInt(); } }
2,136
26.050633
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequenceLowercase.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Replace the data string with a lowercased version. * This can improve performance over TokenSequenceLowercase. */ public class CharSequenceLowercase extends Pipe implements Serializable { public Instance pipe (Instance carrier) { if (carrier.getData() instanceof String) { String data = (String) carrier.getData(); carrier.setData(data.toLowerCase()); } else { throw new IllegalArgumentException("CharSequenceLowercase expects a String, found a " + carrier.getData().getClass()); } return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,476
28.54
121
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/MakeAmpersandXMLFriendly.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; // convert & to &amp /** convert & to &amp;amp in tokens of a token sequence @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ public class MakeAmpersandXMLFriendly extends Pipe implements Serializable { public MakeAmpersandXMLFriendly () { } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); for (int i = 0; i < ts.size(); i++) { Token t = ts.get(i); String s = t.getText(); if (s.indexOf("&") != -1) { if (s.indexOf("&amp;") != -1) // already friendly return carrier; else { s.replaceAll ("&", "&amp;"); t.setText (s); } } } return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,558
24.145161
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequenceMatchDataAndTarget.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.logging.*; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.MalletLogger; /** Run a regular expression over the text of each token; replace the text with the substring matching one regex group; create a target TokenSequence from the text matching another regex group. <p>For example, if you have a data file containing one line per token, and the label also appears on that line, you can first get a TokenSequence in which the text of each line is the Token.getText() of each token, then run this pipe, and separate the target information from the data information. For example to process the following, <pre> BACKGROUND Then PERSON Mr. PERSON Smith BACKGROUND said ... </pre> use <code>new TokenSequenceMatchDataAndTarget (Pattern.compile ("([A-Z]+) (.*)"), 2, 1)</code>. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequenceMatchDataAndTarget extends Pipe implements Serializable { private static Logger logger = MalletLogger.getLogger(TokenSequenceMatchDataAndTarget.class.getName()); Pattern regex; int dataGroup; int targetGroup; public TokenSequenceMatchDataAndTarget (Pattern regex, int dataGroup, int targetGroup) { this.regex = regex; this.dataGroup = dataGroup; this.targetGroup = targetGroup; } public TokenSequenceMatchDataAndTarget (String regex, int dataGroup, int targetGroup) { this (Pattern.compile (regex), dataGroup, targetGroup); } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); TokenSequence targetTokenSeq = new TokenSequence (ts.size()); for (int i = 0; i < ts.size(); i++) { Token t = ts.get(i); Matcher matcher = regex.matcher (t.getText()); if (matcher.matches()) { targetTokenSeq.add (matcher.group(targetGroup)); t.setText (matcher.group (dataGroup)); } else { logger.warning ("Skipping token: No match of "+regex.pattern() +" at token #"+i+" with text "+t.getText()); } } carrier.setTarget(targetTokenSeq); carrier.setData(ts); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); if (CURRENT_SERIAL_VERSION < 1) { out.writeObject(regex); } else { out.writeObject (regex.pattern()); out.writeInt (regex.flags()); } out.writeInt(dataGroup); out.writeInt(targetGroup); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); if (version < 1) regex = (Pattern) in.readObject(); else { String p = (String) in.readObject(); int flags = in.readInt(); regex = Pattern.compile (p, flags); } dataGroup = in.readInt(); targetGroup = in.readInt(); } }
3,552
28.608333
104
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Input2CharSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import java.net.URI; import cc.mallet.types.Instance; import cc.mallet.util.CharSequenceLexer; /** * Pipe that can read from various kinds of text sources * (either URI, File, or Reader) into a CharSequence * * @version $Id: Input2CharSequence.java,v 1.1 2007/10/22 21:37:39 mccallum Exp $ */ public class Input2CharSequence extends Pipe implements Serializable { String encoding = null; public Input2CharSequence () { } public Input2CharSequence( String encoding ) { this.encoding = encoding; } public Instance pipe (Instance carrier) { try { if (carrier.getData() instanceof URI) carrier.setData(pipe ((URI)carrier.getData())); else if (carrier.getData() instanceof File) carrier.setData(pipe ((File)carrier.getData())); else if (carrier.getData() instanceof Reader) carrier.setData(pipe ((Reader)carrier.getData())); else if (carrier.getData() instanceof CharSequence) ; // No conversion necessary else throw new IllegalArgumentException ("Does not handle class "+carrier.getData().getClass()); } catch (java.io.IOException e) { throw new IllegalArgumentException ("IOException " + e); } // System.out.println(carrier.getData().toString()); return carrier; } public CharSequence pipe (URI uri) throws java.io.FileNotFoundException, java.io.IOException { if (! uri.getScheme().equals("file")) throw new UnsupportedOperationException ("Only file: scheme implemented."); return pipe (new File (uri.getPath())); } public CharSequence pipe (File file) throws java.io.FileNotFoundException, java.io.IOException { BufferedReader br = null; if (encoding == null) { br = new BufferedReader (new FileReader (file)); } else { br = new BufferedReader( new InputStreamReader(new FileInputStream(file), encoding) ); } CharSequence cs = pipe(br); br.close(); return cs; } public CharSequence pipe (Reader reader) throws java.io.IOException { final int BUFSIZE = 2048; char[] buf = new char[BUFSIZE]; int count; StringBuffer sb = new StringBuffer (BUFSIZE); do { count = reader.read (buf, 0, BUFSIZE); if (count == -1) break; //System.out.println ("count="+count); sb.append (buf, 0, count); } while (count == BUFSIZE); return sb; } public CharSequence pipe (CharSequence cs) { return cs; } // Serialization private static final long serialVersionUID = 2; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); if (encoding == null) { out.writeObject("null"); } else { out.writeObject(encoding); } } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); this.encoding = (String) in.readObject(); if (encoding.equals("null")) { encoding = null; } } }
3,493
25.469697
95
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SerialPipes.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.lang.reflect.*; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.io.*; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.iterator.EmptyInstanceIterator; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; /** * Convert an instance through a sequence of pipes. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class SerialPipes extends Pipe implements Serializable { ArrayList<Pipe> pipes; public SerialPipes () { this.pipes = new ArrayList<Pipe> (); } public SerialPipes (Pipe[] pipes) { this.pipes = new ArrayList<Pipe> (pipes.length); for (int i = 0; i < pipes.length; i++) this.pipes.add (pipes[i]); resolveAlphabets(); } public SerialPipes (Collection<Pipe> pipeList) { pipes = new ArrayList<Pipe> (pipeList); resolveAlphabets(); } public abstract class Predicate { public abstract boolean predicate (Pipe p); } public SerialPipes newSerialPipesFromSuffix (Predicate testForStartingNewPipes) { int i = 0; while (i < pipes.size()) if (testForStartingNewPipes.predicate(pipes.get(i))) { return new SerialPipes(pipes.subList(i, pipes.size()-1)); } throw new IllegalArgumentException ("No pipes in this SerialPipe satisfied starting predicate."); } public SerialPipes newSerialPipesFromRange (int start, int end) { return new SerialPipes(pipes.subList(start, end)); } private void resolveAlphabets () { Alphabet da = null, ta = null; for (Pipe p : pipes) { p.preceedingPipeDataAlphabetNotification(da); da = p.getDataAlphabet(); p.preceedingPipeTargetAlphabetNotification(ta); ta = p.getTargetAlphabet(); } dataAlphabet = da; targetAlphabet = ta; } // protected void add (Pipe pipe) // protected void remove (int i) // This method removed because pipes should be immutable to be safe. // If you need an augmented pipe, you can make a new SerialPipes containing this one. public void setTargetProcessing (boolean lookForAndProcessTarget) { super.setTargetProcessing (lookForAndProcessTarget); for (Pipe p : pipes) p.setTargetProcessing (lookForAndProcessTarget); } public Iterator<Instance> newIteratorFrom (Iterator<Instance> source) { if (pipes.size() == 0) return new EmptyInstanceIterator(); Iterator<Instance> ret = pipes.get(0).newIteratorFrom(source); for (int i = 1; i < pipes.size(); i++) ret = pipes.get(i).newIteratorFrom(ret); return ret; } public int size() { return pipes.size(); } public Pipe getPipe (int index) { Pipe retPipe = null; try { retPipe = pipes.get(index); } catch (Exception e) { System.err.println("Error getting pipe. Index = " + index + ". " + e.getMessage()); } return retPipe; } /** Allows access to the underlying collection of Pipes. Use with caution. */ public ArrayList<Pipe> pipes() { return pipes; } public String toString () { StringBuffer sb = new StringBuffer(); for (Pipe p : pipes) sb.append (p.toString()+","); return sb.toString(); } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(pipes); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); pipes = (ArrayList) in.readObject(); resolveAlphabets(); } }
4,012
26.29932
99
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequence2FeatureSequenceWithBigrams.java
/* Copyright (C) 2005 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; /** * Convert the token sequence in the data field of each instance to a feature sequence that * preserves bigram information. * @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequence2FeatureSequenceWithBigrams extends Pipe { Alphabet biDictionary; public TokenSequence2FeatureSequenceWithBigrams (Alphabet dataDict, Alphabet bigramAlphabet) { super (dataDict, null); biDictionary = bigramAlphabet; } public TokenSequence2FeatureSequenceWithBigrams (Alphabet dataDict) { super (dataDict, null); biDictionary = new Alphabet(); } public TokenSequence2FeatureSequenceWithBigrams () { super(new Alphabet(), null); biDictionary = new Alphabet(); } public Alphabet getBigramAlphabet () { return biDictionary; } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); FeatureSequence ret = new FeatureSequenceWithBigrams (getDataAlphabet(), biDictionary, ts); carrier.setData(ret); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(biDictionary); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); biDictionary = (Alphabet) in.readObject(); } }
1,985
26.205479
93
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequenceLowercase.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Convert the text in each token in the token sequence in the data field to lower case. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequenceLowercase extends Pipe implements Serializable { public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); for (int i = 0; i < ts.size(); i++) { Token t = ts.get(i); t.setText(t.getText().toLowerCase()); } return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,439
27.235294
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureSequence2FeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.FeatureSequence; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; // This class does not insist on getting its own Alphabet because it can rely on getting // it from the FeatureSequence input. /** * Convert the data field from a feature sequence to a feature vector. */ public class FeatureSequence2FeatureVector extends Pipe implements Serializable { boolean binary; public FeatureSequence2FeatureVector (boolean binary) { this.binary = binary; } public FeatureSequence2FeatureVector () { this (false); } public Instance pipe (Instance carrier) { FeatureSequence fs = (FeatureSequence) carrier.getData(); carrier.setData(new FeatureVector (fs, binary)); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeBoolean (binary); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); if (version > 0) binary = in.readBoolean(); } }
1,766
25.772727
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FilterEmptyFeatureVectors.java
package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; public class FilterEmptyFeatureVectors extends Pipe { private class FilteringPipeInstanceIterator implements Iterator<Instance> { Iterator<Instance> source; Instance nextInstance = null; boolean doesHaveNext = false; public FilteringPipeInstanceIterator (Iterator<Instance> source) { this.source = source; if (source.hasNext()) { nextInstance = source.next(); doesHaveNext = true; } else doesHaveNext = false; } public boolean hasNext () { return doesHaveNext; } public Instance next() { Instance ret = nextInstance; doesHaveNext = false; while (source.hasNext()) { nextInstance = source.next(); if (((FeatureVector)nextInstance.getData()).numLocations() > 0) { doesHaveNext = true; break; } } if (!doesHaveNext) nextInstance = null; return ret; } public void remove () { throw new IllegalStateException ("This iterator does not support remove()."); } /** Return the @link{Pipe} that processes @link{Instance}s going through this iterator. */ public Pipe getPipe () { return null; } public Iterator<Instance> getSourceIterator () { return source; } } public Iterator<Instance> newIteratorFrom (Iterator<Instance> source) { return new FilteringPipeInstanceIterator (source); } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,898
25.746479
105
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SimpleTaggerSentence2TokenSequence.java
/* Copyright (C) 2003 University of Pennsylvania. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Fernando Pereira <a href="mailto:[email protected]">[email protected]</a> Modified by Kuzman Ganchev to covert to TokenSequence rather than to FeatureVectorSequence. */ package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import cc.mallet.types.*; /** * Converts an external encoding of a sequence of elements with binary * features to a {@link TokenSequence}. If target processing * is on (training or labeled test data), it extracts element labels * from the external encoding to create a target {@link LabelSequence}. * Two external encodings are supported: * <ol> * <li> A {@link String} containing lines of whitespace-separated tokens.</li> * <li> a {@link String}<code>[][]</code>.</li> * </ol> * <p/> * Both represent rows of tokens. When target processing is on, the last token * in each row is the label of the sequence element represented by * this row. All other tokens in the row, or all tokens in the row if * not target processing, are the names of features that are on for * the sequence element described by the row. */ public class SimpleTaggerSentence2TokenSequence extends Pipe { protected boolean setTokensAsFeatures; /** * Creates a new * <code>SimpleTaggerSentence2TokenSequence</code> instance. * By default we include tokens as features. */ public SimpleTaggerSentence2TokenSequence () { super (null, new LabelAlphabet()); setTokensAsFeatures = true; } /** * creates a new <code>SimpleTaggerSentence2TokenSequence</code> instance * which includes tokens as features iff the supplied argument is true. */ public SimpleTaggerSentence2TokenSequence (boolean inc) { super (null, new LabelAlphabet()); setTokensAsFeatures = inc; } /** * Parses a string representing a sequence of rows of tokens into an * array of arrays of tokens. * * @param sentence a <code>String</code> * @return the corresponding array of arrays of tokens. */ protected String[][] parseSentence (String sentence) { String[] lines = sentence.split ("\n"); String[][] tokens = new String[lines.length][]; for (int i = 0; i < lines.length; i++) tokens[i] = lines[i].split ("\\s"); return tokens; } /** returns the first String in the array or "" if the array has length 0. */ protected String makeText(String[] in){ if (in.length>0) return in[0]; else return ""; } /** * Takes an instance with data of type String or String[][] and creates * an Instance of type TokenSequence. Each Token in the sequence is * gets the test of the line preceding it and once feature of value 1 * for each "Feature" in the line. For example, if the String[][] is * {{a,b},{c,d,e}} (and target processing is off) then the text would be * "a b" for the first token and "c d e" for the second. Also, the * features "a" and "b" would be set for the first token and "c", "d" and * "e" for the second. The last element in the String[] for the current * token is taken as the target (label), so in the previous example "b" * would have been the label of the first sequence. */ public Instance pipe (Instance carrier) { Object inputData = carrier.getData(); //Alphabet features = getDataAlphabet(); LabelAlphabet labels; LabelSequence target = null; String [][] tokens; TokenSequence ts = new TokenSequence (); if (inputData instanceof String) tokens = parseSentence ((String) inputData); else if (inputData instanceof String[][]) tokens = (String[][]) inputData; else throw new IllegalArgumentException ("Not a String or String[][]; got " + inputData); FeatureVector[] fvs = new FeatureVector[tokens.length]; if (isTargetProcessing ()) { labels = (LabelAlphabet) getTargetAlphabet (); target = new LabelSequence (labels, tokens.length); } for (int l = 0; l < tokens.length; l++) { int nFeatures; if (isTargetProcessing ()) { if (tokens[l].length < 1) throw new IllegalStateException ("Missing label at line " + l + " instance " + carrier.getName ()); nFeatures = tokens[l].length - 1; target.add(tokens[l][nFeatures]); } else nFeatures = tokens[l].length; Token tok = new Token(makeText(tokens[l])); if (setTokensAsFeatures){ for (int f = 0; f < nFeatures; f++) tok.setFeatureValue(tokens[l][f], 1.0); } else { for (int f = 1; f < nFeatures; f++) tok.setFeatureValue(tokens[l][f], 1.0); } ts.add (tok); } carrier.setData (ts); if (isTargetProcessing ()) carrier.setTarget (target); return carrier; } // Serialization garbage private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject (ObjectOutputStream out) throws IOException { out.defaultWriteObject (); out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject (); int version = in.readInt (); } }
5,578
33.652174
109
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/AddClassifierTokenPredictions.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.logging.Logger; import cc.mallet.classify.BalancedWinnowTrainer; import cc.mallet.classify.Classification; import cc.mallet.classify.Classifier; import cc.mallet.classify.ClassifierTrainer; import cc.mallet.classify.Trial; import cc.mallet.types.Alphabet; import cc.mallet.types.AugmentableFeatureVector; import cc.mallet.types.FeatureVector; import cc.mallet.types.FeatureVectorSequence; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import cc.mallet.types.Label; import cc.mallet.types.LabelSequence; import cc.mallet.types.LabelVector; import cc.mallet.types.Labeling; import cc.mallet.util.MalletLogger; /** * This pipe uses a Classifier to label each token (i.e., using 0-th order Markov assumption), * then adds the predictions as features to each token. * * This pipe assumes the input Instance's data is of type FeatureVectorSequence * (each an augmentable feature vector). * * Example usage:<pre> * 1) Create and serialize a featurePipe that converts raw input to FeatureVectorSequences * 2) Pipe input data through featurePipe, train a TokenClassifiers via cross validation, then serialize the classifiers * 2) Pipe input data through featurePipe and this pipe (using the saved classifiers), and train a Transducer * 4) Serialize the trained Transducer * </pre> * @author ghuang */ public class AddClassifierTokenPredictions extends Pipe implements Serializable { private static Logger logger = MalletLogger.getLogger(AddClassifierTokenPredictions.class.getName()); // Specify which predictions are to be added as features. // E.g., { 1, 2 } = add labels of the top 2 highest-scoring predictions as features. int[] m_predRanks2add; // The trained token classifier TokenClassifiers m_tokenClassifiers; // Whether to treat each instance's feature values as binary boolean m_binary; // Whether the pipe is currently being used at production time // (i.e., not being used as pipeline for training a transducer) boolean m_inProduction; // Augmented data alphabet that includes the class predictions Alphabet m_dataAlphabet; public AddClassifierTokenPredictions(InstanceList trainList) { this(trainList, null); } public AddClassifierTokenPredictions(InstanceList trainList, InstanceList testList) { this(new TokenClassifiers(convert(trainList, (Noop) trainList.getPipe())), new int[] { 1 }, true, convert(testList, (Noop) trainList.getPipe())); } public AddClassifierTokenPredictions(TokenClassifiers tokenClassifiers, int[] predRanks2add, boolean binary, InstanceList testList) { m_predRanks2add = predRanks2add; m_binary = binary; m_tokenClassifiers = tokenClassifiers; m_inProduction = false; m_dataAlphabet = (Alphabet) tokenClassifiers.getAlphabet().clone(); Alphabet labelAlphabet = tokenClassifiers.getLabelAlphabet(); // add the token prediction features to the alphabet for (int i = 0; i < m_predRanks2add.length; i++) { for (int j = 0; j < labelAlphabet.size(); j++) { String featName = "TOK_PRED=" + labelAlphabet.lookupObject(j).toString() + "_@_RANK_" + m_predRanks2add[i]; m_dataAlphabet.lookupIndex(featName, true); } } // evaluate token classifier if (testList != null) { Trial trial = new Trial(m_tokenClassifiers, testList); logger.info("Token classifier accuracy on test set = " + trial.getAccuracy()); } } public void setInProduction(boolean inProduction) { m_inProduction = inProduction; } public boolean getInProduction() { return m_inProduction; } public static void setInProduction(Pipe p, boolean value) { if (p instanceof AddClassifierTokenPredictions) ((AddClassifierTokenPredictions) p).setInProduction(value); else if (p instanceof SerialPipes) { SerialPipes sp = (SerialPipes) p; for (int i = 0; i < sp.size(); i++) setInProduction(sp.getPipe(i), value); } } public Alphabet getDataAlphabet() { return m_dataAlphabet; } /** * Add the token classifier's predictions as features to the instance. * This method assumes the input instance contains FeatureVectorSequence as data */ public Instance pipe(Instance carrier) { FeatureVectorSequence fvs = (FeatureVectorSequence) carrier.getData(); InstanceList ilist = convert(carrier, (Noop) m_tokenClassifiers.getInstancePipe()); assert (fvs.size() == ilist.size()); // For passing instances to the token classifier, each instance's data alphabet needs to // match that used by the token classifier at training time. For the resulting piped // instance, each instance's data alphabet needs to contain token classifier's prediction // as features FeatureVector[] fva = new FeatureVector[fvs.size()]; for (int i = 0; i < ilist.size(); i++) { Instance inst = ilist.get(i); Classification c = m_tokenClassifiers.classify(inst, ! m_inProduction); LabelVector lv = c.getLabelVector(); AugmentableFeatureVector afv1 = (AugmentableFeatureVector) inst.getData(); int[] indices = afv1.getIndices(); AugmentableFeatureVector afv2 = new AugmentableFeatureVector(m_dataAlphabet, indices, afv1.getValues(), indices.length + m_predRanks2add.length); for (int j = 0; j < m_predRanks2add.length; j++) { Label label = lv.getLabelAtRank(m_predRanks2add[j]); int idx = m_dataAlphabet.lookupIndex("TOK_PRED=" + label.toString() + "_@_RANK_" + m_predRanks2add[j]); assert(idx >= 0); afv2.add(idx, 1); } fva[i] = afv2; } carrier.setData(new FeatureVectorSequence(fva)); return carrier; } /** * Converts each instance containing a FeatureVectorSequence to multiple instances, * each containing an AugmentableFeatureVector as data. * * @param ilist Instances with FeatureVectorSequence as data field * @param alphabetsPipe a Noop pipe containing the data and target alphabets for the resulting InstanceList * @return an InstanceList where each Instance contains one Token's AugmentableFeatureVector as data */ public static InstanceList convert(InstanceList ilist, Noop alphabetsPipe) { if (ilist == null) return null; // This monstrosity is necessary b/c Classifiers obtain the data/target alphabets via pipes InstanceList ret = new InstanceList(alphabetsPipe); for (Instance inst : ilist) ret.add(inst); //for (int i = 0; i < ilist.size(); i++) ret.add(convert(ilist.get(i), alphabetsPipe)); return ret; } /** * * @param inst input instance, with FeatureVectorSequence as data. * @param alphabetsPipe a Noop pipe containing the data and target alphabets for * the resulting InstanceList and AugmentableFeatureVectors * @return list of instances, each with one AugmentableFeatureVector as data */ public static InstanceList convert(Instance inst, Noop alphabetsPipe) { InstanceList ret = new InstanceList(alphabetsPipe); Object obj = inst.getData(); assert(obj instanceof FeatureVectorSequence); FeatureVectorSequence fvs = (FeatureVectorSequence) obj; LabelSequence ls = (LabelSequence) inst.getTarget(); assert(fvs.size() == ls.size()); Object instName = (inst.getName() == null ? "NONAME" : inst.getName()); for (int j = 0; j < fvs.size(); j++) { FeatureVector fv = fvs.getFeatureVector(j); int[] indices = fv.getIndices(); FeatureVector data = new AugmentableFeatureVector (alphabetsPipe.getDataAlphabet(), indices, fv.getValues(), indices.length); Labeling target = ls.getLabelAtPosition(j); String name = instName.toString() + "_@_POS_" + (j + 1); Object source = inst.getSource(); Instance toAdd = alphabetsPipe.pipe(new Instance(data, target, name, source)); ret.add(toAdd); } return ret; } // Serialization private static final long serialVersionUID = 1; /** * This inner class represents the trained token classifiers. * @author ghuang */ public static class TokenClassifiers extends Classifier implements Serializable { // number of folds in cross-validation training int m_numCV; // random seed to split training data for cross-validation int m_randSeed; // trainer for token classifier ClassifierTrainer m_trainer; // token classifier trained on the entirety of the training set Classifier m_tokenClassifier; // table storing instance name --> out-of-fold classifier // Used to prevent overfitting to the token classifier's predictions HashMap m_table; /** * Train a token classifier using the given Instances with 5-fold cross validation * @param trainList training instances */ public TokenClassifiers(InstanceList trainList) { this(trainList, 0, 5); } public TokenClassifiers(InstanceList trainList, int randSeed, int numCV) { // this(new AdaBoostM2Trainer(new DecisionTreeTrainer(2), 10), trainList, randSeed, numCV); // this(new NaiveBayesTrainer(), trainList, randSeed, numCV); this(new BalancedWinnowTrainer(), trainList, randSeed, numCV); // this(new SVMTrainer(), trainList, randSeed, numCV); } public TokenClassifiers(ClassifierTrainer trainer, InstanceList trainList, int randSeed, int numCV) { super(trainList.getPipe()); m_trainer = trainer; m_randSeed = randSeed; m_numCV = numCV; m_table = new HashMap(); doTraining(trainList); } // train the token classifier private void doTraining(InstanceList trainList) { // train a classifier on the entire training set logger.info("Training token classifier on entire data set (size=" + trainList.size() + ")..."); m_tokenClassifier = m_trainer.train(trainList); Trial t = new Trial(m_tokenClassifier, trainList); logger.info("Training set accuracy = " + t.getAccuracy()); if (m_numCV == 0) return; // train classifiers using cross validation InstanceList.CrossValidationIterator cvIter = trainList.new CrossValidationIterator(m_numCV, m_randSeed); int f = 1; while (cvIter.hasNext()) { f++; InstanceList[] fold = cvIter.nextSplit(); logger.info("Training token classifier on cv fold " + f + " / " + m_numCV + " (size=" + fold[0].size() + ")..."); Classifier foldClassifier = m_trainer.train(fold[0]); Trial t1 = new Trial(foldClassifier, fold[0]); Trial t2 = new Trial(foldClassifier, fold[1]); logger.info("Within-fold accuracy = " + t1.getAccuracy()); logger.info("Out-of-fold accuracy = " + t2.getAccuracy()); /*for (int x = 0; x < t2.size(); x++) { logger.info("xxx pred:" + t2.getClassification(x).getLabeling().getBestLabel() + " true:" + t2.getClassification(x).getInstance().getLabeling()); }*/ for (int i = 0; i < fold[1].size(); i++) { Instance inst = fold[1].get(i); m_table.put(inst.getName(), foldClassifier); } } } public Classification classify(Instance instance) { return classify(instance, false); } /** * * @param instance the instance to classify * @param useOutOfFold whether to check the instance name and use the out-of-fold classifier * if the instance name matches one in the training data * @return the token classifier's output */ public Classification classify(Instance instance, boolean useOutOfFold) { Object instName = instance.getName(); if (! useOutOfFold || ! m_table.containsKey(instName)) return m_tokenClassifier.classify(instance); Classifier classifier = (Classifier) m_table.get(instName); return classifier.classify(instance); } // serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 1; private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(getInstancePipe()); out.writeInt(m_numCV); out.writeInt(m_randSeed); out.writeObject(m_table); out.writeObject(m_tokenClassifier); out.writeObject(m_trainer); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt(); if (version != CURRENT_SERIAL_VERSION) throw new ClassNotFoundException("Mismatched TokenClassifiers versions: wanted " + CURRENT_SERIAL_VERSION + ", got " + version); instancePipe = (Pipe) in.readObject(); m_numCV = in.readInt(); m_randSeed = in.readInt(); m_table = (HashMap) in.readObject(); m_tokenClassifier = (Classifier) in.readObject(); m_trainer = (ClassifierTrainer) in.readObject(); } } }
13,060
33.191099
150
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequenceReplace.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.regex.*; import java.io.*; import cc.mallet.types.Instance; /** Given a string, repeatedly look for matches of the regex, and replace the entire match with the given replacement string. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class CharSequenceReplace extends Pipe implements Serializable { public static final Pattern SKIP_SGML = Pattern.compile ("<[^>]*>"); Pattern regex; String replacement; // xxx Yipes, this only works for UNIX-style newlines. // Anyone want to generalize it to Windows, etc? public static final Pattern SKIP_HEADER = Pattern.compile ("\\n\\n(.*)\\z", Pattern.DOTALL); public CharSequenceReplace (Pattern regex, String replacement) { this.regex = regex; this.replacement = replacement; } public Instance pipe (Instance carrier) { String string = ((CharSequence)carrier.getData()).toString(); Matcher m = regex.matcher(string); carrier.setData(m.replaceAll (replacement)); return carrier; } //Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(regex); out.writeObject(replacement); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); regex = (Pattern) in.readObject(); replacement = (String) in.readObject(); } }
1,985
28.641791
93
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureCountPipe.java
package cc.mallet.pipe; import cc.mallet.types.*; import java.io.*; /** * Pruning low-count features can be a good way to save memory and computation. * However, in order to use Vectors2Vectors, you need to write out the unpruned * instance list, read it back into memory, collect statistics, create new * instances, and then write everything back out. * <p> * This class supports a simpler method that makes two passes over the data: * one to collect statistics and create an augmented "stop list", and a * second to actually create instances. */ public class FeatureCountPipe extends Pipe { FeatureCounter counter; public FeatureCountPipe() { super(new Alphabet(), null); counter = new FeatureCounter(this.getDataAlphabet()); } public FeatureCountPipe(Alphabet dataAlphabet, Alphabet targetAlphabet) { super(dataAlphabet, targetAlphabet); counter = new FeatureCounter(dataAlphabet); } public Instance pipe(Instance instance) { if (instance.getData() instanceof FeatureSequence) { FeatureSequence features = (FeatureSequence) instance.getData(); for (int position = 0; position < features.size(); position++) { counter.increment(features.getIndexAtPosition(position)); } } else { throw new IllegalArgumentException("Looking for a FeatureSequence, found a " + instance.getData().getClass()); } return instance; } /** * Returns a new alphabet that contains only features at or above * the specified limit. */ public Alphabet getPrunedAlphabet(int minimumCount) { Alphabet currentAlphabet = getDataAlphabet(); Alphabet prunedAlphabet = new Alphabet(); for (int feature = 0; feature < currentAlphabet.size(); feature++) { if (counter.get(feature) >= minimumCount) { prunedAlphabet.lookupObject(currentAlphabet.lookupIndex(feature)); } } prunedAlphabet.stopGrowth(); return prunedAlphabet; } /** * Writes a list of features that do not occur at or * above the specified cutoff to the pruned file, one per line. * This file can then be passed to a stopword filter as * "additional stopwords". */ public void writePrunedWords(File prunedFile, int minimumCount) throws IOException { PrintWriter out = new PrintWriter(prunedFile); Alphabet currentAlphabet = getDataAlphabet(); for (int feature = 0; feature < currentAlphabet.size(); feature++) { if (counter.get(feature) < minimumCount) { out.println(currentAlphabet.lookupObject(feature)); } } out.close(); } /** * Add all pruned words to the internal stoplist of a SimpleTokenizer. */ public void addPrunedWordsToStoplist(SimpleTokenizer tokenizer, int minimumCount) { Alphabet currentAlphabet = getDataAlphabet(); for (int feature = 0; feature < currentAlphabet.size(); feature++) { if (counter.get(feature) < minimumCount) { tokenizer.stop((String) currentAlphabet.lookupObject(feature)); } } } /** * List the most common words, for addition to a stop file */ public void writeCommonWords(File commonFile, int totalWords) throws IOException { PrintWriter out = new PrintWriter(commonFile); Alphabet currentAlphabet = getDataAlphabet(); IDSorter[] sortedWords = new IDSorter[currentAlphabet.size()]; for (int type = 0; type < currentAlphabet.size(); type++) { sortedWords[type] = new IDSorter(type, counter.get(type)); } java.util.Arrays.sort(sortedWords); int max = totalWords; if (currentAlphabet.size() < max) { max = currentAlphabet.size(); } for (int rank = 0; rank < max; rank++) { int type = sortedWords[rank].getID(); out.println (currentAlphabet.lookupObject(type)); } out.close(); } static final long serialVersionUID = 1; }
3,809
26.021277
85
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Noop.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; /** * A pipe that does nothing to the instance fields but which has side effects on the dictionary. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Noop extends Pipe implements Serializable { public Noop () { } /** Pass through input without change, but force the creation of Alphabet's, so it can be shared by future DictionariedPipe's. You might want to use this before ParallelPipes where the previous pipes do not need dictionaries, but later steps in each parallel path do, and they all must share the same dictionary. */ public Noop (Alphabet dataDict, Alphabet targetDict) { super (dataDict, targetDict); } public Instance pipe (Instance carrier) { return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,646
25.564516
96
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Target2Label.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.Label; import cc.mallet.types.LabelAlphabet; /** Convert object in the target field into a label in the target field. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Target2Label extends Pipe { private final static long serialVersionUID = -461155063551297878L; //-8390758647439705273L; // gsc: adding constructor that has an option for the data alphabet as well, // this avoids the data alphabet getting set to null towards the end of a // SerialPipes object because the data alphabet might have already been set public Target2Label (Alphabet dataAlphabet, LabelAlphabet labelAlphabet) { super(dataAlphabet, labelAlphabet); } public Target2Label () { this(null, new LabelAlphabet()); } public Target2Label (LabelAlphabet labelAlphabet) { this(null, labelAlphabet); } public Instance pipe (Instance carrier) { if (carrier.getTarget() != null) { if (carrier.getTarget() instanceof Label) throw new IllegalArgumentException ("Already a label."); LabelAlphabet ldict = (LabelAlphabet) getTargetAlphabet(); carrier.setTarget(ldict.lookupLabel (carrier.getTarget())); } return carrier; } }
1,742
30.690909
94
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/LineGroupString2TokenSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> Takes a (possibly) multi-line String and creates one token for each line, where token.getText holds the contents of the line. e.g. input: Instance.data = " PERSON John NN O kicked V 0 the 0 ball " output: TokenSequence ts = (TokenSequence)Instance.data: ts.getToken(0).getText = "PERSON John NN"; ts.getToken(1).getText = "0 kicked V"; ... */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.Lexer; public class LineGroupString2TokenSequence extends Pipe implements Serializable { CharSequenceLexer lexer; public LineGroupString2TokenSequence () { } public Instance pipe (Instance carrier) { if (!(carrier.getData() instanceof CharSequence)) throw new IllegalArgumentException (); String s = carrier.getData().toString(); String[] lines = s.split (System.getProperty ("line.separator")); carrier.setData (new TokenSequence (lines)); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,961
25.513514
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequenceArray2TokenSequence.java
/* Copyright (C) 2003 Univiversity of Pennsylvania. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import java.net.URI; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Transform an array of character Sequences into a token sequence. @author Fernando Pereira <a href="mailto:[email protected]">[email protected]</a> */ public class CharSequenceArray2TokenSequence extends Pipe implements Serializable { public CharSequenceArray2TokenSequence () { } public Instance pipe (Instance carrier) { carrier.setData(new TokenSequence((CharSequence[]) carrier.getData())); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,382
27.8125
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Target2FeatureSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; /** Convert a token sequence in the target field into a feature sequence in the target field. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class Target2FeatureSequence extends Pipe implements Serializable { public Target2FeatureSequence () { super (null, new Alphabet()); } public Instance pipe (Instance carrier) { //Object in = carrier.getData(); Object target = carrier.getTarget(); if (target instanceof FeatureSequence) ; // Nothing to do else if (target instanceof TokenSequence) { TokenSequence ts = (TokenSequence) target; FeatureSequence fs = new FeatureSequence (getTargetAlphabet(), ts.size()); for (int i = 0; i < ts.size(); i++) fs.add (ts.get(i).getText()); carrier.setTarget(fs); } else { throw new IllegalArgumentException ("Unrecognized target type."); } return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,779
28.180328
93
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/StringList2FeatureSequence.java
package cc.mallet.pipe; import java.io.*; import java.util.ArrayList; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureSequence; import cc.mallet.types.Instance; /** * Convert a list of strings into a feature sequence */ public class StringList2FeatureSequence extends Pipe { public long totalNanos = 0; public StringList2FeatureSequence (Alphabet dataDict) { super (dataDict, null); } public StringList2FeatureSequence () { super(new Alphabet(), null); } public Instance pipe (Instance carrier) { long start = System.nanoTime(); try { ArrayList<String> tokens = (ArrayList<String>) carrier.getData(); FeatureSequence featureSequence = new FeatureSequence ((Alphabet) getDataAlphabet(), tokens.size()); for (int i = 0; i < tokens.size(); i++) { featureSequence.add (tokens.get(i)); } carrier.setData(featureSequence); totalNanos += System.nanoTime() - start; } catch (ClassCastException cce) { System.err.println("Expecting ArrayList<String>, found " + carrier.getData().getClass()); } return carrier; } static final long serialVersionUID = 1; }
1,133
22.142857
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/PipeUtils.java
/* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.SerialPipes; import cc.mallet.types.Alphabet; /** * Created: Aug 28, 2005 * * @author <A HREF="mailto:[email protected]>[email protected]</A> * @version $Id: PipeUtils.java,v 1.1 2007/10/22 21:37:39 mccallum Exp $ */ public class PipeUtils { private PipeUtils () {}; // no instances public static Pipe concatenatePipes (Pipe p1, Pipe p2) { Alphabet dataDict = combinedDataDicts (p1, p2); Alphabet targetDict = combinedTargetDicts (p1, p2); Pipe ret = new SerialPipes (new Pipe[] { p1, p2 }); if (dataDict != null) ret.dataAlphabetResolved = true; if (targetDict != null) ret.targetAlphabetResolved = true; ret.dataAlphabet = dataDict; ret.targetAlphabet = targetDict; return ret; } private static Alphabet combinedDataDicts (Pipe p1, Pipe p2) { if (p1.dataAlphabet == null) return p2.dataAlphabet; if (p2.dataAlphabet == null) return p1.dataAlphabet; if (p1.dataAlphabet == p2.dataAlphabet) return p2.dataAlphabet; throw new IllegalArgumentException ("Attempt to concat pipes with incompatible data dicts."); } private static Alphabet combinedTargetDicts (Pipe p1, Pipe p2) { if (p1.targetAlphabet == null) return p2.targetAlphabet; if (p2.targetAlphabet == null) return p1.targetAlphabet; if (p1.targetAlphabet == p2.targetAlphabet) return p2.targetAlphabet; throw new IllegalArgumentException ("Attempt to concat pipes with incompatible target dicts."); } }
1,962
34.690909
99
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequence2FeatureSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureSequence; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Convert the token sequence in the data field each instance to a feature sequence. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequence2FeatureSequence extends Pipe { public TokenSequence2FeatureSequence (Alphabet dataDict) { super (dataDict, null); } public TokenSequence2FeatureSequence () { super(new Alphabet(), null); } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); FeatureSequence ret = new FeatureSequence ((Alphabet)getDataAlphabet(), ts.size()); for (int i = 0; i < ts.size(); i++) { ret.add (ts.get(i).getText()); } carrier.setData(ret); return carrier; } }
1,370
25.882353
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureSequence2AugmentableFeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.AugmentableFeatureVector; import cc.mallet.types.FeatureSequence; import cc.mallet.types.Instance; // This class does not insist on gettings its own Alphabet because it can rely on getting // it from the FeatureSequence input. /** * Convert the data field from a feature sequence to an augmentable feature vector. */ public class FeatureSequence2AugmentableFeatureVector extends Pipe { boolean binary; public FeatureSequence2AugmentableFeatureVector (boolean binary) { this.binary = binary; } public FeatureSequence2AugmentableFeatureVector () { this (false); } public Instance pipe (Instance carrier) { carrier.setData(new AugmentableFeatureVector ((FeatureSequence)carrier.getData(), binary)); return carrier; } }
1,331
26.75
93
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Classification2ConfidencePredictingFeatureVector.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.util.ArrayList; import java.util.logging.*; import cc.mallet.classify.*; import cc.mallet.classify.evaluate.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; import cc.mallet.util.PropertyList; /** Pipe features from underlying classifier to * the confidence prediction instance list */ public class Classification2ConfidencePredictingFeatureVector extends Pipe { public Classification2ConfidencePredictingFeatureVector () { super (new Alphabet(), new LabelAlphabet()); } public Instance pipe (Instance carrier) { Classification classification = (Classification) carrier.getData(); PropertyList features = null; LabelVector lv = classification.getLabelVector(); Label bestLabel = lv.getBestLabel(); Instance inst = (Instance)classification.getInstance(); FeatureVector fv = (FeatureVector)inst.getData(); Alphabet fdict = fv.getAlphabet(); double winningThreshold = .990; double varianceThreshold = .15; double secondThreshold = .03; double winningScore = lv.getValueAtRank(0); double marginOfVictory = winningScore - lv.getValueAtRank(1); // attempts to use the confusion matrix of the training list // as some prior knowledge in training features = PropertyList.add ("winningScore", winningScore, features); features = PropertyList.add ("secondScore", lv.getValueAtRank(1), features); for(int i=0; i<lv.numLocations(); i++) { // features = PropertyList.add (lv.getLabelAtRank(i).toString() +"HasRank"+i, 1.0, features); features = PropertyList.add (lv.getLabelAtRank(i).toString() +"HasValue", lv.valueAtLocation (i), features); } features = PropertyList.add ("MarginOfVictory", marginOfVictory, features); features = PropertyList.add("numFeatures", ((double)fv.numLocations()/fdict.size()), features); features = PropertyList.add (bestLabel.toString() + "IsFirst-" + lv.getLabelAtRank(1).toString()+"IsSecond", 1.0, features); features = PropertyList.add ("Range", winningScore - lv.getValueAtRank(lv.numLocations()-1), features); features = PropertyList.add (bestLabel.toString()+"IsFirst", 1.0, features); features = PropertyList.add (lv.getLabelAtRank(1).toString() + "IsSecond", 1.0, features); // loop through original feature vector // and add each feature to PropertyList // features = PropertyList.add ("winningScore", winningScore, features); // features = PropertyList.add ("secondScore", lv.getValueAtRank(1), features); // features = PropertyList.add (bestLabel.toString()+"IsFirst", 1.0, features); // features = PropertyList.add (lv.getLabelAtRank(1).toString() + "IsSecond", 1.0, features); // xxx this hurt performance. is this correct function call? // for(int loc = 0; loc < fv.numLocations(); loc++) // features = PropertyList.add(fdict.lookupObject(loc).toString(), 1.0, features); //features = PropertyList.add ("winningClassPrecision", confusionMatrix.getPrecision(lv.getBestIndex()) , features); // features = PropertyList.add ("confusionBetweenTop2", confusionMatrix.getConfusionBetween(lv.getBestIndex(), lv.getIndexAtRank(1)) , features); //features = PropertyList.add ("Variance",getScoreVariance(lv), features); // use cutoffs of some metrics /* if(winningScore < winningThreshold){ features = PropertyList.add ("WinningScoreBelowX", 1.0, features); bestScoreLessThanX++; if(classification.bestLabelIsCorrect()) { reallyWrong++; } } if(marginOfVictory < .9) features = PropertyList.add ("MarginOfVictoryBelow.9", 1.0, features); if(getScoreVariance(lv) < varianceThreshold) { features = PropertyList.add ("VarianceBelowX", 1.0, features); varianceLessThanX++; } if(lv.getValueAtRank(1) > secondThreshold) { features = PropertyList.add ("SecondScoreAboveX", 1.0, features); secondScoreGreaterThanX++; } */ /* // all the confidence predicting features features = PropertyList.add ("winningScore", winningScore, features); features = PropertyList.add(bestLabel.toString()+"IsFirst", 1.0, features); features = PropertyList.add (lv.getLabelAtRank(1).toString() + "IsSecond", 1.0, features); features = PropertyList.add ("secondScore", lv.getValueAtRank(1), features); for(int i=0; i<lv.numLocations(); i++) { features = PropertyList.add (lv.getLabelAtRank(i).toString() +"HasRank"+i, lv.getValueAtRank(i), features); } if(marginOfVictory < .9) features = PropertyList.add ("MarginOfVictoryBelow.9", 1.0, features); if(winningScore < winningThreshold){ features = PropertyList.add ("WinningScoreBelowX", 1.0, features); bestScoreLessThanX++; } if(getScoreVariance(lv) < varianceThreshold) { features = PropertyList.add ("VarianceBelowX", 1.0, features); varianceLessThanX++; } if(lv.getValueAtRank(1) > secondThreshold) { features = PropertyList.add ("SecondScoreAboveX", 1.0, features); secondScoreGreaterThanX++; } LabelAlphabet vocab = lv.getLabelAlphabet(); for(int i=0; i<vocab.size(); i++) { features = PropertyList.add(vocab.lookupObject(i).toString()+"'sScore", lv.valueAtLocation(i), features); } features = PropertyList.add("numFeatures", ((double)fv.numLocations()/fdict.size()), features); features = PropertyList.add (bestLabel.toString() + "IsFirst-" + lv.getLabelAtRank(1).toString()+"IsSecond", 1.0, features); features = PropertyList.add("marginOfVictory", lv.getBestValue() - lv.getValueAtRank(1), features); */ /* // xxx these features either had 0 info gain or had a negative // impact on performance features = PropertyList.add ("scoreVariance", getScoreVariance(lv), features); features = PropertyList.add ("scoreMean", getScoreMean(lv), features); */ // loop through original feature vector // and add each feature to PropertyList // xxx this hurt performance. is this correct function call? //for(int loc = 0; loc < fv.numLocations(); loc++) // features = PropertyList.add(fdict.lookupObject(loc).toString(), 1.0, features); // ... // ... carrier.setTarget(((LabelAlphabet)getTargetAlphabet()).lookupLabel(classification.bestLabelIsCorrect() ? "correct" : "incorrect")); carrier.setData(new FeatureVector ((Alphabet) getDataAlphabet(), features, false)); carrier.setName(inst.getName()); carrier.setSource(inst.getSource()); return carrier; } private double getScoreMean(LabelVector lv) { double sum = 0.0; for(int i=0; i<lv.numLocations(); i++) { sum += lv.getValueAtRank(i); } return sum / lv.numLocations(); } private double getScoreVariance(LabelVector lv) { double mean = getScoreMean(lv); double squaredDifference = 0.0; for(int i=0; i<lv.numLocations(); i++) { squaredDifference += (mean - lv.getValueAtRank(i)) * (mean - lv.getValueAtRank(i)); } return squaredDifference / lv.numLocations(); } }
7,456
38.041885
147
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Pipe.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.logging.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.io.*; import java.rmi.dgc.VMID; import cc.mallet.types.Alphabet; import cc.mallet.types.AlphabetCarrying; import cc.mallet.types.Instance; import cc.mallet.types.SingleInstanceIterator; import cc.mallet.util.MalletLogger; /** The abstract superclass of all Pipes, which transform one data type to another. Pipes are most often used for feature extraction. <p> Although Pipe does not have any "abstract methods", in order to use a Pipe subclass you must override either the {@link pipe} method or the {@link newIteratorFrom} method. The former is appropriate when the pipe's processing of an Instance is strictly one-to-one. For every Instance coming in, there is exactly one Instance coming out. The later is appropriate when the pipe's processing may result in more or fewer Instances than arrive through its source iterator. <p> A pipe operates on an {@link cc.mallet.types.Instance}, which is a carrier of data. A pipe reads from and writes to fields in the Instance when it is requested to process the instance. It is up to the pipe which fields in the Instance it reads from and writes to, but usually a pipe will read its input from and write its output to the "data" field of an instance. <p> A pipe doesn't have any direct notion of input or output - it merely modifies instances that are handed to it. A set of helper classes, which implement the interface {@link Iterator<Instance>}, iterate over commonly encountered input data structures and feed the elements of these data structures to a pipe as instances. <p> A pipe is frequently used in conjunction with an {@link cc.mallet.types.InstanceList} As instances are added to the list, they are processed by the pipe associated with the instance list and the processed Instance is kept in the list. <p> In one common usage, a {@link cc.mallet.pipe.iterator.FileIterator} is given a list of directories to operate over. The FileIterator walks through each directory, creating an instance for each file and putting the data from the file in the data field of the instance. The directory of the file is stored in the target field of the instance. The FileIterator feeds instances to an InstanceList, which processes the instances through its associated pipe and keeps the results. <p> Pipes can be hierachically composed. In a typical usage, a SerialPipe is created, which holds other pipes in an ordered list. Piping an instance through a SerialPipe means piping the instance through each of the child pipes in sequence. <p> A pipe holds two separate Alphabets: one for the symbols (feature names) encountered in the data fields of the instances processed through the pipe, and one for the symbols (e.g. class labels) encountered in the target fields. <p> @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public abstract class Pipe implements Serializable, AlphabetCarrying { private static Logger logger = MalletLogger.getLogger(Pipe.class.getName()); Alphabet dataAlphabet = null; Alphabet targetAlphabet = null; boolean dataAlphabetResolved = false; boolean targetAlphabetResolved = false; boolean targetProcessing = true; VMID instanceId = new VMID(); //used in readResolve to distinguish persistent instances /** Construct a pipe with no data and target dictionaries */ public Pipe () { this (null, null); } /** * Construct pipe with data and target dictionaries. * Note that, since the default values of the dataDictClass and targetDictClass are null, * that if you specify null for one of the arguments here, this pipe step will not * ever create any corresponding dictionary for the argument. * @param dataDict Alphabet that will be used as the data dictionary. * @param targetDict Alphabet that will be used as the target dictionary. */ public Pipe (Alphabet dataDict, Alphabet targetDict) { this.dataAlphabet = dataDict; this.targetAlphabet = targetDict; } /** Each instance processed is tested by this method. * If it returns true, then the instance by-passes processing by this Pipe. * Common usage is to override this method in an anonymous inner sub-class of Pipe. * <code> SerialPipes sp = new SerialPipes (new Pipe[] { new CharSequence2TokenSequence() { public boolean precondition (Instance inst) { return inst instanceof CharSequence; } }, new TokenSequence2FeatureSequence(), }); * </code> */ // TODO "precondition" doesn't seem like the best name for this because if false, we don't fail, we pass thru. // Consider alternatives: skipIfTrue, passThru, skipPredicate, // TODO Actually, we might really want multiple different methods like this: // (a) if false, drop this instance and go on to next, (b) if false, pass through unchanged (current implementation) public boolean precondition (Instance inst) { return true; } // TODO Really this should be 'protected', but isn't for historical reasons. /** Really this should be 'protected', but isn't for historical reasons. */ public Instance pipe (Instance inst) { throw new UnsupportedOperationException ("Pipes of class "+this.getClass().getName() +" do not guarantee one-to-one mapping of Instances. Use 'newIteratorFrom' method instead."); } // TODO: Consider naming this simply "iterator" /** Given an InstanceIterator, return a new InstanceIterator whose instances * have also been processed by this pipe. If you override this method, be sure to check * and obey this pipe's {@link skipIfFalse(Instance)} method. */ public Iterator<Instance> newIteratorFrom (Iterator<Instance> source) { return new SimplePipeInstanceIterator (source); } /** A convenience method that will pull all instances from source through this pipe, * and return the results as an array. */ public Instance[] instancesFrom (Iterator<Instance> source) { source = this.newIteratorFrom(source); if (!source.hasNext()) return new Instance[0]; Instance inst = source.next(); if (!source.hasNext()) return new Instance[] {inst}; ArrayList<Instance> ret = new ArrayList<Instance>(); ret.add(inst); while (source.hasNext()) ret.add (source.next()); return (Instance[])ret.toArray(); } public Instance[] instancesFrom (Instance inst) { return instancesFrom (new SingleInstanceIterator(inst)); } // TODO Do we really want to encourage behavior like this? Consider removing this method. // This only works properly if the pipe is one-to-one. public Instance instanceFrom (Instance inst) { Instance[] results = instancesFrom (inst); if (results.length == 0) return null; else return results[0]; } /** Set whether input is taken from target field of instance during processing. * If argument is false, don't expect to find input material for the target. * By default, this is true. */ public void setTargetProcessing (boolean lookForAndProcessTarget) { targetProcessing = lookForAndProcessTarget; } /** Return true iff this pipe expects and processes information in the <tt>target</tt> slot. */ public boolean isTargetProcessing () { return targetProcessing; } // If this Pipe produces objects that use a Alphabet, this // method returns that dictionary. Even if this particular Pipe // doesn't use a Alphabet it may return non-null if // objects passing through it use a dictionary. // This method should not be called until the dictionary is really // needed, because it may set off a chain of events that "resolve" // the dictionaries of an entire pipeline, and generally this // resolution should not take place until the pipeline is completely // in place, and pipe() is being called. // xxx Perhaps desire to wait until pipe() is being called is unrealistic // and unnecessary. public Alphabet getDataAlphabet () { return dataAlphabet; } public Alphabet getTargetAlphabet () { return targetAlphabet; } public Alphabet getAlphabet () { return getDataAlphabet(); } public Alphabet[] getAlphabets() { return new Alphabet[] {getDataAlphabet(), getTargetAlphabet()}; } public boolean alphabetsMatch (AlphabetCarrying object) { Alphabet[] oas = object.getAlphabets(); return oas.length == 2 && oas[0].equals(getDataAlphabet()) && oas[1].equals(getTargetAlphabet()); } public void setDataAlphabet (Alphabet dDict) { if (dataAlphabet != null && dataAlphabet.size() > 0) throw new IllegalStateException ("Can't set this Pipe's Data Alphabet; it already has one."); dataAlphabet = dDict; } public boolean isDataAlphabetSet() { if (dataAlphabet != null && dataAlphabet.size() > 0) return true; return false; } public void setOrCheckDataAlphabet (Alphabet a) { if (dataAlphabet == null) dataAlphabet = a; else if (! dataAlphabet.equals(a)) throw new IllegalStateException ("Data alphabets do not match"); } public void setTargetAlphabet (Alphabet tDict) { if (targetAlphabet != null) throw new IllegalStateException ("Can't set this Pipe's Target Alphabet; it already has one."); targetAlphabet = tDict; } public void setOrCheckTargetAlphabet (Alphabet a) { if (targetAlphabet == null) targetAlphabet = a; else if (! targetAlphabet.equals(a)) throw new IllegalStateException ("Target alphabets do not match"); } protected void preceedingPipeDataAlphabetNotification (Alphabet a) { if (dataAlphabet == null) dataAlphabet = a; } protected void preceedingPipeTargetAlphabetNotification (Alphabet a) { if (targetAlphabet == null) targetAlphabet = a; } public VMID getInstanceId() { return instanceId;} // for debugging // The InstanceIterator used to implement the one-to-one pipe() method behavior. private class SimplePipeInstanceIterator implements Iterator<Instance> { Iterator<Instance> source; public SimplePipeInstanceIterator (Iterator<Instance> source) { this.source = source; } public boolean hasNext () { return source.hasNext(); } public Instance next() { Instance input = source.next(); if (!precondition(input)) return input; else return pipe (input); } /** Return the @link{Pipe} that processes @link{Instance}s going through this iterator. */ public Pipe getPipe () { return null; } public Iterator<Instance> getSourceIterator () { return source; } public void remove() { throw new IllegalStateException ("Not supported."); } } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(dataAlphabet); out.writeObject(targetAlphabet); out.writeBoolean(dataAlphabetResolved); out.writeBoolean(targetAlphabetResolved); out.writeBoolean(targetProcessing); out.writeObject(instanceId); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); dataAlphabet = (Alphabet) in.readObject(); targetAlphabet = (Alphabet) in.readObject(); dataAlphabetResolved = in.readBoolean(); targetAlphabetResolved = in.readBoolean(); targetProcessing = in.readBoolean(); instanceId = (VMID) in.readObject(); } private transient static HashMap deserializedEntries = new HashMap(); /** * This gets called after readObject; it lets the object decide whether * to return itself or return a previously read in version. * We use a hashMap of instanceIds to determine if we have already read * in this object. * @return * @throws ObjectStreamException */ public Object readResolve() throws ObjectStreamException { //System.out.println(" *** Pipe ReadResolve: instance id= " + instanceId); Object previous = deserializedEntries.get(instanceId); if (previous != null){ //System.out.println(" *** Pipe ReadResolve:Resolving to previous instance. instance id= " + instanceId); return previous; } if (instanceId != null){ deserializedEntries.put(instanceId, this); } //System.out.println(" *** Pipe ReadResolve: new instance. instance id= " + instanceId); return this; } }
12,802
35.166667
119
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TokenSequenceRemoveStopwords.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.HashSet; import java.util.ArrayList; import java.io.*; import cc.mallet.types.FeatureSequenceWithBigrams; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; /** * Remove tokens from the token sequence in the data field whose text is in the stopword list. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class TokenSequenceRemoveStopwords extends Pipe implements Serializable { // xxx Use a gnu.trove collection instead HashSet<String> stoplist = null; boolean caseSensitive = true; boolean markDeletions = false; private HashSet<String> newDefaultStopList () { HashSet<String> sl = new HashSet<String>(); for (int i = 0; i < stopwords.length; i++) sl.add (stopwords[i]); return sl; } public TokenSequenceRemoveStopwords (boolean caseSensitive, boolean markDeletions) { stoplist = newDefaultStopList(); this.caseSensitive = caseSensitive; this.markDeletions = markDeletions; } public TokenSequenceRemoveStopwords (boolean caseSensitive) { stoplist = newDefaultStopList(); this.caseSensitive = caseSensitive; } public TokenSequenceRemoveStopwords () { this (false); } /** * Load a stoplist from a file. * @param stoplistFile The file to load * @param encoding The encoding of the stoplist file (eg UTF-8) * @param includeDefault Whether to include the standard mallet English stoplist */ public TokenSequenceRemoveStopwords(File stoplistFile, String encoding, boolean includeDefault, boolean caseSensitive, boolean markDeletions) { if (! includeDefault) { stoplist = new HashSet<String>(); } else { stoplist = newDefaultStopList(); } addStopWords (fileToStringArray(stoplistFile, encoding)); this.caseSensitive = caseSensitive; this.markDeletions = markDeletions; } public TokenSequenceRemoveStopwords setCaseSensitive (boolean flag) { this.caseSensitive = flag; return this; } public TokenSequenceRemoveStopwords setMarkDeletions (boolean flag) { this.markDeletions = flag; return this; } public TokenSequenceRemoveStopwords addStopWords (String[] words) { for (int i = 0; i < words.length; i++) stoplist.add (words[i]); return this; } public TokenSequenceRemoveStopwords removeStopWords (String[] words) { for (int i = 0; i < words.length; i++) stoplist.remove (words[i]); return this; } /** Remove whitespace-separated tokens in file "wordlist" to the stoplist. */ public TokenSequenceRemoveStopwords removeStopWords (File wordlist) { this.removeStopWords (fileToStringArray(wordlist, null)); return this; } /** Add whitespace-separated tokens in file "wordlist" to the stoplist. */ public TokenSequenceRemoveStopwords addStopWords (File wordlist) { if (wordlist != null) this.addStopWords (fileToStringArray(wordlist, null)); return this; } private String[] fileToStringArray (File f, String encoding) { ArrayList<String> wordarray = new ArrayList<String>(); try { BufferedReader input = null; if (encoding == null) { input = new BufferedReader (new FileReader (f)); } else { input = new BufferedReader( new InputStreamReader( new FileInputStream(f), encoding )); } String line; while (( line = input.readLine()) != null) { String[] words = line.split ("\\s+"); for (int i = 0; i < words.length; i++) wordarray.add (words[i]); } } catch (IOException e) { throw new IllegalArgumentException("Trouble reading file "+f); } return (String[]) wordarray.toArray(new String[]{}); } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); // xxx This doesn't seem so efficient. Perhaps have TokenSequence // use a LinkedList, and remove Tokens from it? -? // But a LinkedList implementation of TokenSequence would be quite inefficient -AKM TokenSequence ret = new TokenSequence (); Token prevToken = null; for (int i = 0; i < ts.size(); i++) { Token t = ts.get(i); if (! stoplist.contains (caseSensitive ? t.getText() : t.getText().toLowerCase())) { // xxx Should we instead make and add a copy of the Token? ret.add (t); prevToken = t; } else if (markDeletions && prevToken != null) prevToken.setProperty (FeatureSequenceWithBigrams.deletionMark, t.getText()); } carrier.setData(ret); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 2; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeBoolean(caseSensitive); out.writeBoolean(markDeletions); out.writeObject(stoplist); // New as of CURRENT_SERIAL_VERSION 2 } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); caseSensitive = in.readBoolean(); if (version > 0) markDeletions = in.readBoolean(); if (version > 1) { stoplist = (HashSet<String>) in.readObject(); } } static final String[] stopwords = { "a", "able", "about", "above", "according", "accordingly", "across", "actually", "after", "afterwards", "again", "against", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "appear", "appreciate", "appropriate", "are", "around", "as", "aside", "ask", "asking", "associated", "at", "available", "away", "awfully", "b", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "both", "brief", "but", "by", "c", "came", "can", "cannot", "cant", "cause", "causes", "certain", "certainly", "changes", "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "course", "currently", "d", "definitely", "described", "despite", "did", "different", "do", "does", "doing", "done", "down", "downwards", "during", "e", "each", "edu", "eg", "eight", "either", "else", "elsewhere", "enough", "entirely", "especially", "et", "etc", "even", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "f", "far", "few", "fifth", "first", "five", "followed", "following", "follows", "for", "former", "formerly", "forth", "four", "from", "further", "furthermore", "g", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got", "gotten", "greetings", "h", "had", "happens", "hardly", "has", "have", "having", "he", "hello", "help", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "hi", "him", "himself", "his", "hither", "hopefully", "how", "howbeit", "however", "i", "ie", "if", "ignored", "immediate", "in", "inasmuch", "inc", "indeed", "indicate", "indicated", "indicates", "inner", "insofar", "instead", "into", "inward", "is", "it", "its", "itself", "j", "just", "k", "keep", "keeps", "kept", "know", "knows", "known", "l", "last", "lately", "later", "latter", "latterly", "least", "less", "lest", "let", "like", "liked", "likely", "little", "look", "looking", "looks", "ltd", "m", "mainly", "many", "may", "maybe", "me", "mean", "meanwhile", "merely", "might", "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "n", "name", "namely", "nd", "near", "nearly", "necessary", "need", "needs", "neither", "never", "nevertheless", "new", "next", "nine", "no", "nobody", "non", "none", "noone", "nor", "normally", "not", "nothing", "novel", "now", "nowhere", "o", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on", "once", "one", "ones", "only", "onto", "or", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "own", "p", "particular", "particularly", "per", "perhaps", "placed", "please", "plus", "possible", "presumably", "probably", "provides", "q", "que", "quite", "qv", "r", "rather", "rd", "re", "really", "reasonably", "regarding", "regardless", "regards", "relatively", "respectively", "right", "s", "said", "same", "saw", "say", "saying", "says", "second", "secondly", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "should", "since", "six", "so", "some", "somebody", "somehow", "someone", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup", "sure", "t", "take", "taken", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "theres", "thereupon", "these", "they", "think", "third", "this", "thorough", "thoroughly", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "twice", "two", "u", "un", "under", "unfortunately", "unless", "unlikely", "until", "unto", "up", "upon", "us", "use", "used", "useful", "uses", "using", "usually", "uucp", "v", "value", "various", "very", "via", "viz", "vs", "w", "want", "wants", "was", "way", "we", "welcome", "well", "went", "were", "what", "whatever", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will", "willing", "wish", "with", "within", "without", "wonder", "would", "would", "x", "y", "yes", "yet", "you", "your", "yours", "yourself", "yourselves", "z", "zero", // stop words for paper abstracts // "abstract", //"paper", //"presents", //"discuss", //"discusses", //"conclude", //"concludes", //"based", //"approach" }; //stopwords for french, added by Limin Yao static final String[] stopwordsFrench = { "fut", "S", "ces", "ral", "new", "tr", "arm", "y", "autres", "o", "tait", "dont", "ann", "apr", "sous", "ans", "cette", "politique", "of", "c", "contre", "leur", "ville", "fait", "res", "on", "deux", "cle", "v", "publique", "france", "te", "guerre", "sident", "unis", "mais", "entre", "aussi", "tat", "ais", "ses", "sa", "ont", "tre", "d", "pays", "en", "Il", "tats", "comme", "am", "si", "c", "fran", "pas", "g", "qu", "R", "aux", "ce", "f", "p", "ne", "son", "me", "avec", "l", "se", "ou", "sont", "il", "Les", "re", "plus", "m", "es", "pr", "la", "sur", "que", "pour", "modifier", "a", "qui", "Le", "t", "n", "au", "dans", "une", "par", "un", "r", "est", "e", "du", "s", "les", "en", "des", "le", "et", "l", "d", "la", "de", }; }
12,725
14.078199
96
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureVectorSequence2FeatureVectors.java
package cc.mallet.pipe; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; import cc.mallet.types.FeatureVectorSequence; import cc.mallet.types.Instance; import cc.mallet.types.LabelSequence; /** Given instances with a FeatureVectorSequence in the data field, break up the sequence into * the individual FeatureVectors, producing one FeatureVector per Instance. */ public class FeatureVectorSequence2FeatureVectors extends Pipe { final class FeatureVectorIterator implements Iterator<Instance> { Iterator<Instance> superIterator; Instance superInstance; Iterator dataSubiterator, targetSubiterator; int count = 0; public FeatureVectorIterator (Iterator<Instance> inputIterator) { superInstance = inputIterator.next(); dataSubiterator = ((FeatureVectorSequence)superInstance.getData()).iterator(); targetSubiterator = ((LabelSequence)superInstance.getTarget()).iterator(); } public Instance next () { if (!dataSubiterator.hasNext()) { assert (superIterator.hasNext()); superInstance = superIterator.next(); dataSubiterator = ((FeatureVectorSequence)superInstance.getData()).iterator(); targetSubiterator = ((LabelSequence)superInstance.getTarget()).iterator(); } // We are assuming sequences don't have zero length assert (dataSubiterator.hasNext()); assert (targetSubiterator.hasNext()); return new Instance (dataSubiterator.next(), targetSubiterator.next(), superInstance.getSource()+" tokensequence:"+count++, null); } public boolean hasNext () { return dataSubiterator.hasNext() || superIterator.hasNext(); } public void remove () { } } public FeatureVectorSequence2FeatureVectors() {} public Iterator<Instance> newIteratorFrom (Iterator<Instance> inputIterator) { return new FeatureVectorIterator (inputIterator); } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
2,254
34.234375
95
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/CharSequenceRemoveHTML.java
/* Copyright (C) 2006 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import javax.swing.text.html.*; import cc.mallet.pipe.iterator.FileIterator; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import java.io.*; /** * This pipe removes HTML from a CharSequence. The HTML is actually parsed here, * so we should have less HTML slipping through... but it is almost certainly * much slower than a regular expression, and could fail on broken HTML. * * @author Greg Druck <a href="mailto:[email protected]">[email protected]</a> */ public class CharSequenceRemoveHTML extends Pipe { public Instance pipe(Instance carrier) { String text = ((CharSequence) carrier.getData()).toString(); // I take these out ahead of time because the // Java HTML parser seems to die here. text = text.replaceAll("\\<NOFRAMES\\>",""); text = text.replaceAll("\\<\\/NOFRAMES\\>",""); ParserGetter kit = new ParserGetter(); HTMLEditorKit.Parser parser = kit.getParser(); HTMLEditorKit.ParserCallback callback = new TagStripper(); try { StringReader r = new StringReader(text); parser.parse(r, callback, true); } catch (IOException e) { System.err.println(e); } String result = ((TagStripper) callback).getText(); carrier.setData((CharSequence) result); return carrier; } private class TagStripper extends HTMLEditorKit.ParserCallback { private String text; public TagStripper() { text = ""; } public void handleText(char[] txt, int position) { for (int index = 0; index < txt.length; index++) { text += txt[index]; } text += "\n"; } public String getText() { return text; } } private class ParserGetter extends HTMLEditorKit { // purely to make this method public public HTMLEditorKit.Parser getParser() { return super.getParser(); } } public static void main(String[] args) { String htmldir = args[0]; Pipe pipe = new SerialPipes(new Pipe[] { new Input2CharSequence(), new CharSequenceRemoveHTML() }); InstanceList list = new InstanceList(pipe); list.addThruPipe(new FileIterator(htmldir, FileIterator.STARTING_DIRECTORIES)); for (int index = 0; index < list.size(); index++) { Instance inst = list.get(index); System.err.println(inst.getData()); } } }
2,658
27.287234
82
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/PipeException.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; public class PipeException extends Exception { }
598
27.52381
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/Csv2Array.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.util.logging.*; import java.lang.reflect.Array; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; import cc.mallet.types.Labeling; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.MalletLogger; /** Converts a string of comma separated values to an array. To be used prior to {@link Array2FeatureVector}. Note that this class assumes that each location of the line corresponds to a feature index (i.e. "dense" representation) eg: instance 1: 1,0,0,1,0,0,1 << feature alphabet size = 7 instance 2: 0,0,1,0,0,0,1 << feature alphabet size = 7 @author Aron Culotta */ public class Csv2Array extends Pipe { CharSequenceLexer lexer; int numberFeatures = -1; private static Logger logger = MalletLogger.getLogger(Csv2Array.class.getName()); public Csv2Array () { this.lexer = new CharSequenceLexer ("([^,]+)"); } public Csv2Array (String regex) { this.lexer = new CharSequenceLexer (regex); } public Csv2Array (CharSequenceLexer l) { this.lexer = l; } /** Convert the data in an <CODE>Instance</CODE> from a CharSequence * of comma-separated-values to an array, where each index is the * feature name. */ public Instance pipe( Instance carrier ) { CharSequence c = (CharSequence)carrier.getData(); int nf = countNumberFeatures (c); if (numberFeatures == -1) // first instance seen numberFeatures = nf; else if (numberFeatures != nf) throw new IllegalArgumentException ("Instances must have same-length feature vectors. length_i: " + numberFeatures + " length_j: " + nf); double[] feats = new double[numberFeatures]; lexer.setCharSequence (c); int i=0; while (lexer.hasNext()) feats[i++] = Double.parseDouble ((String)lexer.next()); carrier.setData (feats); return carrier; } private int countNumberFeatures (CharSequence c) { String s = c.toString(); int ret = 0; int pos = 0; while ((pos = s.indexOf (",", pos) + 1) != 0) ret++; return ret+1; } }
2,507
27.827586
140
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/SelectiveSGML2TokenSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import java.net.URI; import java.util.regex.*; import java.util.Set; import cc.mallet.types.Instance; import cc.mallet.types.Token; import cc.mallet.types.TokenSequence; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.Lexer; /** Similar to {@link SGML2TokenSequence}, except that only the tags listed in <code>allowedTags</code> are converted to {@link Label}s. @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ public class SelectiveSGML2TokenSequence extends Pipe implements Serializable { Pattern sgmlPattern = Pattern.compile ("</?([^>]*)>"); CharSequenceLexer lexer; String backgroundTag; Set allowedTags; /** @param lexer to tokenize input @param backgroundTag default tag when not in any other tag @param allowed set of tags (Strings) that will be converted to labels */ public SelectiveSGML2TokenSequence (CharSequenceLexer lexer, String backgroundTag, Set allowed) { this.lexer = lexer; this.backgroundTag = backgroundTag; this.allowedTags = allowed; } public SelectiveSGML2TokenSequence (String regex, String backgroundTag, Set allowed) { this (new CharSequenceLexer (regex), backgroundTag, allowed); } public SelectiveSGML2TokenSequence (Set allowed) { this (new CharSequenceLexer(), "O", allowed); } public SelectiveSGML2TokenSequence (CharSequenceLexer lex, Set allowed) { this (lex, "O", allowed); } public Instance pipe (Instance carrier) { if (!(carrier.getData() instanceof CharSequence)) throw new ClassCastException ("carrier.data is a " + carrier.getData().getClass().getName() + " not a CharSequence"); TokenSequence dataTokens = new TokenSequence (); TokenSequence targetTokens = new TokenSequence (); CharSequence string = (CharSequence) carrier.getData(); String tag = backgroundTag; String nextTag = backgroundTag; Matcher m = sgmlPattern.matcher (string); int textStart = 0; int textEnd = 0; int nextStart = 0; boolean done = false; while (!done) { done = !findNextValidMatch (m); if (done) textEnd = string.length()-1; else { String sgml = m.group(); int groupCount = m.groupCount(); if (sgml.charAt(1) == '/') nextTag = backgroundTag; else{ nextTag = m.group(0); nextTag = sgml.substring(1, sgml.length()-1); } nextStart = m.end(); textEnd = m.start(); } if (textEnd - textStart > 0) { lexer.setCharSequence (string.subSequence (textStart, textEnd)); while (lexer.hasNext()) { dataTokens.add (new Token ((String) lexer.next())); targetTokens.add (new Token (tag)); } } textStart = nextStart; tag = nextTag; } carrier.setData(dataTokens); carrier.setTarget(targetTokens); carrier.setSource(dataTokens); return carrier; } /** Finds the next match contained in <code> allowedTags </code>. */ private boolean findNextValidMatch (Matcher m) { if (!m.find ()) return false; String sgml = m.group(); int start = m.start (); int first = 1; int last = sgml.length() - 1; if (sgml.charAt(1) == '/') first = 2; sgml = sgml.substring (first, last); if (allowedTags.contains (sgml)) { m.find (start); return true; } else return findNextValidMatch (m); } public String toString () { String ret = "sgml pattern: " + sgmlPattern.toString(); ret += "\nlexer: " + lexer.getPattern().toString(); ret += "\nbg tag: " + backgroundTag.toString(); ret += "\nallowedHash: " + allowedTags + "\n"; return ret; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(sgmlPattern); out.writeObject(lexer); out.writeObject(backgroundTag); out.writeObject(allowedTags); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); sgmlPattern = (Pattern) in.readObject(); lexer = (CharSequenceLexer) in.readObject(); backgroundTag = (String) in.readObject(); allowedTags = (Set) in.readObject(); } }
4,691
27.436364
96
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/PrintTokenSequenceFeatures.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; import cc.mallet.util.*; /** * Print properties of the token sequence in the data field and the corresponding value * of any token in a token sequence or feature in a featur sequence in the target field. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class PrintTokenSequenceFeatures extends Pipe implements Serializable { String prefix = null; public PrintTokenSequenceFeatures (String prefix) { this.prefix = prefix; } public PrintTokenSequenceFeatures () { } public Instance pipe (Instance carrier) { TokenSequence ts = (TokenSequence) carrier.getData(); TokenSequence targets = carrier.getTarget() instanceof TokenSequence ? (TokenSequence)carrier.getTarget() : null; TokenSequence source = carrier.getSource() instanceof TokenSequence ? (TokenSequence)carrier.getSource() : null; StringBuffer sb = new StringBuffer (); if (prefix != null) sb.append (prefix); sb.append ("name: "+carrier.getName()+"\n"); for (int i = 0; i < ts.size(); i++) { if (source != null) { sb.append (source.get(i).getText()); sb.append (' '); } if (carrier.getTarget() instanceof TokenSequence) { sb.append (((TokenSequence)carrier.getTarget()).get(i).getText()); sb.append (' '); } if (carrier.getTarget() instanceof FeatureSequence) { sb.append (((FeatureSequence)carrier.getTarget()).getObjectAtPosition(i).toString()); sb.append (' '); } PropertyList pl = ts.get(i).getFeatures(); if (pl != null) { PropertyList.Iterator iter = pl.iterator(); while (iter.hasNext()) { iter.next(); double v = iter.getNumericValue(); if (v == 1.0) sb.append (iter.getKey()); else sb.append (iter.getKey()+'='+v); sb.append (' '); } } sb.append ('\n'); } System.out.print (sb.toString()); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); out.writeObject(prefix); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); prefix = (String) in.readObject(); } }
2,804
28.840426
115
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/FeatureVectorConjunctions.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** Include in the FeatureVector conjunctions of all its features. Only works with binary FeatureVectors. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.FeatureSequence; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; // This class does not insist on getting its own Alphabet because it can rely on getting // it from the FeatureSequence input. /** Include in the FeatureVector conjunctions of all its features. Only works with binary FeatureVectors. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class FeatureVectorConjunctions extends Pipe implements Serializable { public FeatureVectorConjunctions () { super(); } public Instance pipe (Instance carrier) { FeatureVector fv = (FeatureVector) carrier.getData(); carrier.setData(new FeatureVector (fv, fv.getAlphabet(), null, null)); return carrier; } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,825
28.451613
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/TargetStringToFeatures.java
package cc.mallet.pipe; import cc.mallet.types.*; import cc.mallet.pipe.*; import java.io.Serializable; import java.util.Arrays; public class TargetStringToFeatures extends Pipe implements Serializable { public TargetStringToFeatures () { super(null, new Alphabet()); } public Instance pipe(Instance carrier) { if (! (carrier.getTarget() instanceof String)) { throw new IllegalArgumentException("Target must be of type String"); } String featuresLine = (String) carrier.getTarget(); String[] features = featuresLine.split(",?\\s+"); double[] values = new double[ features.length ]; Arrays.fill(values, 1.0); for (int i=0; i<features.length; i++) { // Support the syntax "FEATURE=0.000342 OTHER_FEATURE=-2.32423" \ if (features[i].indexOf("=") != -1) { String[] keyValuePair = features[i].split("="); features[i] = keyValuePair[0]; values[i] = Double.parseDouble(keyValuePair[1]); } // ensure that the feature has a spot in the alphabet \ getTargetAlphabet().lookupIndex(features[i], true); } FeatureVector target = new FeatureVector(getTargetAlphabet(), features, values); carrier.setTarget(target); return carrier; } private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; }
1,622
30.211538
119
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/InstanceListTrimFeaturesByCount.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe; import java.io.*; import cc.mallet.types.*; /** * Unimplemented. @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class InstanceListTrimFeaturesByCount extends Pipe implements Serializable { int minCount; public InstanceListTrimFeaturesByCount (int minCount) { super (new Alphabet(), null); this.minCount = minCount; } public Instance pipe (Instance carrier) { // xxx Not yet implemented! throw new UnsupportedOperationException ("Not yet implemented"); } // Serialization private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject (ObjectOutputStream out) throws IOException { out.writeInt (CURRENT_SERIAL_VERSION); } private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int version = in.readInt (); } }
1,353
25.038462
92
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/RandomTokenSequenceIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.net.URI; import java.util.Iterator; import java.util.logging.*; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.iterator.PipeInputIterator; import cc.mallet.types.Alphabet; import cc.mallet.types.Dirichlet; import cc.mallet.types.Instance; import cc.mallet.types.Label; import cc.mallet.types.Multinomial; import cc.mallet.types.TokenSequence; import cc.mallet.util.MalletLogger; import cc.mallet.util.Randoms; public class RandomTokenSequenceIterator implements Iterator<Instance> { private static Logger logger = MalletLogger.getLogger(RandomTokenSequenceIterator.class.getName()); Randoms r; Dirichlet classCentroidDistribution; double classCentroidAvergeAlphaMean; double classCentroidAvergeAlphaVariance; double featureVectorSizePoissonLambda; double classInstanceCountPoissonLamba; String[] classNames; int[] numInstancesPerClass; // indexed over classes Dirichlet[] classCentroid; // indexed over classes int currentClassIndex; int currentInstanceIndex; public RandomTokenSequenceIterator (Randoms r, // the generator of all random-ness used here Dirichlet classCentroidDistribution, // includes a Alphabet double classCentroidAvergeAlphaMean, // Gaussian mean on the sum of alphas double classCentroidAvergeAlphaVariance, // Gaussian variance on the sum of alphas double featureVectorSizePoissonLambda, double classInstanceCountPoissonLamba, String[] classNames) { this.r = r; this.classCentroidDistribution = classCentroidDistribution; assert (classCentroidDistribution.getAlphabet() instanceof Alphabet); this.classCentroidAvergeAlphaMean = classCentroidAvergeAlphaMean; this.classCentroidAvergeAlphaVariance = classCentroidAvergeAlphaVariance; this.featureVectorSizePoissonLambda = featureVectorSizePoissonLambda; this.classInstanceCountPoissonLamba = classInstanceCountPoissonLamba; this.classNames = classNames; this.numInstancesPerClass = new int[classNames.length]; this.classCentroid = new Dirichlet[classNames.length]; for (int i = 0; i < classNames.length; i++) { logger.fine ("classCentroidAvergeAlphaMean = "+classCentroidAvergeAlphaMean); double aveAlpha = r.nextGaussian (classCentroidAvergeAlphaMean, classCentroidAvergeAlphaVariance); logger.fine ("aveAlpha = "+aveAlpha); classCentroid[i] = classCentroidDistribution.randomDirichlet (r, aveAlpha); //logger.fine ("Dirichlet for class "+classNames[i]); classCentroid[i].print(); } reset (); } public RandomTokenSequenceIterator (Randoms r, Alphabet vocab, String[] classnames) { this (r, new Dirichlet(vocab, 2.0), 30, 0, 10, 20, classnames); } public Alphabet getAlphabet () { return classCentroidDistribution.getAlphabet(); } private static Alphabet dictOfSize (int size) { Alphabet ret = new Alphabet (); for (int i = 0; i < size; i++) ret.lookupIndex ("feature"+i); return ret; } private static String[] classNamesOfSize (int size) { String[] ret = new String[size]; for (int i = 0; i < size; i++) ret[i] = "class"+i; return ret; } public RandomTokenSequenceIterator (Randoms r, int vocabSize, int numClasses) { this (r, new Dirichlet(dictOfSize(vocabSize), 2.0), 30, 0, 10, 20, classNamesOfSize(numClasses)); } public void reset () { for (int i = 0; i < classNames.length; i++) { this.numInstancesPerClass[i] = r.nextPoisson (classInstanceCountPoissonLamba); logger.fine ("Class "+classNames[i]+" will have " +numInstancesPerClass[i]+" instances."); } this.currentClassIndex = classNames.length - 1; this.currentInstanceIndex = numInstancesPerClass[currentClassIndex] - 1; } public Instance next () { if (currentInstanceIndex < 0) { if (currentClassIndex <= 0) throw new IllegalStateException ("No next TokenSequence."); currentClassIndex--; currentInstanceIndex = numInstancesPerClass[currentClassIndex] - 1; } URI uri = null; try { uri = new URI ("random:" + classNames[currentClassIndex] + "/" + currentInstanceIndex); } catch (Exception e) {e.printStackTrace(); throw new IllegalStateException (); } //xxx Producing small numbers? int randomSize = r.nextPoisson (featureVectorSizePoissonLambda); int randomSize = (int)featureVectorSizePoissonLambda; TokenSequence ts = classCentroid[currentClassIndex].randomTokenSequence (r, randomSize); //logger.fine ("FeatureVector "+currentClassIndex+" "+currentInstanceIndex); fv.print(); currentInstanceIndex--; return new Instance (ts, classNames[currentClassIndex], uri, null); } public boolean hasNext () { return ! (currentClassIndex <= 0 && currentInstanceIndex <= 0); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
5,504
35.456954
100
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/FileIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.ArrayList; import java.util.Iterator; import java.net.URI; import java.util.regex.*; import java.io.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.Label; import cc.mallet.util.Strings; /** * An iterator that generates instances from an initial * directory or set of directories. The iterator will recurse through sub-directories. * Each filename becomes the data field of an instance, and the result of * a user-specified regular expression pattern applied to the filename becomes * the target value of the instance. * <p> * In document classification it is common that the file name in the data field * will be subsequently processed by one or more pipes until it contains a feature vector. * The pattern applied to the file name is often * used to extract a directory name * that will be used as the true label of the instance; this label is kept in the target * field. * * * @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ public class FileIterator implements Iterator<Instance> { FileFilter fileFilter; ArrayList<File> fileArray; Iterator<File> subIterator; Pattern targetPattern; // Set target slot to string coming from 1st group of this Pattern File[] startingDirectories; int[] minFileIndex; int fileCount; int commonPrefixIndex; /** Special value that means to use the directories[i].getPath() as the target name */ /** Use as label names the directories specified in the constructor, * optionally removing common prefix of all starting directories */ // [email protected] 08/09/10: // generalize regular expressions to work with Windows filenames public static final String sep = "\\" + File.separatorChar; public static final Pattern STARTING_DIRECTORIES = Pattern.compile ("_STARTING_DIRECTORIES_"); /** Use as label names the first directory in the filename. */ public static final Pattern FIRST_DIRECTORY = Pattern.compile (sep+"?([^"+sep+"]*)"+sep+".+"); /** Use as label name the last directory in the filename. */ public static final Pattern LAST_DIRECTORY = Pattern.compile(".*"+sep+"([^"+sep+"]+)"+sep+"[^"+sep+"]+"); // was ("([^/]*)/[^/]+"); /** Use as label names all the directory names in the filename. */ public static final Pattern ALL_DIRECTORIES = Pattern.compile ("^(.*)"+sep+"[^"+sep+"]+"); // added by Fuchun Peng public ArrayList<File> getFileArray() { return fileArray; } /** * Construct a FileIterator that will supply filenames within initial directories * as instances * @param directories Array of directories to collect files from * @param fileFilter class implementing interface FileFilter that will decide which names to accept. * May be null. * @param targetPattern regex Pattern applied to the filename whose first parenthesized group * on matching is taken to be the target value of the generated instance. The pattern is applied to * the directory with the matcher.find() method. If null, then all instances * will have target null. * @param removeCommonPrefix boolean that modifies the behavior of the STARTING_DIRECTORIES pattern, * removing the common prefix of all initially specified directories, * leaving the remainder of each filename as the target value. * */ protected FileIterator(File[] directories, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) { this.startingDirectories = directories; this.fileFilter = fileFilter; this.minFileIndex = new int[directories.length]; this.fileArray = new ArrayList<File> (); this.targetPattern = targetPattern; for (int i = 0; i < directories.length; i++) { if (!directories[i].isDirectory()) throw new IllegalArgumentException (directories[i].getAbsolutePath() + " is not a directory."); minFileIndex[i] = fileArray.size(); fillFileArray (directories[i], fileFilter, fileArray); } this.subIterator = fileArray.iterator(); this.fileCount = 0; String[] dirStrings = new String[directories.length]; for (int i = 0; i < directories.length; i++) dirStrings[i] = directories[i].toString(); if (removeCommonPrefix) this.commonPrefixIndex = Strings.commonPrefixIndex (dirStrings); //print the files // System.out.println("FileIterator fileArray"); // for(int i=0; i<fileArray.size(); i++){ // File file = (File) fileArray.get(i); // System.out.println(file.toString()); // } } public FileIterator (File[] directories, FileFilter fileFilter, Pattern targetPattern) { this (directories, fileFilter, targetPattern, false); } /** Iterate over Files that pass the fileFilter test, setting... */ public FileIterator (File[] directories, Pattern targetPattern) { this (directories, null, targetPattern); } public FileIterator (File[] directories, Pattern targetPattern, boolean removeCommonPrefix ) { this (directories, null, targetPattern, removeCommonPrefix); } public static File[] stringArray2FileArray (String[] sa) { File[] ret = new File[sa.length]; for (int i = 0; i < sa.length; i++) ret[i] = new File (sa[i]); return ret; } public FileIterator (String[] directories, FileFilter ff) { this (stringArray2FileArray(directories), ff, null); } public FileIterator (String[] directories, String targetPattern) { this (stringArray2FileArray(directories), Pattern.compile(targetPattern)); } public FileIterator (String[] directories, Pattern targetPattern) { this (stringArray2FileArray(directories), targetPattern); } public FileIterator (String[] directories, Pattern targetPattern, boolean removeCommonPrefix) { this (stringArray2FileArray(directories), targetPattern, removeCommonPrefix); } public FileIterator (File directory, FileFilter fileFilter, Pattern targetPattern) { this (new File[] {directory}, fileFilter, targetPattern); } public FileIterator (File directory, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) { this (new File[] {directory}, fileFilter, targetPattern, removeCommonPrefix); } public FileIterator (File directory, FileFilter fileFilter) { this (new File[] {directory}, fileFilter, null); } public FileIterator (File directory, Pattern targetPattern) { this (new File[] {directory}, null, targetPattern); } public FileIterator (File directory, Pattern targetPattern, boolean removeCommonPrefix) { this (new File[] {directory}, null, targetPattern, removeCommonPrefix); } public FileIterator (String directory, Pattern targetPattern) { this (new File[] {new File(directory)}, null, targetPattern); } public FileIterator (String directory, Pattern targetPattern, boolean removeCommonPrefix) { this (new File[] {new File(directory)}, null, targetPattern, removeCommonPrefix); } public FileIterator (File directory) { this (new File[] {directory}, null, null, false); } public FileIterator (String directory) { this (new File[] {new File(directory)}, null, null, false); } public FileIterator (String directory, FileFilter filter) { this (new File[] {new File(directory) }, filter, null); } private int fillFileArray (File directory, FileFilter filter, ArrayList<File> files) { int count = 0; File[] directoryContents = directory.listFiles(); for (int i = 0; i < directoryContents.length; i++) { if (directoryContents[i].isDirectory()) count += fillFileArray (directoryContents[i], filter, files); else if (filter == null || filter.accept(directoryContents[i])) { files.add (directoryContents[i]); count++; } } return count; } // The PipeInputIterator interface public Instance next () { File nextFile = subIterator.next(); String path = nextFile.getAbsolutePath(); String targetName = null; if (targetPattern == STARTING_DIRECTORIES) { int i; for (i = 0; i < minFileIndex.length; i++) if (minFileIndex[i] > fileCount) break; targetName = startingDirectories[--i].getPath().substring(commonPrefixIndex); } else if (targetPattern != null) { Matcher m = targetPattern.matcher(path); if (m.find ()){ targetName = m.group (1); } } fileCount++; return new Instance (nextFile, targetName, nextFile.toURI(), null); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } // culotta - 9.11.03 public File nextFile () { return subIterator.next(); } public boolean hasNext () { return subIterator.hasNext(); } }
9,348
32.629496
122
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/RandomFeatureVectorIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.net.URI; import java.util.Iterator; import java.util.logging.*; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.iterator.PipeInputIterator; import cc.mallet.types.Alphabet; import cc.mallet.types.Dirichlet; import cc.mallet.types.FeatureVector; import cc.mallet.types.Instance; import cc.mallet.types.Label; import cc.mallet.types.LabelAlphabet; import cc.mallet.types.Multinomial; import cc.mallet.util.MalletLogger; import cc.mallet.util.Randoms; public class RandomFeatureVectorIterator implements Iterator<Instance> { private static Logger logger = MalletLogger.getLogger(RandomFeatureVectorIterator.class.getName()); Randoms r; Dirichlet classCentroidDistribution; double classCentroidAvergeAlphaMean; double classCentroidAvergeAlphaVariance; double featureVectorSizePoissonLambda; double classInstanceCountPoissonLamba; String[] classNames; int[] numInstancesPerClass; // indexed over classes Dirichlet[] classCentroid; // indexed over classes int currentClassIndex; int currentInstanceIndex; public RandomFeatureVectorIterator (Randoms r, // the generator of all random-ness used here Dirichlet classCentroidDistribution, // includes a Alphabet double classCentroidAvergeAlphaMean, // Gaussian mean on the sum of alphas double classCentroidAvergeAlphaVariance, // Gaussian variance on the sum of alphas double featureVectorSizePoissonLambda, double classInstanceCountPoissonLamba, String[] classNames) { this.r = r; this.classCentroidDistribution = classCentroidDistribution; assert (classCentroidDistribution.getAlphabet() instanceof Alphabet); this.classCentroidAvergeAlphaMean = classCentroidAvergeAlphaMean; this.classCentroidAvergeAlphaVariance = classCentroidAvergeAlphaVariance; this.featureVectorSizePoissonLambda = featureVectorSizePoissonLambda; this.classInstanceCountPoissonLamba = classInstanceCountPoissonLamba; this.classNames = classNames; this.numInstancesPerClass = new int[classNames.length]; this.classCentroid = new Dirichlet[classNames.length]; for (int i = 0; i < classNames.length; i++) { logger.fine ("classCentroidAvergeAlphaMean = "+classCentroidAvergeAlphaMean); double aveAlpha = r.nextGaussian (classCentroidAvergeAlphaMean, classCentroidAvergeAlphaVariance); logger.fine ("aveAlpha = "+aveAlpha); classCentroid[i] = classCentroidDistribution.randomDirichlet (r, aveAlpha); //logger.fine ("Dirichlet for class "+classNames[i]); classCentroid[i].print(); } reset (); } public RandomFeatureVectorIterator (Randoms r, Alphabet vocab, String[] classnames) { this (r, new Dirichlet(vocab, 2.0), 30, 0, 10, 20, classnames); } public Alphabet getAlphabet () { return classCentroidDistribution.getAlphabet(); } private static Alphabet dictOfSize (int size) { Alphabet ret = new Alphabet (); for (int i = 0; i < size; i++) ret.lookupIndex ("feature"+i); return ret; } private static String[] classNamesOfSize (int size) { String[] ret = new String[size]; for (int i = 0; i < size; i++) ret[i] = "class"+i; return ret; } public RandomFeatureVectorIterator (Randoms r, int vocabSize, int numClasses) { this (r, new Dirichlet(dictOfSize(vocabSize), 2.0), 30, 0, 10, 20, classNamesOfSize(numClasses)); } public void reset () { for (int i = 0; i < classNames.length; i++) { this.numInstancesPerClass[i] = r.nextPoisson (classInstanceCountPoissonLamba); logger.fine ("Class "+classNames[i]+" will have " +numInstancesPerClass[i]+" instances."); } this.currentClassIndex = classNames.length - 1; this.currentInstanceIndex = numInstancesPerClass[currentClassIndex] - 1; } public LabelAlphabet getLabelAlphabet () { return null; } public Instance next () { if (currentInstanceIndex < 0) { if (currentClassIndex <= 0) throw new IllegalStateException ("No next FeatureVector."); currentClassIndex--; currentInstanceIndex = numInstancesPerClass[currentClassIndex] - 1; } URI uri = null; try { uri = new URI ("random:" + classNames[currentClassIndex] + "/" + currentInstanceIndex); } catch (Exception e) {e.printStackTrace(); throw new IllegalStateException (); } //xxx Producing small numbers? int randomSize = r.nextPoisson (featureVectorSizePoissonLambda); int randomSize = (int)featureVectorSizePoissonLambda; FeatureVector fv = classCentroid[currentClassIndex].randomFeatureVector (r, randomSize); //logger.fine ("FeatureVector "+currentClassIndex+" "+currentInstanceIndex); fv.print(); currentInstanceIndex--; return new Instance (fv, classNames[currentClassIndex], uri, null); } public boolean hasNext () { return ! (currentClassIndex == 0 && currentInstanceIndex == 0); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
5,603
35.38961
100
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/LineGroupIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.io.*; import java.util.Iterator; import java.util.regex.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; /** Iterate over groups of lines of text, separated by lines that match a regular expression. For example, the WSJ BaseNP data consists of sentences with one word per line, each sentence separated by a blank line. If the "boundary" line is to be included in the group, it is placed at the end of the group. */ public class LineGroupIterator implements Iterator<Instance> { LineNumberReader reader; Pattern lineBoundaryRegex; boolean skipBoundary; //boolean putBoundaryLineAtEnd; // Not yet implemented String nextLineGroup; String nextBoundary; String nextNextBoundary; int groupIndex = 0; boolean putBoundaryInSource = true; public LineGroupIterator (Reader input, Pattern lineBoundaryRegex, boolean skipBoundary) { this.reader = new LineNumberReader (input); this.lineBoundaryRegex = lineBoundaryRegex; this.skipBoundary = skipBoundary; setNextLineGroup(); } public String peekLineGroup () { return nextLineGroup; } private void setNextLineGroup () { StringBuffer sb = new StringBuffer (); String line; if (!skipBoundary && nextBoundary != null) sb.append(nextBoundary + '\n'); while (true) { try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException (e); } //System.out.println ("LineGroupIterator: got line: "+line); if (line == null) { break; } else if (lineBoundaryRegex.matcher (line).matches()) { if (sb.length() > 0) { this.nextBoundary = this.nextNextBoundary; this.nextNextBoundary = line; break; } else { // The first line of the file. if (!skipBoundary) sb.append(line + '\n'); this.nextNextBoundary = line; } } else { sb.append(line); sb.append('\n'); } } if (sb.length() == 0) this.nextLineGroup = null; else this.nextLineGroup = sb.toString(); } public Instance next () { assert (nextLineGroup != null); Instance carrier = new Instance (nextLineGroup, null, "linegroup"+groupIndex++, putBoundaryInSource ? nextBoundary : null); setNextLineGroup (); return carrier; } public boolean hasNext () { return nextLineGroup != null; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
2,955
27.699029
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/CsvIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import cc.mallet.types.Instance; import java.io.*; import java.util.Iterator; import java.util.regex.*; import java.net.URI; import java.net.URISyntaxException; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; /** * This iterator, perhaps more properly called a Line Pattern Iterator, * reads through a file and returns one instance per line, * based on a regular expression.<p> * * If you have data of the form * <pre>[name] [label] [data]</pre> * and a {@link Pipe} <code>instancePipe</code>, you could read instances using this code: <pre> InstanceList instances = new InstanceList(instancePipe); instances.addThruPipe(new CsvIterator(new FileReader(dataFile), "(\\w+)\\s+(\\w+)\\s+(.*)", 3, 2, 1) // (data, target, name) field indices ); </pre> * */ public class CsvIterator implements Iterator<Instance> { LineNumberReader reader; Pattern lineRegex; int uriGroup, targetGroup, dataGroup; String currentLine; public CsvIterator (Reader input, Pattern lineRegex, int dataGroup, int targetGroup, int uriGroup) { this.reader = new LineNumberReader (input); this.lineRegex = lineRegex; this.targetGroup = targetGroup; this.dataGroup = dataGroup; this.uriGroup = uriGroup; if (dataGroup <= 0) throw new IllegalStateException ("You must extract a data field."); try { this.currentLine = reader.readLine(); } catch (IOException e) { throw new IllegalStateException (); } } public CsvIterator (Reader input, String lineRegex, int dataGroup, int targetGroup, int uriGroup) { this (input, Pattern.compile (lineRegex), dataGroup, targetGroup, uriGroup); } public CsvIterator (String filename, String lineRegex, int dataGroup, int targetGroup, int uriGroup) throws java.io.FileNotFoundException { this (new FileReader (new File(filename)), Pattern.compile (lineRegex), dataGroup, targetGroup, uriGroup); } // The PipeInputIterator interface public Instance next () { String uriStr = null; String data = null; String target = null; Matcher matcher = lineRegex.matcher(currentLine); if (matcher.find()) { if (uriGroup > 0) uriStr = matcher.group(uriGroup); if (targetGroup > 0) target = matcher.group(targetGroup); if (dataGroup > 0) data = matcher.group(dataGroup); } else { throw new IllegalStateException ("Line #"+reader.getLineNumber()+" does not match regex:\n" + currentLine); } String uri; if (uriStr == null) { uri = "csvline:"+reader.getLineNumber(); } else { uri = uriStr; } assert (data != null); Instance carrier = new Instance (data, target, uri, null); try { this.currentLine = reader.readLine(); } catch (IOException e) { throw new IllegalStateException (); } return carrier; } public boolean hasNext () { return currentLine != null; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
3,639
28.836066
109
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/UnlabeledFileIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.ArrayList; import java.util.Iterator; import java.util.regex.*; import java.io.*; import cc.mallet.types.Instance; /** * An iterator that generates instances from an initial * directory or set of directories. The iterator will recurse through sub-directories. * Each filename becomes the data field of an instance, and the targets are set to null. * To set the target values to the directory name, use FileIterator instead. * <p> * @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> * @author Gregory Druck <a href="mailto:[email protected]">[email protected]</a> */ public class UnlabeledFileIterator implements Iterator<Instance> { FileFilter fileFilter; ArrayList<File> fileArray; Iterator<File> subIterator; File[] startingDirectories; int[] minFileIndex; int fileCount; /** Special value that means to use the directories[i].getPath() as the target name */ // xxx Note that these are specific to UNIX directory delimiter characters! Fix this. /** Use as label names the directories specified in the constructor, * optionally removing common prefix of all starting directories */ public static final Pattern STARTING_DIRECTORIES = Pattern.compile ("_STARTING_DIRECTORIES_"); /** Use as label names the first directory in the filename. */ public static final Pattern FIRST_DIRECTORY = Pattern.compile ("/?([^/]*)/.+"); /** Use as label name the last directory in the filename. */ public static final Pattern LAST_DIRECTORY = Pattern.compile(".*/([^/]+)/[^/]+"); // was ("([^/]*)/[^/]+"); /** Use as label names all the directory names in the filename. */ public static final Pattern ALL_DIRECTORIES = Pattern.compile ("^(.*)/[^/]+"); // added by Fuchun Peng public ArrayList<File> getFileArray() { return fileArray; } /** * Construct a FileIterator that will supply filenames within initial directories * as instances * @param directories Array of directories to collect files from * @param fileFilter class implementing interface FileFilter that will decide which names to accept. * May be null. * @param targetPattern regex Pattern applied to the filename whose first parenthesized group * on matching is taken to be the target value of the generated instance. The pattern is applied to * the directory with the matcher.find() method. If null, then all instances * will have target null. * @param removeCommonPrefix boolean that modifies the behavior of the STARTING_DIRECTORIES pattern, * removing the common prefix of all initially specified directories, * leaving the remainder of each filename as the target value. * */ protected UnlabeledFileIterator(File[] directories, FileFilter fileFilter) { this.startingDirectories = directories; this.fileFilter = fileFilter; this.minFileIndex = new int[directories.length]; this.fileArray = new ArrayList<File> (); for (int i = 0; i < directories.length; i++) { if (!directories[i].isDirectory()) throw new IllegalArgumentException (directories[i].getAbsolutePath() + " is not a directory."); minFileIndex[i] = fileArray.size(); fillFileArray (directories[i], fileFilter, fileArray); } this.subIterator = fileArray.iterator(); this.fileCount = 0; String[] dirStrings = new String[directories.length]; for (int i = 0; i < directories.length; i++) dirStrings[i] = directories[i].toString(); } public static File[] stringArray2FileArray (String[] sa) { File[] ret = new File[sa.length]; for (int i = 0; i < sa.length; i++) ret[i] = new File (sa[i]); return ret; } public UnlabeledFileIterator (String[] directories, FileFilter ff) { this (stringArray2FileArray(directories), ff); } public UnlabeledFileIterator (File directory, FileFilter fileFilter) { this (new File[] {directory}, fileFilter); } public UnlabeledFileIterator (File directory) { this (new File[] {directory}, null); } public UnlabeledFileIterator (File[] directories) { this (directories, null); } public UnlabeledFileIterator (String directory) { this (new File[] {new File(directory)}, null); } public UnlabeledFileIterator (String directory, FileFilter filter) { this (new File[] {new File(directory) }, filter); } private int fillFileArray (File directory, FileFilter filter, ArrayList<File> files) { int count = 0; File[] directoryContents = directory.listFiles(); for (int i = 0; i < directoryContents.length; i++) { if (directoryContents[i].isDirectory()) count += fillFileArray (directoryContents[i], filter, files); else if (filter == null || filter.accept(directoryContents[i])) { files.add (directoryContents[i]); count++; } } return count; } // The PipeInputIterator interface public Instance next () { File nextFile = subIterator.next(); fileCount++; return new Instance (nextFile, null, nextFile.toURI(), null); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } // culotta - 9.11.03 public File nextFile () { return subIterator.next(); } public boolean hasNext () { return subIterator.hasNext(); } }
5,935
33.312139
122
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/EmptyInstanceIterator.java
package cc.mallet.pipe.iterator; import java.util.Iterator; import cc.mallet.types.Instance; public class EmptyInstanceIterator implements Iterator<Instance> { public boolean hasNext() { return false; } public Instance next () { throw new IllegalStateException ("This iterator never has any instances."); } public void remove () { throw new IllegalStateException ("This iterator does not support remove()."); } }
420
31.384615
104
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/ConcatenatedInstanceIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.Iterator; import cc.mallet.pipe.*; import cc.mallet.types.Instance; public class ConcatenatedInstanceIterator implements Iterator<Instance> { Iterator<Instance>[] iterators; Instance next; int iteratorIndex; public ConcatenatedInstanceIterator (Iterator<Instance>[] iterators) { this.iterators = iterators; this.iteratorIndex = 0; setNext(); } private void setNext () { next = null; for (; iteratorIndex < iterators.length && !iterators[iteratorIndex].hasNext(); iteratorIndex++); if (iteratorIndex < iterators.length) next = (Instance)iterators[iteratorIndex].next(); } public boolean hasNext () { return next != null; } public Instance next () { Instance ret = (Instance)next; setNext(); return ret; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
1,458
23.316667
114
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/PatternMatchIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.io.*; import java.util.Iterator; import java.util.regex.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; /** Iterates over matching regular expresions. E.g. * regexp = Pattern.compile ("<p>(.+?)</p>") will * extract <p> elements from: * * <p> This block is an element </p> this is not <p> but this is </p> * */ public class PatternMatchIterator implements Iterator<Instance> { Pattern regexp; Matcher matcher; String nextElement; int elementIndex; public PatternMatchIterator (CharSequence input, Pattern regexp) { this.elementIndex = 0; this.regexp = regexp; this.matcher = regexp.matcher (input); this.nextElement = getNextElement(); } public String getNextElement () { if (matcher.find()) return matcher.group(1); else return null; } // The PipeInputIterator interface public Instance next () { assert (nextElement != null); Instance carrier = new Instance (nextElement, null, "element"+elementIndex++, null); nextElement = getNextElement (); return carrier; } public boolean hasNext () { return nextElement != null; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
1,856
25.913043
89
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/SegmentIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.ArrayList; import java.util.Iterator; import java.net.URI; import java.io.*; import cc.mallet.fst.*; import cc.mallet.pipe.Noop; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; /** Iterates over {@link Segment}s extracted by a {@link Transducer} for some {@link InstanceList}. */ public class SegmentIterator implements Iterator<Instance> { Iterator subIterator; ArrayList segments; /** NOTE!: Assumes that <code>segmentStartTags[i]</code> corresponds to <code>segmentContinueTags[i]</code>. @param model model to segment input sequences @param ilist list of instances to be segmented @param segmentStartTags array of tags indicating the start of a segment @param segmentContinueTags array of tags indicating the continuation of a segment */ public SegmentIterator (Transducer model, InstanceList ilist, Object[] segmentStartTags, Object[] segmentContinueTags) { setSubIterator (model, ilist, segmentStartTags, segmentContinueTags); } /** Iterates over {@link Segment}s for only one {@link Instance}. */ public SegmentIterator (Transducer model, Instance instance, Object[] segmentStartTags, Object[] segmentContinueTags) { InstanceList ilist = new InstanceList (new Noop (instance.getDataAlphabet(), instance.getTargetAlphabet())); ilist.add (instance); setSubIterator (model, ilist, segmentStartTags, segmentContinueTags); } /** Useful when no {@link Transduce} is specified. A list of sequences specifies the output. @param ilist InstanceList containing sequence. @param segmentStartTags array of tags indicating the start of a segment @param segmentContinueTags array of tags indicating the continuation of a segment @param predictions list of {@link Sequence}s that are the predicted output of some {@link Transducer} */ public SegmentIterator (InstanceList ilist, Object[] startTags, Object[] inTags, ArrayList predictions) { setSubIterator (ilist, startTags, inTags, predictions); } /** Iterate over segments in one instance. @param ilist InstanceList containing sequence. @param segmentStartTags array of tags indicating the start of a segment @param segmentContinueTags array of tags indicating the continuation of a segment @param predictions list of {@link Sequence}s that are the predicted output of some {@link Transducer} */ public SegmentIterator (Instance instance, Object[] startTags, Object[] inTags, Sequence prediction) { InstanceList ilist = new InstanceList (new Noop (instance.getDataAlphabet(), instance.getTargetAlphabet())); ilist.add (instance); ArrayList predictions = new ArrayList(); predictions.add (prediction); setSubIterator (ilist, startTags, inTags, predictions); } /** Iterate over segments in one labeled sequence */ public SegmentIterator (Sequence input, Sequence predicted, Sequence truth, Object[] startTags, Object[] inTags) { segments = new ArrayList (); if (input.size() != truth.size () || predicted.size () != truth.size ()) throw new IllegalStateException ("sequence lengths not equal. input: " + input.size () + " true: " + truth.size () + " predicted: " + predicted.size ()); // find predicted segments for (int n=0; n < predicted.size (); n++) { for (int s=0; s < startTags.length; s++) { if (startTags[s].equals (predicted.get (n))) { // found start tag int j=n+1; while (j < predicted.size() && inTags[s].equals (predicted.get (j))) // find end tag j++; segments.add (new Segment (input, predicted, truth, n, j-1, startTags[s], inTags[s])); } } } this.subIterator = segments.iterator(); } private void setSubIterator (InstanceList ilist, Object[] startTags, Object[] inTags, ArrayList predictions) { segments = new ArrayList (); // stores predicted <code>Segment</code>s Iterator iter = ilist.iterator (); for (int i=0; i < ilist.size(); i++) { Instance instance = (Instance) ilist.get (i); Sequence input = (Sequence) instance.getData (); Sequence trueOutput = (Sequence) instance.getTarget (); Sequence predOutput = (Sequence) predictions.get (i); if (input.size() != trueOutput.size () || predOutput.size () != trueOutput.size ()) throw new IllegalStateException ("sequence lengths not equal. input: " + input.size () + " true: " + trueOutput.size () + " predicted: " + predOutput.size ()); // find predicted segments for (int n=0; n < predOutput.size (); n++) { for (int s=0; s < startTags.length; s++) { if (startTags[s].equals (predOutput.get (n))) { // found start tag int j=n+1; while (j < predOutput.size() && inTags[s].equals (predOutput.get (j))) // find end tag j++; segments.add (new Segment (input, predOutput, trueOutput, n, j-1, startTags[s], inTags[s])); } } } } this.subIterator = segments.iterator (); } private void setSubIterator (Transducer model, InstanceList ilist, Object[] segmentStartTags, Object[] segmentContinueTags) { segments = new ArrayList (); // stores predicted <code>Segment</code>s Iterator iter = ilist.iterator (); while (iter.hasNext ()) { Instance instance = (Instance) iter.next (); Sequence input = (Sequence) instance.getData (); Sequence trueOutput = (Sequence) instance.getTarget (); Sequence predOutput = new MaxLatticeDefault (model, input).bestOutputSequence(); if (input.size() != trueOutput.size () || predOutput.size () != trueOutput.size ()) throw new IllegalStateException ("sequence lengths not equal. input: " + input.size () + " true: " + trueOutput.size () + " predicted: " + predOutput.size ()); // find predicted segments for (int i=0; i < predOutput.size (); i++) { for (int s=0; s < segmentStartTags.length; s++) { if (segmentStartTags[s].equals (predOutput.get (i))) { // found start tag int j=i+1; while (j < predOutput.size() && segmentContinueTags[s].equals (predOutput.get (j))) // find end tag j++; segments.add (new Segment (input, predOutput, trueOutput, i, j-1, segmentStartTags[s], segmentContinueTags[s])); } } } } this.subIterator = segments.iterator (); } // The PipeInputIterator interface public Instance next () { Segment nextSegment = (Segment) subIterator.next(); return new Instance (nextSegment, nextSegment.getTruth (), null, null); } public Segment nextSegment () { return (Segment) subIterator.next (); } public boolean hasNext () { return subIterator.hasNext(); } public ArrayList toArrayList () { return this.segments; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
7,501
38.072917
126
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/PipeExtendedIterator.java
/* Copyright (C) 2003 University of Pennsylvania. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Fernando Pereira <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.Iterator; import cc.mallet.pipe.*; import cc.mallet.types.Instance; /** * Provides a {@link PipeExtendedIterator} that applies a {@link Pipe} to * the {@link Instance}s returned by a given {@link PipeExtendedIterator}, * It is intended to encapsulate preprocessing that should not belong to the * input {@link Pipe} of a {@link Classifier} or {@link Transducer}. * * @author <a href="mailto:[email protected]">Fernando Pereira</a> * @version 1.0 */ @Deprecated // Now that Pipe's support iteration directly, this should no longer be necessary? -AKM 9/2007 public class PipeExtendedIterator implements Iterator<Instance> { private Iterator<Instance> iterator; private Pipe pipe; /** * Creates a new <code>PipeExtendedIterator</code> instance. * * @param iterator the base <code>PipeExtendedIterator</code> * @param pipe The <code>Pipe</code> to postprocess the iterator output */ public PipeExtendedIterator (Iterator<Instance> iterator, Pipe pipe) { this.iterator = iterator; this.pipe = pipe; } //public PipeExtendedIterator(ArrayDataAndTargetIterator iterator2, CharSequenceArray2TokenSequence sequence) { // TODO Auto-generated constructor stub //} public boolean hasNext () { return iterator.hasNext(); } public Instance next () { return pipe.pipe(iterator.next()); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
2,006
28.086957
112
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/FileUriIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.Iterator; import java.util.ArrayList; import java.io.*; import java.net.URI; import java.util.regex.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Instance; public class FileUriIterator extends FileIterator { public FileUriIterator (File[] directories, FileFilter filter, Pattern targetPattern) { super (directories, filter, targetPattern); } public FileUriIterator (File directory, FileFilter filter, Pattern targetPattern) { super (directory, filter, targetPattern); } public FileUriIterator (File[] directories, Pattern targetPattern) { super (directories, null, targetPattern); } public FileUriIterator (File directory, Pattern targetPattern) { super (directory, null, targetPattern); } public Instance next () { Instance carrier = super.next(); carrier.setData(((File)carrier.getData()).toURI()); return carrier; } }
1,442
24.315789
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/FileListIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Gary Huang <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.net.URI; import java.util.regex.*; import java.io.*; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.Label; import cc.mallet.util.Strings; /** * An iterator that generates instances for a pipe from a list of filenames. * Each file is treated as a text file whose target is determined by * a user-specified regular expression pattern applied to the filename * * @author Gary Huang <a href="mailto:[email protected]">[email protected]</a> */ public class FileListIterator implements Iterator<Instance> { FileFilter fileFilter; ArrayList fileArray; Iterator subIterator; Pattern targetPattern; // Set target slot to string coming from 1st group of this Pattern int commonPrefixIndex; /** Special value that means to use the directories[i].getPath() as the target name */ // xxx Note that these are specific to UNIX directory delimiter characters! Fix this. /** Use as label names the directories of the given files, * optionally removing common prefix of all starting directories */ public static final Pattern STARTING_DIRECTORIES = Pattern.compile ("_STARTING_DIRECTORIES_"); /** Use as label names the first directory in the filename. */ public static final Pattern FIRST_DIRECTORY = Pattern.compile ("/?([^/]*)/.+"); /** Use as label name the last directory in the filename. */ public static final Pattern LAST_DIRECTORY = Pattern.compile(".*/([^/]+)/[^/]+"); // was ("([^/]*)/[^/]+"); /** Use as label names all the directory names in the filename. */ public static final Pattern ALL_DIRECTORIES = Pattern.compile ("^(.*)/[^/]+"); /* Pass null as targetPattern to get null targets */ /** * Construct an iterator over the given arry of Files * * The instances constructed from the files are returned in the same order * as they appear in the given array * * @param files Array of files from which to construct instances * @param fileFilter class implementing interface FileFilter that will decide which names to accept. * May be null. * @param targetPattern regex Pattern applied to the filename whose first parenthesized group * on matching is taken to be the target value of the generated instance. * The pattern is applied to the filename with the matcher.find() method. * @param removeCommonPrefix boolean that modifies the behavior of the STARTING_DIRECTORIES * pattern, removing the common prefix of all initially specified * directories, leaving the remainder of each filename as the target value. * */ public FileListIterator(File[] files, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) { this.fileFilter = fileFilter; this.fileArray = new ArrayList(); this.targetPattern = targetPattern; fillFileArrayAssignCommonPrefixIndexAndSubIterator(files, removeCommonPrefix); } public FileListIterator(String[] filenames, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) { this(FileIterator.stringArray2FileArray(filenames), fileFilter, targetPattern, removeCommonPrefix); } /** * Construct a FileListIterator with the file containing the list of files, which * contains one filename per line. * * The instances constructed from the filelist are returned in the same order * as listed */ public FileListIterator(File filelist, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) throws FileNotFoundException, IOException { this.fileFilter = fileFilter; this.fileArray = new ArrayList(); this.targetPattern = targetPattern; List filenames = readFileNames (filelist); File[] fa = stringList2FileArray (filenames, null); fillFileArrayAssignCommonPrefixIndexAndSubIterator(fa, removeCommonPrefix); } /** * Construct a FileListIterator with the file containing the list of files * of RELATIVE pathnames, one filename per line. * <p> * The instances constructed from the filelist are returned in the same order * as listed * @param filelist List of relative file names. * @param baseDirectory Base directory for relative file names. * */ public FileListIterator(File filelist, File baseDirectory, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) throws FileNotFoundException, IOException { this.fileFilter = fileFilter; this.fileArray = new ArrayList(); this.targetPattern = targetPattern; List filenames = readFileNames (filelist); File[] fa = stringList2FileArray (filenames, baseDirectory); fillFileArrayAssignCommonPrefixIndexAndSubIterator(fa, removeCommonPrefix); } private static File[] stringList2FileArray (List filenames, File baseDir) { File[] fa = new File[filenames.size()]; for (int i = 0; i < filenames.size(); i++) if (baseDir != null) { fa[i] = new File (baseDir, (String) filenames.get(i)); } else { fa[i] = new File ((String) filenames.get(i)); } return fa; } private static List readFileNames (File filelist) throws IOException { ArrayList filenames = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader (filelist)); String filename = reader.readLine(); while (filename != null && filename.trim().length() > 0) { filenames.add(filename.trim()); filename = reader.readLine(); } reader.close(); return filenames; } public FileListIterator(String filelistName, FileFilter fileFilter, Pattern targetPattern, boolean removeCommonPrefix) throws FileNotFoundException, IOException { this (new File(filelistName), fileFilter, targetPattern, removeCommonPrefix); } public FileListIterator(String filelistName, Pattern targetPattern) throws FileNotFoundException, IOException { this (new File(filelistName), null, targetPattern, true); } // The PipeInputIterator interface public Instance next () { File nextFile = (File) subIterator.next(); String path = nextFile.getParent(); String targetName = null; if (targetPattern == STARTING_DIRECTORIES) { targetName = path.substring(commonPrefixIndex); } else if (targetPattern != null) { Matcher m = targetPattern.matcher(path); if (m.find ()){ targetName = m.group (1); } } return new Instance (nextFile, targetName, nextFile.toURI(), null); } public File nextFile () { return (File) subIterator.next(); } public boolean hasNext () { return subIterator.hasNext(); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } public ArrayList getFileArray() { return fileArray; } private void fillFileArrayAssignCommonPrefixIndexAndSubIterator(File[] files, boolean removeCommonPrefix) { ArrayList filenames = new ArrayList(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) throw new IllegalArgumentException(files[i] + " is not a file."); else if (! files[i].exists()) throw new IllegalArgumentException(files[i] + " does not exist."); if (this.fileFilter == null || this.fileFilter.accept(files[i])) { this.fileArray.add(files[i]); if (removeCommonPrefix) filenames.add(files[i].getPath()); } } this.subIterator = this.fileArray.iterator(); if (removeCommonPrefix) { // find the common prefix index of all filenames String[] fn = new String[filenames.size()]; for (int i = 0; i < fn.length; i++) fn[i] = (String) filenames.get(i); this.commonPrefixIndex = Strings.commonPrefixIndex(fn); } else this.commonPrefixIndex = 0; } }
8,609
32.764706
118
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/ArrayIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.net.URI; import java.util.Iterator; import java.util.List; import cc.mallet.types.Instance; public class ArrayIterator implements Iterator<Instance> { Iterator subIterator; Object target; int index; public ArrayIterator (List data, Object target) { this.subIterator = data.iterator (); this.target = target; this.index = 0; } public ArrayIterator (List data) { this (data, null); } public ArrayIterator (Object[] data, Object target) { this (java.util.Arrays.asList (data), target); } public ArrayIterator (Object[] data) { this (data, null); } public Instance next () { URI uri = null; try { uri = new URI ("array:" + index++); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(); } return new Instance (subIterator.next(), target, uri, null); } public boolean hasNext () { return subIterator.hasNext(); } public void remove() { subIterator.remove(); } }
1,510
21.552239
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/LineIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.io.*; import java.util.Iterator; import java.util.regex.*; import java.net.URI; import java.net.URISyntaxException; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; public class LineIterator implements Iterator<Instance> { LineNumberReader reader; Pattern lineRegex; int uriGroup, targetGroup, dataGroup; String currentLine; public LineIterator (Reader input, Pattern lineRegex, int dataGroup, int targetGroup, int uriGroup) { this.reader = new LineNumberReader (input); this.lineRegex = lineRegex; this.targetGroup = targetGroup; this.dataGroup = dataGroup; if (dataGroup < 0) throw new IllegalStateException ("You must extract a data field."); try { this.currentLine = reader.readLine(); } catch (IOException e) { throw new IllegalStateException (); } } public LineIterator (Reader input, String lineRegex, int dataGroup, int targetGroup, int uriGroup) { this (input, Pattern.compile (lineRegex), dataGroup, targetGroup, uriGroup); } public LineIterator (String filename, String lineRegex, int dataGroup, int targetGroup, int uriGroup) throws java.io.FileNotFoundException { this (new FileReader (new File(filename)), Pattern.compile (lineRegex), dataGroup, targetGroup, uriGroup); } // The PipeInputIterator interface public Instance next () { String uriStr = null; String data = null; String target = null; Matcher matcher = lineRegex.matcher(currentLine); if (matcher.find()) { if (uriGroup > -1) uriStr = matcher.group(uriGroup); if (targetGroup > -1) target = matcher.group(targetGroup); if (dataGroup > -1) data = matcher.group(dataGroup); } else throw new IllegalStateException ("Line #"+reader.getLineNumber()+" does not match regex"); String uri; if (uriStr == null) { uri = "csvline:"+reader.getLineNumber(); } else { uri = uriStr; } assert (data != null); Instance carrier = new Instance (data, target, uri, null); try { this.currentLine = reader.readLine(); } catch (IOException e) { throw new IllegalStateException (); } return carrier; } public boolean hasNext () { return currentLine != null; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
2,839
27.979592
102
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/PipeInputIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.Iterator; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.Label; /** * Interface for classes that generate instances. * * Typically, these instances will be unprocessed (e.g., they * may come from a corpus data file), and are passed through a pipe * as they are added to an InstanceList. * * @see Pipe * @see cc.mallet.types.InstanceList * */ @Deprecated // You should just use Iterator<Instance> directly. This class will be removed in the future. public abstract class PipeInputIterator implements Iterator<Instance> { public abstract Instance next (); public abstract boolean hasNext (); public void remove () { throw new UnsupportedOperationException (); } // Sometimes (as in an InstanceList used for AdaBoost) Instances may be weighted. // Weights may also come from other raw input sources for instances in Pipes. public double getWeight () { return 1.0; } }
1,537
31.723404
106
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/SimpleFileLineIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.io.*; import java.util.Iterator; import java.util.regex.*; import java.net.URI; import java.net.URISyntaxException; import cc.mallet.pipe.Pipe; import cc.mallet.types.*; public class SimpleFileLineIterator implements Iterator<Instance> { BufferedReader reader = null; int index = -1; String currentLine = null; boolean hasNextUsed = false; int progressDisplayInterval = 0; public SimpleFileLineIterator (String filename) { try { this.reader = new BufferedReader (new FileReader(filename)); this.index = 0; } catch (IOException e) { throw new RuntimeException (e); } } public SimpleFileLineIterator (File file) { try { this.reader = new BufferedReader (new FileReader(file)); this.index = 0; } catch (IOException e) { throw new RuntimeException (e); } } /** Set the iterator to periodically print the * total number of lines read to standard out. * @param interval how often to print */ public void setProgressDisplayInterval(int interval) { progressDisplayInterval = interval; } public Instance next () { URI uri = null; try { uri = new URI ("array:" + index++); } catch (Exception e) { throw new RuntimeException (e); } if (!hasNextUsed) { try { currentLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException (e); } } else { hasNextUsed = false; } if (progressDisplayInterval != 0 && index > 0 && index % progressDisplayInterval == 0) { System.out.println(index); } return new Instance (currentLine, null, uri, null); } public boolean hasNext () { hasNextUsed = true; try { currentLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException (e); } return (currentLine != null); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
2,454
23.306931
89
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/SelectiveFileLineIterator.java
/* Copyright (C) 2010 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe.iterator; import java.io.*; import java.util.Iterator; import java.net.URI; import cc.mallet.types.*; /** * Very similar to the SimpleFileLineIterator, * but skips lines that match a regular expression. * * @author Gregory Druck */ public class SelectiveFileLineIterator implements Iterator<Instance> { BufferedReader reader = null; int index = -1; String currentLine = null; boolean hasNextUsed = false; String skipRegex; public SelectiveFileLineIterator (Reader reader, String skipRegex) { this.reader = new BufferedReader (reader); this.index = 0; this.skipRegex = skipRegex; } public Instance next () { if (!hasNextUsed) { try { currentLine = reader.readLine(); while (currentLine != null && currentLine.matches(skipRegex)) { currentLine = reader.readLine(); } } catch (IOException e) { throw new RuntimeException (e); } } else { hasNextUsed = false; } URI uri = null; try { uri = new URI ("array:" + index++); } catch (Exception e) { throw new RuntimeException (e); } return new Instance (currentLine, null, uri, null); } public boolean hasNext () { hasNextUsed = true; try { currentLine = reader.readLine(); while (currentLine != null && currentLine.matches(skipRegex)) { currentLine = reader.readLine(); } } catch (IOException e) { throw new RuntimeException (e); } return (currentLine != null); } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
1,985
25.131579
89
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/StringArrayIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.net.URI; import java.util.Iterator; import cc.mallet.types.Instance; public class StringArrayIterator implements Iterator<Instance> { String[] data; int index; public StringArrayIterator (String[] data) { this.data = data; this.index = 0; } public Instance next () { URI uri = null; try { uri = new URI ("array:" + index); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(); } return new Instance (data[index++], null, uri, null); } public boolean hasNext () { return index < data.length; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
1,228
26.311111
90
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/ParenGroupIterator.java
/* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe.iterator; import java.io.*; import java.util.Iterator; import cc.mallet.types.*; /** * Iterator that takes a Reader, breaks up the input into * top-level parenthesized expressions. For example, * in the input <tt>(a (a b) c) f (d e)</tt>, there * are two top-level expressions '(a (a b) c)' and '(d e)'. * * Text that is not within parentheses is ignored. * * Created: Thu Feb 26 13:45:43 2004 * * @author <a href="mailto:[email protected]">Charles Sutton</a> * @version $Id: ParenGroupIterator.java,v 1.1 2007/10/22 21:37:49 mccallum Exp $ */ public class ParenGroupIterator implements Iterator<Instance> { private Reader reader; private char open; private char close; private String nextGroup; private int groupIdx; public ParenGroupIterator (Reader input) { this (input, '(', ')'); } public ParenGroupIterator (Reader input, char openParen, char closeParen) { this.reader = new BufferedReader (input); this.open = openParen; this.close = closeParen; nextGroup = getNextGroup (); } private String getNextGroup () { StringBuffer buf = new StringBuffer (); int depth = 1; try { // Eat up nonparen characters int b; while ((b = reader.read()) != (int)open) { if (b == -1) return null; } buf.append (open); while ((b = reader.read()) != -1) { char ch = (char)b; buf.append (ch); if (ch == open) { depth++; } else if (ch == close) { depth--; if (depth == 0) break; } } } catch (IOException e) { throw new RuntimeException (e); } return buf.toString(); } // Interface PipeInputIterate public Instance next () { Instance carrier = new Instance (nextGroup, null, "parengroup"+(groupIdx++), null); nextGroup = getNextGroup (); return carrier; } public boolean hasNext () { return nextGroup != null; } public void remove () { throw new IllegalStateException ("This Iterator<Instance> does not support remove()."); } }
2,453
23.54
89
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/ArrayDataAndTargetIterator.java
/* Copyright (C) 2003 University of Pennsylvania This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Fernando Pereira <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator; import java.util.Iterator; import java.util.ArrayList; import java.util.List; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import cc.mallet.pipe.Pipe; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import cc.mallet.types.Label; public class ArrayDataAndTargetIterator implements Iterator<Instance> { Iterator subIterator; Iterator targetIterator; int index; public ArrayDataAndTargetIterator (List data, List targets) { this.subIterator = data.iterator (); this.targetIterator = targets.iterator (); this.index = 0; } public ArrayDataAndTargetIterator (Object[] data, Object target[]) { this (java.util.Arrays.asList (data), java.util.Arrays.asList (target)); } // The PipeInputIterator interface public Instance next () { URI uri = null; try { uri = new URI ("array:" + index++); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(); } return new Instance (subIterator.next(), targetIterator.next(), uri, null); } public boolean hasNext () { return subIterator.hasNext(); } public void remove () { throw new IllegalStateException ("This iterator does not support remove()."); } }
1,730
26.47619
104
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/iterator/tests/TestPatternMatchIterator.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.iterator.tests; import junit.framework.*; import java.util.Iterator; import java.util.regex.*; import cc.mallet.pipe.iterator.*; import cc.mallet.types.*; public class TestPatternMatchIterator extends TestCase { public TestPatternMatchIterator (String name) { super (name); } String data = "<p>Inside inside inside</p> outside <p>inside\ninside</p> outside\noutside"; public void testOne () { Iterator iter = new PatternMatchIterator( data, Pattern.compile("<p>(.+?)</p>", Pattern.DOTALL)); int i=0; while (iter.hasNext()) { Instance inst = (Instance) iter.next(); System.out.println( inst.getName() + " : " + inst.getData() ); if (i++==0) assertTrue (inst.getData().equals("Inside inside inside")); else assertTrue (inst.getData().equals("inside\ninside")); } } public static Test suite () { return new TestSuite (TestPatternMatchIterator.class); } protected void setUp () { } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } }
1,620
26.016667
101
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/tests/TestSGML2TokenSequence.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Aron Culotta <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.tests; import junit.framework.*; import java.util.ArrayList; import java.util.regex.*; import cc.mallet.pipe.*; import cc.mallet.pipe.iterator.*; import cc.mallet.pipe.tsf.*; import cc.mallet.types.*; public class TestSGML2TokenSequence extends TestCase { public TestSGML2TokenSequence (String name) { super (name); } String[] dataWithTags = new String[] { "zeroth test string", "<tag>first</tag> test string", "second <tag>test</tag> string", "third test <tag>string</tag>", }; String[] data = new String[] { "zeroth test string", "first test string", "second test string", "third test string", }; String[] tags = new String[] { "O O O", "tag O O ", "O tag O", "O O tag", }; public static class Array2ArrayIterator extends Pipe { public Instance pipe (Instance carrier) { carrier.setData(new ArrayIterator ((Object[])carrier.getData())); return carrier; } } public void testOne () { Pipe p = new SerialPipes (new Pipe[] { new Input2CharSequence (), new SGML2TokenSequence() }); for (int i=0; i < dataWithTags.length; i++) { Instance inst = p.instanceFrom(new Instance (dataWithTags[i], null, null, null)); TokenSequence input = (TokenSequence)inst.getData(); TokenSequence target = (TokenSequence)inst.getTarget(); String[] oginput = data[i].split("\\s+"); String[] ogtags = tags[i].split("\\s+"); assert (input.size() == target.size()); assert (input.size() == oginput.length); for (int j=0; j < oginput.length; j++) { assert (oginput[j].equals (input.get(j).getText())); assert (ogtags[j].equals (target.get(j).getText())); } } } public static Test suite () { return new TestSuite (TestSGML2TokenSequence.class); } protected void setUp () { } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } }
2,400
23.752577
86
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/tests/TestPipeUtils.java
/* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe.tests; import cc.mallet.fst.SimpleTagger; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.PipeUtils; import cc.mallet.pipe.SerialPipes; import cc.mallet.pipe.SimpleTaggerSentence2TokenSequence; import cc.mallet.types.Alphabet; import cc.mallet.types.Instance; import junit.framework.*; /** * Created: Aug 28, 2005 * * @author <A HREF="mailto:[email protected]>[email protected]</A> * @version $Id: TestPipeUtils.java,v 1.1 2007/10/22 21:37:40 mccallum Exp $ */ public class TestPipeUtils extends TestCase { public TestPipeUtils (String name) { super (name); } private static class StupidPipe extends Pipe { public Instance pipe (Instance carrier) { System.out.println ("StupidPipe says hi."); return carrier; } } private static String data = "f1 f2 CL1\nf1 f3 CL2"; public void testPipesAreStupid () { Pipe p1 = new StupidPipe (); Pipe p2 = new SimpleTaggerSentence2TokenSequence (); // initialize p2's dict p2.instanceFrom(new Instance (data, null, null, null)); Pipe serial = new SerialPipes (new Pipe[] { p1, p2 }); try { serial.getDataAlphabet (); assertTrue ("Test failed: Should have generated exception.", false); } catch (IllegalStateException e) {} } public void testConcatenatePipes () { Pipe p1 = new StupidPipe (); Pipe p2 = new SimpleTagger.SimpleTaggerSentence2FeatureVectorSequence (); // initialize p2's dict p2.instanceFrom(new Instance (data, null, null, null)); assertEquals (3, p2.getDataAlphabet ().size()); Pipe serial = PipeUtils.concatenatePipes (p1, p2); Alphabet dict = serial.getDataAlphabet (); assertEquals (3, dict.size ()); assertTrue (dict == p2.getDataAlphabet ()); } public void testConcatenateNullPipes () { Pipe p1 = new StupidPipe (); Pipe p2 = new SimpleTagger.SimpleTaggerSentence2FeatureVectorSequence (); Pipe serial = PipeUtils.concatenatePipes (p1, p2); p2.instanceFrom(new Instance (data, null, null, null)); assertEquals (3, serial.getDataAlphabet ().size ()); } public void testConcatenateBadPipes () { Pipe p1 = new SimpleTaggerSentence2TokenSequence (); // force resolving data alphabet Alphabet dict1 = p1.getDataAlphabet (); Pipe p2 = new SimpleTaggerSentence2TokenSequence (); // force resolving data alphabet Alphabet dict2 = p2.getDataAlphabet (); assertTrue (dict1 != dict2); try { PipeUtils.concatenatePipes (p1, p2); assertTrue ("Test failed: concatenatePipes() allowed putting together incompatible alphabets.", false); } catch (IllegalArgumentException e) { // Exception expected } } public static Test suite () { return new TestSuite (TestPipeUtils.class); } public static void main (String[] args) throws Throwable { TestSuite theSuite; if (args.length > 0) { theSuite = new TestSuite (); for (int i = 0; i < args.length; i++) { theSuite.addTest (new TestPipeUtils (args[i])); } } else { theSuite = (TestSuite) suite (); } junit.textui.TestRunner.run (theSuite); } }
3,592
27.744
109
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/tests/TestInstancePipe.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.tests; import junit.framework.*; import java.util.ArrayList; import java.util.regex.*; import java.io.IOException; import cc.mallet.pipe.*; import cc.mallet.pipe.iterator.*; import cc.mallet.pipe.tsf.*; import cc.mallet.types.*; import cc.mallet.types.tests.TestSerializable; public class TestInstancePipe extends TestCase { public TestInstancePipe (String name) { super (name); } String[] data = new String[] { "This is the first test string", "The second test string is here", "And this is the third test string", }; public static class Array2ArrayIterator extends Pipe { public Instance pipe (Instance carrier) { carrier.setData(new ArrayIterator ((Object[])carrier.getData())); return carrier; } } public Pipe createPipe () { return new SerialPipes (new Pipe[] { new CharSequence2TokenSequence (), new TokenSequenceLowercase (), new TokenSequence2FeatureSequence (), new FeatureSequence2FeatureVector ()}); } public void testOne () { Pipe p = createPipe(); InstanceList ilist = new InstanceList (p); ilist.addThruPipe(new StringArrayIterator(data)); assertTrue (ilist.size() == 3); } public void testTwo () { Pipe p = new SerialPipes (new Pipe[] { new CharSequence2TokenSequence (), new TokenSequenceLowercase (), new RegexMatches ("vowel", Pattern.compile ("[aeiou]")), new RegexMatches ("firsthalf", Pattern.compile ("[a-m]")), new RegexMatches ("secondhalf", Pattern.compile ("[n-z]")), new RegexMatches ("length2", Pattern.compile ("..")), new RegexMatches ("length3", Pattern.compile ("...")), new PrintInput (), new TokenSequence2TokenInstances()}); InstanceList ilist = new InstanceList (p); ilist.addThruPipe (new StringArrayIterator(data)); assert (ilist.size() == 19) : "list size = "+ilist.size(); assertTrue (ilist.size() == 19); } public void testOneFromSerialized () throws IOException, ClassNotFoundException { Pipe p = createPipe (); Pipe clone = (Pipe) TestSerializable.cloneViaSerialization (p); InstanceList ilist = new InstanceList (clone); ilist.addThruPipe(new StringArrayIterator(data)); assertTrue (ilist.size() == 3); } public static Test suite () { return new TestSuite (TestInstancePipe.class); } protected void setUp () { } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } }
3,049
27.240741
91
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/tests/TestIterators.java
/* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.pipe.tests; import java.io.*; import cc.mallet.pipe.Noop; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.iterator.*; import cc.mallet.types.InstanceList; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit Test for PipeInputIterators * * * Created: Thu Feb 26 14:27:15 2004 * * @author <a href="mailto:[email protected]">Charles Sutton</a> * @version $Id: TestIterators.java,v 1.1 2007/10/22 21:37:40 mccallum Exp $ */ public class TestIterators extends TestCase { public TestIterators (String name){ super(name); } public void testParenGroupIterator () { String input = "(a (b c) ((d)) ) f\n\n (3\n 4) ( 6) "; Reader reader = new StringReader (input); ParenGroupIterator it = new ParenGroupIterator (reader); Pipe pipe = new Noop(); pipe.setTargetProcessing (false); InstanceList lst = new InstanceList (pipe); lst.addThruPipe (it); assertEquals (3, lst.size()); assertEquals ("(a (b c) ((d)) )", lst.get(0).getData()); assertEquals ("(3\n 4)", lst.get(1).getData()); assertEquals ("( 6)", lst.get(2).getData()); } /** * @return a <code>TestSuite</code> */ public static TestSuite suite(){ return new TestSuite (TestIterators.class); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }// TestIterators
1,799
25.865672
76
java
twitter_nlp
twitter_nlp-master/mallet-2.0.6/src/cc/mallet/pipe/tests/TestRainbowStyle.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.pipe.tests; import junit.framework.*; import java.net.URI; import java.net.URL; import java.io.File; import java.util.Iterator; import java.util.regex.*; import cc.mallet.pipe.*; import cc.mallet.pipe.iterator.*; import cc.mallet.types.*; public class TestRainbowStyle extends TestCase { public TestRainbowStyle (String name) { super (name); } public void testThree () { InstanceList il = new InstanceList ( new SerialPipes (new Pipe[] { new Target2Label (), new CharSequence2TokenSequence (), new TokenSequenceLowercase (), new TokenSequenceRemoveStopwords (), new TokenSequence2FeatureSequence (), new FeatureSequence2FeatureVector () })); Iterator<Instance> pi = new FileIterator (new File("foo/bar"), null, Pattern.compile("^([^/]*)/")); il.addThruPipe (pi); } public static Test suite () { return new TestSuite (TestRainbowStyle.class); } protected void setUp () { } public static void main (String[] args) { junit.textui.TestRunner.run (suite()); } }
1,564
23.453125
101
java