Запуск MALLET в Java

Я пытаюсь запустить Mallet на Java и получаю следующую ошибку.

Couldn't open cc.mallet.util.MalletLogger resources/logging.properties file.
Perhaps the 'resources' directories weren't copied into the 'class' directory.
Continuing.

Я пытаюсь запустить пример с веб-сайта Маллета (http://mallet.cs.umass.edu/topics-devel.php). Ниже мой код. Любая помощь приветствуется.

package scriptAnalyzer;

import cc.mallet.util.*;
import cc.mallet.types.*;
import cc.mallet.pipe.*;
import cc.mallet.pipe.iterator.*;
import cc.mallet.topics.*;

import java.util.*;
import java.util.regex.*;
import java.io.*;

public class Mallet {

    public static void main(String[] args) throws Exception {

        String filePath = "C:/mallet/ap.txt";
        // Begin by importing documents from text to feature sequences
        ArrayList<Pipe> pipeList = new ArrayList<Pipe>();

        // Pipes: lowercase, tokenize, remove stopwords, map to features
        pipeList.add( new CharSequenceLowercase() );
        pipeList.add( new CharSequence2TokenSequence(Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")) );
        pipeList.add( new TokenSequenceRemoveStopwords(new File("stoplists/en.txt"), "UTF-8", false, false, false) );
        pipeList.add( new TokenSequence2FeatureSequence() );

        InstanceList instances = new InstanceList (new SerialPipes(pipeList));

        Reader fileReader = new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8");
        instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),
                                               3, 2, 1)); // data, label, name fields

        // Create a model with 100 topics, alpha_t = 0.01, beta_w = 0.01
        //  Note that the first parameter is passed as the sum over topics, while
        //  the second is the parameter for a single dimension of the Dirichlet prior.
        int numTopics = 5;
        ParallelTopicModel model = new ParallelTopicModel(numTopics, 1.0, 0.01);

        model.addInstances(instances);

        // Use two parallel samplers, which each look at one half the corpus and combine
        //  statistics after every iteration.
        model.setNumThreads(2);

        // Run the model for 50 iterations and stop (this is for testing only, 
        //  for real applications, use 1000 to 2000 iterations)
        model.setNumIterations(50);
        model.estimate();

        // Show the words and topics in the first instance

        // The data alphabet maps word IDs to strings
        Alphabet dataAlphabet = instances.getDataAlphabet();

        FeatureSequence tokens = (FeatureSequence) model.getData().get(0).instance.getData();
        LabelSequence topics = model.getData().get(0).topicSequence;

        Formatter out = new Formatter(new StringBuilder(), Locale.US);
        for (int position = 0; position < tokens.getLength(); position++) {
            out.format("%s-%d ", dataAlphabet.lookupObject(tokens.getIndexAtPosition(position)), topics.getIndexAtPosition(position));
        }
        System.out.println(out);

        // Estimate the topic distribution of the first instance, 
        //  given the current Gibbs state.
        double[] topicDistribution = model.getTopicProbabilities(0);

        // Get an array of sorted sets of word ID/count pairs
        ArrayList<TreeSet<IDSorter>> topicSortedWords = model.getSortedWords();

        // Show top 5 words in topics with proportions for the first document
        for (int topic = 0; topic < numTopics; topic++) {
            Iterator<IDSorter> iterator = topicSortedWords.get(topic).iterator();

            out = new Formatter(new StringBuilder(), Locale.US);
            out.format("%d\t%.3f\t", topic, topicDistribution[topic]);
            int rank = 0;
            while (iterator.hasNext() && rank < 5) {
                IDSorter idCountPair = iterator.next();
                out.format("%s (%.0f) ", dataAlphabet.lookupObject(idCountPair.getID()), idCountPair.getWeight());
                rank++;
            }
            System.out.println(out);
        }

        // Create a new instance with high probability of topic 0
        StringBuilder topicZeroText = new StringBuilder();
        Iterator<IDSorter> iterator = topicSortedWords.get(0).iterator();

        int rank = 0;
        while (iterator.hasNext() && rank < 5) {
            IDSorter idCountPair = iterator.next();
            topicZeroText.append(dataAlphabet.lookupObject(idCountPair.getID()) + " ");
            rank++;
        }

        // Create a new instance named "test instance" with empty target and source fields.
        InstanceList testing = new InstanceList(instances.getPipe());
        testing.addThruPipe(new Instance(topicZeroText.toString(), null, "test instance", null));

        TopicInferencer inferencer = model.getInferencer();
        double[] testProbabilities = inferencer.getSampledDistribution(testing.get(0), 10, 1, 5);
        System.out.println("0\t" + testProbabilities[0]);
    }

}

person user2962197    schedule 06.01.2014    source источник
comment
Похоже, пропал resources/logging.properties. Он использует Maven? Муравей? Вы правильно строите?   -  person Dave Newton    schedule 07.01.2014


Ответы (4)


Если вы попытаетесь запустить Mallet, загрузив версию 2.0.8-SNAPSHOT (https://github.com/mimno/Mallet) или получив последнюю версию maven (2.0.7), вы получите эту ошибку.

Причина в том, что Маллет ожидает файл logging.properties внутри созданной папки target\classes\cc\mallet\util\resources. Когда вы создаете проект с помощью maven, этот файл не создается, поэтому это исключение возникает в MalletLogger.java.

Кто-то должен либо правильно настроить maven, чтобы файл logging.properties был создан в целевой папке. Временным решением было бы изменить код Маллета, чтобы установить другой путь для logging.properties.

person Stamatis Rapanakis    schedule 11.07.2014

Маллет ищет файл журнала, если он не указан в свойствах системы. Самый простой способ разобраться с этим, если вы используете Maven, — поместить файл в

src/main/resources/cc/mallet/util/resources/logging.properties 

это автоматически скопирует часть стандартного процесса сборки Maven в:

target/classes/cc/mallet/util/resources/logging.properties 

Таким образом, вам не нужна никакая специальная конфигурация. Файл может быть пустым, но логически намеренно опущен, поэтому вы настраиваете собственное ведение журнала.

person Richard Vowles    schedule 16.10.2015
comment
Работает и для Gradle. - person Danke Xie; 04.12.2017

Для всех, кто использует Maven и пытается настроить ведение журнала Mallet, попробуйте следующее:

Создайте новый текстовый файл по адресу src/mallet_resources/logging.properties. На самом деле не нужно ничего указывать; пустого файла достаточно, чтобы Маллет заткнулся.

Затем измените файл pom.xml, чтобы убедиться, что файл скопирован в место, указанное в другом ответе. Для этого в разделе <build><plugins> добавляем:

<!--Mallet logging is horrifically verbose, and has not easy to configure-->
<!--We have to use this complicated process to copy the logging.properties file to the right location -->
<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
    <executions>
        <execution>
            <id>copy-resources</id>
            <phase>validate</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>
                    ${basedir}/target/classes/cc/mallet/util/resources
                </outputDirectory>
                <resources>
                    <resource>
                        <directory>src/mallet-resources</directory>
                        <filtering>true</filtering>
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>
person Dave    schedule 19.08.2014

Относительно ошибки «Не удалось открыть файл edu.umass.cs.mallet.base.util.MalletLogger resources/logging.properties», которая возникает (например) при запуске run.sh (или другого скрипта или команды) в BANNER Named Entity Распознавание (использует МОЛОТОК).

Решение:

Скопируйте logging.properties из

src/main/java/edu/umass/cs/mallet/base/util/resources/logging.properties

to

цель/скала-2.11/классы/образование/umass/CS/маллет/база/утилита/ресурсы/logging.properties

[Я использую БАННЕР, предоставленный по адресу https://github.com/clulab/banner]

Еще одну ошибку, с которой я столкнулся в то же время (... Не удалось выполнить логирование класса конфигурации "edu.umass.cs.mallet.base.util.Logger.DefaultConfigurator"), можно смело игнорировать:

https://osdir.com/ml/ai.mallet.devel/2007-11/msg00008.html >> «Я думаю, что это ошибка дистрибутива, но она влияет только на ведение журнала. Я всегда игнорировал это предупреждение».

http://comments.gmane.org/gmane.comp.ai.mallet.devel/200 >> «Эта ошибка не должна влиять на ваш вывод».

http://courses.washington.edu/ling572/winter09/teaching_slides/1_08_Mallet.pptx >> Слайд 20: «Не обращайте внимания на это сообщение». [Фей Ся, январь 2009 г., «Введение в Маллет», группа Эндрю МакКаллума в Университете Массачусетса (https://people.cs.umass.edu/~mccallum/)]

person Victoria Stuart    schedule 15.10.2015