Apache Lucene open-source search software
[LUCENE-4345] - added utility class for creating training / test / cv index from a single index
Tommaso Teofili3459b28334e2
diff --git a/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java b/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.javanew file mode 100644index 00000000000..5f1f6074a72--- /dev/null+++ b/lucene/classification/src/java/org/apache/lucene/classification/utils/DatasetSplitter.java@@ -0,0 +1,124 @@+package org.apache.lucene.classification.utils;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.FieldType;+import org.apache.lucene.document.TextField;+import org.apache.lucene.index.AtomicReader;+import org.apache.lucene.index.IndexWriter;+import org.apache.lucene.index.IndexWriterConfig;+import org.apache.lucene.index.StorableField;+import org.apache.lucene.search.IndexSearcher;+import org.apache.lucene.search.MatchAllDocsQuery;+import org.apache.lucene.search.ScoreDoc;+import org.apache.lucene.search.TopDocs;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.Version;++import java.io.IOException;++/**+ * Utility class for creating training / test / cross validation indexes from the original index.+ */+public class DatasetSplitter {++ private double crossValidationRatio;+ private double testRatio;++ public DatasetSplitter(double testRatio, double crossValidationRatio) {+ this.crossValidationRatio = crossValidationRatio;+ this.testRatio = testRatio;+ }++ public void split(AtomicReader originalIndex, Directory trainingIndex, Directory testIndex, Directory crossValidationIndex,+ Analyzer analyzer, String... fieldNames) throws IOException {++ // TODO : check that the passed fields are stored in the original index++ // create IWs for train / test / cv IDXs+ IndexWriter testWriter = new IndexWriter(testIndex, new IndexWriterConfig(Version.LUCENE_50, analyzer));+ IndexWriter cvWriter = new IndexWriter(crossValidationIndex, new IndexWriterConfig(Version.LUCENE_50, analyzer));+ IndexWriter trainingWriter = new IndexWriter(trainingIndex, new IndexWriterConfig(Version.LUCENE_50, analyzer));++ try {+ int size = originalIndex.maxDoc();++ IndexSearcher indexSearcher = new IndexSearcher(originalIndex);+ TopDocs topDocs = indexSearcher.search(new MatchAllDocsQuery(), Integer.MAX_VALUE);++ // set the type to be indexed, stored, with term vectors+ FieldType ft = new FieldType(TextField.TYPE_STORED);+ ft.setStoreTermVectors(true);+ ft.setStoreTermVectorOffsets(true);+ ft.setStoreTermVectorPositions(true);++ int b = 0;++ // iterate over existing documents+ for (ScoreDoc scoreDoc : topDocs.scoreDocs) {++ // create a new document for indexing+ Document doc = new Document();+ if (fieldNames != null && fieldNames.length > 0) {+ for (String fieldName : fieldNames) {+ doc.add(new Field(fieldName, originalIndex.document(scoreDoc.doc).getField(fieldName).stringValue(), ft));+ }+ } else {+ for (StorableField storableField : originalIndex.document(scoreDoc.doc).getFields()) {+ if (storableField.readerValue()!= null){+ doc.add(new Field(storableField.name(), storableField.readerValue(), ft));+ }+ else if (storableField.binaryValue()!= null){+ doc.add(new Field(storableField.name(), storableField.binaryValue(), ft));+ }+ else if (storableField.stringValue()!= null){+ doc.add(new Field(storableField.name(), storableField.stringValue(), ft));+ }+ else if (storableField.numericValue()!= null){+ doc.add(new Field(storableField.name(), storableField.numericValue().toString(), ft));+ }+ }+ }++ // add it to one of the IDXs+ if (b % 2 == 0 && testWriter.maxDoc() < size * testRatio) {+ testWriter.addDocument(doc);+ testWriter.commit();+ } else if (cvWriter.maxDoc() < size * crossValidationRatio) {+ cvWriter.addDocument(doc);+ cvWriter.commit();+ } else {+ trainingWriter.addDocument(doc);+ trainingWriter.commit();+ }+ b++;+ }+ } catch (Exception e) {+ throw new IOException(e);+ } finally {+ // close IWs+ testWriter.close();+ cvWriter.close();+ trainingWriter.close();+ }+ }++}diff --git a/lucene/classification/src/test/org/apache/lucene/classification/utils/DataSplitterTest.java b/lucene/classification/src/test/org/apache/lucene/classification/utils/DataSplitterTest.javanew file mode 100644index 00000000000..84171553801--- /dev/null+++ b/lucene/classification/src/test/org/apache/lucene/classification/utils/DataSplitterTest.java@@ -0,0 +1,145 @@+package org.apache.lucene.classification.utils;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;+import org.apache.lucene.document.FieldType;+import org.apache.lucene.document.TextField;+import org.apache.lucene.index.AtomicReader;+import org.apache.lucene.index.DirectoryReader;+import org.apache.lucene.index.IndexReader;+import org.apache.lucene.index.RandomIndexWriter;+import org.apache.lucene.index.SlowCompositeReaderWrapper;+import org.apache.lucene.store.BaseDirectoryWrapper;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.LuceneTestCase;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import java.io.IOException;+import java.util.Random;++/**+ * Testcase for {@link org.apache.lucene.classification.utils.DatasetSplitter}+ */+public class DataSplitterTest extends LuceneTestCase {++ private AtomicReader originalIndex;+ private RandomIndexWriter indexWriter;+ private Directory dir;++ private String textFieldName = "text";+ private String classFieldName = "class";+ private String idFieldName = "id";++ @Before+ public void setUp() throws Exception {+ super.setUp();+ dir = newDirectory();+ indexWriter = new RandomIndexWriter(random(), dir);++ FieldType ft = new FieldType(TextField.TYPE_STORED);+ ft.setStoreTermVectors(true);+ ft.setStoreTermVectorOffsets(true);+ ft.setStoreTermVectorPositions(true);++ Analyzer analyzer = new MockAnalyzer(new Random());++ Document doc;+ for (int i = 0; i < 100; i++) {+ doc = new Document();+ doc.add(new Field(idFieldName, new Random().toString(), ft));+ doc.add(new Field(textFieldName, new StringBuilder(new Random().toString()).append(new Random().toString()).append(+ new Random().toString()).toString(), ft));+ doc.add(new Field(classFieldName, new Random().toString(), ft));+ indexWriter.addDocument(doc, analyzer);+ }++ indexWriter.commit();++ originalIndex = SlowCompositeReaderWrapper.wrap(indexWriter.getReader());++ }++ @After+ public void tearDown() throws Exception {+ originalIndex.close();+ indexWriter.close();+ dir.close();+ super.tearDown();+ }+++ @Test+ public void testSplitOnAllFields() throws Exception {+ assertSplit(originalIndex, 0.1, 0.1, null);+ }+++ @Test+ public void testSplitOnSomeFields() throws Exception {+ assertSplit(originalIndex, 0.2, 0.35, idFieldName, textFieldName);+ }++ public static void assertSplit(AtomicReader originalIndex, double testRatio, double crossValidationRatio, String... fieldNames) throws Exception {++ BaseDirectoryWrapper trainingIndex = newDirectory();+ BaseDirectoryWrapper testIndex = newDirectory();+ BaseDirectoryWrapper crossValidationIndex = newDirectory();++ try {+ DatasetSplitter datasetSplitter = new DatasetSplitter(testRatio, crossValidationRatio);+ datasetSplitter.split(originalIndex, trainingIndex, testIndex, crossValidationIndex, new MockAnalyzer(new Random()), fieldNames);++ assertNotNull(trainingIndex);+ assertNotNull(testIndex);+ assertNotNull(crossValidationIndex);++ DirectoryReader trainingReader = DirectoryReader.open(trainingIndex);+ assertTrue((int) (originalIndex.maxDoc() * (1d - testRatio - crossValidationRatio)) == trainingReader.maxDoc());+ DirectoryReader testReader = DirectoryReader.open(testIndex);+ assertTrue((int) (originalIndex.maxDoc() * testRatio) == testReader.maxDoc());+ DirectoryReader cvReader = DirectoryReader.open(crossValidationIndex);+ assertTrue((int) (originalIndex.maxDoc() * crossValidationRatio) == cvReader.maxDoc());++ trainingReader.close();+ testReader.close();+ cvReader.close();+ closeQuietly(trainingReader);+ closeQuietly(testReader);+ closeQuietly(cvReader);+ } finally {+ trainingIndex.close();+ testIndex.close();+ crossValidationIndex.close();+ }+ }++ private static void closeQuietly(IndexReader reader) throws IOException {+ try {+ if (reader != null)+ reader.close();+ } catch (Exception e) {+ // do nothing+ }+ }+}