Search in sources :

Example 1 with EvaluationResult

use of zemberek.core.embeddings.FastText.EvaluationResult in project zemberek-nlp by ahmetaa.

the class CategoryPredictionExperiment method runExperiment.

private void runExperiment() throws Exception {
    Path corpusPath = experimentRoot.resolve("category.corpus");
    Path train = experimentRoot.resolve("category.train");
    Path test = experimentRoot.resolve("category.test");
    Path titleRaw = experimentRoot.resolve("category.title");
    Path modelPath = experimentRoot.resolve("category.model");
    Path predictionPath = experimentRoot.resolve("category.predictions");
    extractCategoryDocuments(rawCorpusRoot, corpusPath);
    boolean useOnlyTitles = true;
    boolean useLemmas = true;
    generateSets(corpusPath, train, test, useOnlyTitles, useLemmas);
    generateRawSet(corpusPath, titleRaw);
    FastText fastText;
    if (modelPath.toFile().exists()) {
        Log.info("Reusing existing model %s", modelPath);
        fastText = FastText.load(modelPath);
    } else {
        Args argz = Args.forSupervised();
        argz.thread = 4;
        argz.model = Args.model_name.supervised;
        argz.loss = Args.loss_name.softmax;
        argz.epoch = 50;
        argz.wordNgrams = 2;
        argz.minCount = 0;
        argz.lr = 0.5;
        argz.dim = 100;
        argz.bucket = 5_000_000;
        fastText = new FastTextTrainer(argz).train(train);
        fastText.saveModel(modelPath);
    }
    EvaluationResult result = fastText.test(test, 1);
    Log.info(result.toString());
    WebCorpus corpus = new WebCorpus("corpus", "labeled");
    corpus.addDocuments(WebCorpus.loadDocuments(corpusPath));
    Log.info("Testing started.");
    List<String> testLines = Files.readAllLines(test, StandardCharsets.UTF_8);
    try (PrintWriter pw = new PrintWriter(predictionPath.toFile(), "utf-8")) {
        for (String testLine : testLines) {
            String id = testLine.substring(0, testLine.indexOf(' ')).substring(1);
            WebDocument doc = corpus.getDocument(id);
            List<ScoredItem<String>> res = fastText.predict(testLine, 3);
            List<String> predictedCategories = new ArrayList<>();
            for (ScoredItem<String> re : res) {
                if (re.score < -10) {
                    continue;
                }
                predictedCategories.add(String.format(Locale.ENGLISH, "%s (%.2f)", re.item.replaceAll("__label__", "").replaceAll("_", " "), re.score));
            }
            pw.println("id = " + id);
            pw.println();
            pw.println(doc.getTitle());
            pw.println();
            pw.println("Actual Category = " + doc.getCategory());
            pw.println("Predictions   = " + String.join(", ", predictedCategories));
            pw.println();
            pw.println("------------------------------------------------------");
            pw.println();
        }
    }
    Log.info("Done.");
}
Also used : Path(java.nio.file.Path) Args(zemberek.core.embeddings.Args) ScoredItem(zemberek.core.ScoredItem) ArrayList(java.util.ArrayList) FastTextTrainer(zemberek.core.embeddings.FastTextTrainer) EvaluationResult(zemberek.core.embeddings.FastText.EvaluationResult) WebDocument(zemberek.corpus.WebDocument) WebCorpus(zemberek.corpus.WebCorpus) FastText(zemberek.core.embeddings.FastText) PrintWriter(java.io.PrintWriter)

Example 2 with EvaluationResult

use of zemberek.core.embeddings.FastText.EvaluationResult in project zemberek-nlp by ahmetaa.

the class FastTextTest method test.

private void test(FastText f, Path testPath, int k) throws IOException {
    EvaluationResult result = f.test(testPath, k);
    Log.info(result.toString());
}
Also used : EvaluationResult(zemberek.core.embeddings.FastText.EvaluationResult)

Example 3 with EvaluationResult

use of zemberek.core.embeddings.FastText.EvaluationResult in project zemberek-nlp by ahmetaa.

the class EvaluateClassifier method run.

@Override
public void run() throws Exception {
    System.out.println("Loading classification model...");
    FastTextClassifier classifier = FastTextClassifier.load(model);
    EvaluationResult result = classifier.evaluate(input, maxPrediction, threshold);
    System.out.println("Result = " + result.toString());
    if (predictions == null) {
        String name = input.toFile().getName();
        predictions = Paths.get("").resolve(name + ".predictions");
    }
    List<String> testLines = Files.readAllLines(input, StandardCharsets.UTF_8);
    try (PrintWriter pw = new PrintWriter(predictions.toFile(), "utf-8")) {
        for (String testLine : testLines) {
            List<ScoredItem<String>> res = classifier.predict(testLine, maxPrediction);
            res = res.stream().filter(s -> s.score >= threshold).collect(Collectors.toList());
            List<String> predictedCategories = new ArrayList<>();
            for (ScoredItem<String> re : res) {
                predictedCategories.add(String.format(Locale.ENGLISH, "%s (%.6f)", re.item.replaceAll("__label__", ""), Math.exp(re.score)));
            }
            pw.println(testLine);
            pw.println("Predictions   = " + String.join(", ", predictedCategories));
            pw.println();
        }
    }
    System.out.println("Predictions are written to " + predictions);
}
Also used : FastTextClassifier(zemberek.classification.FastTextClassifier) ScoredItem(zemberek.core.ScoredItem) ArrayList(java.util.ArrayList) EvaluationResult(zemberek.core.embeddings.FastText.EvaluationResult) PrintWriter(java.io.PrintWriter)

Example 4 with EvaluationResult

use of zemberek.core.embeddings.FastText.EvaluationResult in project zemberek-nlp by ahmetaa.

the class FastTextTest method dbpediaClassificationTest.

/**
 * Runs the dbpedia classification task. run with -Xms8G or more.
 */
@Test
@Ignore("Not an actual Test.")
public void dbpediaClassificationTest() throws Exception {
    Path inputRoot = Paths.get("/media/aaa/3t/aaa/fasttext");
    Path trainFile = inputRoot.resolve("dbpedia.train");
    Path modelPath = Paths.get("/media/aaa/3t/aaa/fasttext/dbpedia.model.bin");
    FastText fastText;
    if (modelPath.toFile().exists()) {
        fastText = FastText.load(modelPath);
    } else {
        Args argz = Args.forSupervised();
        argz.thread = 4;
        argz.epoch = 5;
        argz.wordNgrams = 2;
        argz.minCount = 1;
        argz.lr = 0.1;
        argz.dim = 32;
        argz.bucket = 5_000_000;
        fastText = new FastTextTrainer(argz).train(trainFile);
        fastText.saveModel(modelPath);
    }
    Path testFile = inputRoot.resolve("dbpedia.test");
    Log.info("Testing started.");
    EvaluationResult result = fastText.test(testFile, 1);
    Log.info(result.toString());
}
Also used : Path(java.nio.file.Path) Args(zemberek.core.embeddings.Args) FastTextTrainer(zemberek.core.embeddings.FastTextTrainer) EvaluationResult(zemberek.core.embeddings.FastText.EvaluationResult) FastText(zemberek.core.embeddings.FastText) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

EvaluationResult (zemberek.core.embeddings.FastText.EvaluationResult)4 PrintWriter (java.io.PrintWriter)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 ScoredItem (zemberek.core.ScoredItem)2 Args (zemberek.core.embeddings.Args)2 FastText (zemberek.core.embeddings.FastText)2 FastTextTrainer (zemberek.core.embeddings.FastTextTrainer)2 Ignore (org.junit.Ignore)1 Test (org.junit.Test)1 FastTextClassifier (zemberek.classification.FastTextClassifier)1 WebCorpus (zemberek.corpus.WebCorpus)1 WebDocument (zemberek.corpus.WebDocument)1