Apache Lucene open-source search software
LUCENE-5348 - added minDoc/TermFreq params to kNN classifier
Tommaso Teofili7b9ca4745a92
diff --git a/lucene/classification/src/java/org/apache/lucene/classification/KNearestNeighborClassifier.java b/lucene/classification/src/java/org/apache/lucene/classification/KNearestNeighborClassifier.javaindex e21e670d2d5..22d530ac87d 100644--- a/lucene/classification/src/java/org/apache/lucene/classification/KNearestNeighborClassifier.java+++ b/lucene/classification/src/java/org/apache/lucene/classification/KNearestNeighborClassifier.java@@ -49,6 +49,9 @@ public class KNearestNeighborClassifier implements Classifier<BytesRef> {private final int k;private Query query;+ private int minDocsFreq;+ private int minTermFreq;+/*** Create a {@link Classifier} using kNN algorithm*@@ -58,6 +61,19 @@ public class KNearestNeighborClassifier implements Classifier<BytesRef> {this.k = k;}+ /**+ * Create a {@link Classifier} using kNN algorithm+ *+ * @param k the number of neighbors to analyze as an <code>int</code>+ * @param minDocsFreq the minimum number of docs frequency for MLT to be set with {@link MoreLikeThis#setMinDocFreq(int)}+ * @param minTermFreq the minimum number of term frequency for MLT to be set with {@link MoreLikeThis#setMinTermFreq(int)}+ */+ public KNearestNeighborClassifier(int k, int minDocsFreq, int minTermFreq) {+ this.k = k;+ this.minDocsFreq = minDocsFreq;+ this.minTermFreq = minTermFreq;+ }+/*** {@inheritDoc}*/@@ -93,11 +109,11 @@ public class KNearestNeighborClassifier implements Classifier<BytesRef> {}double max = 0;BytesRef assignedClass = new BytesRef();- for (BytesRef cl : classCounts.keySet()) {- Integer count = classCounts.get(cl);+ for (Map.Entry<BytesRef, Integer> entry : classCounts.entrySet()) {+ Integer count = entry.getValue();if (count > max) {max = count;- assignedClass = cl.clone();+ assignedClass = entry.getKey().clone();}}double score = max / (double) k;@@ -117,13 +133,7 @@ public class KNearestNeighborClassifier implements Classifier<BytesRef> {*/@Overridepublic void train(AtomicReader atomicReader, String textFieldName, String classFieldName, Analyzer analyzer, Query query) throws IOException {- this.textFieldNames = new String[]{textFieldName};- this.classFieldName = classFieldName;- mlt = new MoreLikeThis(atomicReader);- mlt.setAnalyzer(analyzer);- mlt.setFieldNames(new String[]{textFieldName});- indexSearcher = new IndexSearcher(atomicReader);- this.query = query;+ train(atomicReader, new String[]{textFieldName}, classFieldName, analyzer, query);}/**@@ -137,6 +147,12 @@ public class KNearestNeighborClassifier implements Classifier<BytesRef> {mlt.setAnalyzer(analyzer);mlt.setFieldNames(textFieldNames);indexSearcher = new IndexSearcher(atomicReader);+ if (minDocsFreq > 0) {+ mlt.setMinDocFreq(minDocsFreq);+ }+ if (minTermFreq > 0) {+ mlt.setMinTermFreq(minTermFreq);+ }this.query = query;}}diff --git a/lucene/classification/src/test/org/apache/lucene/classification/ClassificationTestBase.java b/lucene/classification/src/test/org/apache/lucene/classification/ClassificationTestBase.javaindex cd488043fd5..f8de59fa90f 100644--- a/lucene/classification/src/test/org/apache/lucene/classification/ClassificationTestBase.java+++ b/lucene/classification/src/test/org/apache/lucene/classification/ClassificationTestBase.java@@ -39,14 +39,17 @@ import java.util.Random;* Base class for testing {@link Classifier}s*/public abstract class ClassificationTestBase<T> extends LuceneTestCase {- public final static String POLITICS_INPUT = "Here are some interesting questions and answers about Mitt Romney.. If you don't know the answer to the question about Mitt Romney, then simply click on the answer below the question section.";+ public final static String POLITICS_INPUT = "Here are some interesting questions and answers about Mitt Romney.. " ++ "If you don't know the answer to the question about Mitt Romney, then simply click on the answer below the question section.";public static final BytesRef POLITICS_RESULT = new BytesRef("politics");- public static final String TECHNOLOGY_INPUT = "Much is made of what the likes of Facebook, Google and Apple know about users. Truth is, Amazon may know more.";+ public static final String TECHNOLOGY_INPUT = "Much is made of what the likes of Facebook, Google and Apple know about users." ++ " Truth is, Amazon may know more.";public static final BytesRef TECHNOLOGY_RESULT = new BytesRef("technology");private RandomIndexWriter indexWriter;private Directory dir;+ private FieldType ft;String textFieldName;String categoryFieldName;@@ -61,6 +64,10 @@ public abstract class ClassificationTestBase<T> extends LuceneTestCase {textFieldName = "text";categoryFieldName = "cat";booleanFieldName = "bool";+ ft = new FieldType(TextField.TYPE_STORED);+ ft.setStoreTermVectors(true);+ ft.setStoreTermVectorOffsets(true);+ ft.setStoreTermVectorPositions(true);}@Override@@ -72,7 +79,7 @@ public abstract class ClassificationTestBase<T> extends LuceneTestCase {}protected void checkCorrectClassification(Classifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName) throws Exception {- checkCorrectClassification(classifier, inputDoc, expectedResult, analyzer, textFieldName, classFieldName, null);+ checkCorrectClassification(classifier, inputDoc, expectedResult, analyzer, textFieldName, classFieldName, null);}protected void checkCorrectClassification(Classifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName, Query query) throws Exception {@@ -90,6 +97,106 @@ public abstract class ClassificationTestBase<T> extends LuceneTestCase {atomicReader.close();}}+ protected void checkOnlineClassification(Classifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName) throws Exception {+ checkOnlineClassification(classifier, inputDoc, expectedResult, analyzer, textFieldName, classFieldName, null);+ }++ protected void checkOnlineClassification(Classifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName, Query query) throws Exception {+ AtomicReader atomicReader = null;+ try {+ populateSampleIndex(analyzer);+ atomicReader = SlowCompositeReaderWrapper.wrap(indexWriter.getReader());+ classifier.train(atomicReader, textFieldName, classFieldName, analyzer, query);+ ClassificationResult<T> classificationResult = classifier.assignClass(inputDoc);+ assertNotNull(classificationResult.getAssignedClass());+ assertEquals("got an assigned class of " + classificationResult.getAssignedClass(), expectedResult, classificationResult.getAssignedClass());+ assertTrue("got a not positive score " + classificationResult.getScore(), classificationResult.getScore() > 0);+ updateSampleIndex(analyzer);+ ClassificationResult<T> secondClassificationResult = classifier.assignClass(inputDoc);+ assertEquals(classificationResult.getAssignedClass(), secondClassificationResult.getAssignedClass());+ assertEquals(Double.valueOf(classificationResult.getScore()), Double.valueOf(secondClassificationResult.getScore()));++ } finally {+ if (atomicReader != null)+ atomicReader.close();+ }+ }++ private void populateSampleIndex(Analyzer analyzer) throws IOException {+ indexWriter.deleteAll();+ indexWriter.commit();++ String text;++ Document doc = new Document();+ text = "The traveling press secretary for Mitt Romney lost his cool and cursed at reporters " ++ "who attempted to ask questions of the Republican presidential candidate in a public plaza near the Tomb of " ++ "the Unknown Soldier in Warsaw Tuesday.";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "politics", ft));+ doc.add(new Field(booleanFieldName, "true", ft));++ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "Mitt Romney seeks to assure Israel and Iran, as well as Jewish voters in the United" ++ " States, that he will be tougher against Iran's nuclear ambitions than President Barack Obama.";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "politics", ft));+ doc.add(new Field(booleanFieldName, "true", ft));+ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "And there's a threshold question that he has to answer for the American people and " ++ "that's whether he is prepared to be commander-in-chief,\" she continued. \"As we look to the past events, we " ++ "know that this raises some questions about his preparedness and we'll see how the rest of his trip goes.\"";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "politics", ft));+ doc.add(new Field(booleanFieldName, "true", ft));+ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "Still, when it comes to gun policy, many congressional Democrats have \"decided to " ++ "keep quiet and not go there,\" said Alan Lizotte, dean and professor at the State University of New York at " ++ "Albany's School of Criminal Justice.";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "politics", ft));+ doc.add(new Field(booleanFieldName, "true", ft));+ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "Standing amongst the thousands of people at the state Capitol, Jorstad, director of " ++ "technology at the University of Wisconsin-La Crosse, documented the historic moment and shared it with the " ++ "world through the Internet.";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "technology", ft));+ doc.add(new Field(booleanFieldName, "false", ft));+ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "So, about all those experts and analysts who've spent the past year or so saying " ++ "Facebook was going to make a phone. A new expert has stepped forward to say it's not going to happen.";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "technology", ft));+ doc.add(new Field(booleanFieldName, "false", ft));+ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "More than 400 million people trust Google with their e-mail, and 50 million store files" ++ " in the cloud using the Dropbox service. People manage their bank accounts, pay bills, trade stocks and " ++ "generally transfer or store huge volumes of personal data online.";+ doc.add(new Field(textFieldName, text, ft));+ doc.add(new Field(categoryFieldName, "technology", ft));+ doc.add(new Field(booleanFieldName, "false", ft));+ indexWriter.addDocument(doc, analyzer);++ doc = new Document();+ text = "unlabeled doc";+ doc.add(new Field(textFieldName, text, ft));+ indexWriter.addDocument(doc, analyzer);++ indexWriter.commit();+ }protected void checkPerformance(Classifier<T> classifier, Analyzer analyzer, String classFieldName) throws Exception {AtomicReader atomicReader = null;@@ -137,22 +244,12 @@ public abstract class ClassificationTestBase<T> extends LuceneTestCase {return builder.toString();}- private void populateSampleIndex(Analyzer analyzer) throws Exception {-- indexWriter.deleteAll();- indexWriter.commit();-- FieldType ft = new FieldType(TextField.TYPE_STORED);- ft.setStoreTermVectors(true);- ft.setStoreTermVectorOffsets(true);- ft.setStoreTermVectorPositions(true);+ private void updateSampleIndex(Analyzer analyzer) throws Exception {String text;Document doc = new Document();- text = "The traveling press secretary for Mitt Romney lost his cool and cursed at reporters " +- "who attempted to ask questions of the Republican presidential candidate in a public plaza near the Tomb of " +- "the Unknown Soldier in Warsaw Tuesday.";+ text = "Warren Bennis says John F. Kennedy grasped a key lesson about the presidency that few have followed.";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "politics", ft));doc.add(new Field(booleanFieldName, "true", ft));@@ -160,59 +257,49 @@ public abstract class ClassificationTestBase<T> extends LuceneTestCase {indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "Mitt Romney seeks to assure Israel and Iran, as well as Jewish voters in the United" +- " States, that he will be tougher against Iran's nuclear ambitions than President Barack Obama.";+ text = "Julian Zelizer says Bill Clinton is still trying to shape his party, years after the White House, while George W. Bush opts for a much more passive role.";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "politics", ft));doc.add(new Field(booleanFieldName, "true", ft));indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "And there's a threshold question that he has to answer for the American people and " +- "that's whether he is prepared to be commander-in-chief,\" she continued. \"As we look to the past events, we " +- "know that this raises some questions about his preparedness and we'll see how the rest of his trip goes.\"";+ text = "Crossfire: Sen. Tim Scott passes on Sen. Lindsey Graham endorsement";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "politics", ft));doc.add(new Field(booleanFieldName, "true", ft));indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "Still, when it comes to gun policy, many congressional Democrats have \"decided to " +- "keep quiet and not go there,\" said Alan Lizotte, dean and professor at the State University of New York at " +- "Albany's School of Criminal Justice.";+ text = "Illinois becomes 16th state to allow same-sex marriage.";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "politics", ft));doc.add(new Field(booleanFieldName, "true", ft));indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "Standing amongst the thousands of people at the state Capitol, Jorstad, director of " +- "technology at the University of Wisconsin-La Crosse, documented the historic moment and shared it with the " +- "world through the Internet.";+ text = "Apple is developing iPhones with curved-glass screens and enhanced sensors that detect different levels of pressure, according to a new report.";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "technology", ft));doc.add(new Field(booleanFieldName, "false", ft));indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "So, about all those experts and analysts who've spent the past year or so saying " +- "Facebook was going to make a phone. A new expert has stepped forward to say it's not going to happen.";+ text = "The Xbox One is Microsoft's first new gaming console in eight years. It's a quality piece of hardware but it's also noteworthy because Microsoft is using it to make a statement.";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "technology", ft));doc.add(new Field(booleanFieldName, "false", ft));indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "More than 400 million people trust Google with their e-mail, and 50 million store files" +- " in the cloud using the Dropbox service. People manage their bank accounts, pay bills, trade stocks and " +- "generally transfer or store huge volumes of personal data online.";+ text = "Google says it will replace a Google Maps image after a California father complained it shows the body of his teen-age son, who was shot to death in 2009.";doc.add(new Field(textFieldName, text, ft));doc.add(new Field(categoryFieldName, "technology", ft));doc.add(new Field(booleanFieldName, "false", ft));indexWriter.addDocument(doc, analyzer);doc = new Document();- text = "unlabeled doc";+ text = "second unlabeled doc";doc.add(new Field(textFieldName, text, ft));indexWriter.addDocument(doc, analyzer);diff --git a/lucene/classification/src/test/org/apache/lucene/classification/KNearestNeighborClassifierTest.java b/lucene/classification/src/test/org/apache/lucene/classification/KNearestNeighborClassifierTest.javaindex 7e754adb560..2a0308286f2 100644--- a/lucene/classification/src/test/org/apache/lucene/classification/KNearestNeighborClassifierTest.java+++ b/lucene/classification/src/test/org/apache/lucene/classification/KNearestNeighborClassifierTest.java@@ -29,7 +29,10 @@ public class KNearestNeighborClassifierTest extends ClassificationTestBase<Bytes@Testpublic void testBasicUsage() throws Exception {- checkCorrectClassification(new KNearestNeighborClassifier(1), TECHNOLOGY_INPUT, TECHNOLOGY_RESULT, new MockAnalyzer(random()), textFieldName, categoryFieldName);+ // usage with default MLT min docs / term freq+ checkCorrectClassification(new KNearestNeighborClassifier(3), POLITICS_INPUT, POLITICS_RESULT, new MockAnalyzer(random()), textFieldName, categoryFieldName);+ // usage without custom min docs / term freq for MLT+ checkCorrectClassification(new KNearestNeighborClassifier(3, 2, 1), TECHNOLOGY_INPUT, TECHNOLOGY_RESULT, new MockAnalyzer(random()), textFieldName, categoryFieldName);}@Test