言語処理100本ノックでPython入門 #56 - Stanford Core NLPの共参照解析


今日は、言語処理100本ノック 2015の第6章・問題56です。


■ 問題
56. 共参照解析
Stanford Core NLPの共参照解析の結果に基づき,文中の参照表現(mention)を代表参照表現(representative mention)に置換せよ.ただし,置換するときは,「代表参照表現(参照表現)」のように,元の参照表現が分かるように配慮せよ.

■ nlp.txt.xmlファイルの再作成


java -cp "/Users/hideyuki/Documents/Dev/corenlp/*" -Xmx3g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner,parse,dcoref -file nlp.txt

    <mention representative="true">
representative="true"の属性のあるのが「代表参照表現」で、この属性の無いのが「参照表現」です(たぶん)。 start, endは、tokenの番号です。


■ 置き換え処理を考える




ちなみに、Stanford Core NLPの共参照解析の結果そのものが「これでいいのかな?」と疑問に思うようなものがあります。でもそれはもうどうしようもないです。

■ Pythonのコード

今回は、CoreferenceAnalyserというクラスを定義してみました。 いままでは関数主体のコードでしたが、C#erの僕には今回のようにclassを定義したほうがしっくりきますね。

from xml.etree import ElementTree

class CoreferenceAnalyser:
    def __init__(self, filepath):
        xdoc = ElementTree.parse(filepath)
        root = xdoc.getroot()
        self.sentences = root.find('document/sentences')
        self.coreference = root.find('document/coreference')

    def enumCoreference(self):
        for e in self.coreference:
            yield e

    # mentionのtext内容をrepresentativeMentionの内容に置き換える
    def replaceMention(self, mention, representativeMention):
        sentenceid = mention.find('sentence').text
        startid = mention.find('start').text
        endid = str(int(mention.find('end').text) - 1)
        targetSentence = self.sentences.find("sentence[@id='" + sentenceid  + "']")
        startToken = targetSentence.find("tokens/token[@id='" + startid + "']")
        endToken = targetSentence.find("tokens/token[@id='" + endid + "']")

        text = representativeMention.find('text').text

        startword = startToken.find('word')
        startword.text = '「{}({}'.format(text, startword.text)
        endword = endToken.find('word')
        endword.text = endword.text + ')」'

    def replaceAll(self):
        for cf in self.enumCoreference():
            rm = cf.find("mention[@representative='true']")
            for m in cf.findall('mention'):
                if 'representative' in m.attrib:
                self.replaceMention(m, rm)

    def writeText(self):
        with open('result56.txt', 'w', encoding='utf8') as w:
            prev = ''
            for e in self.sentences.findall('sentence/tokens/token'):
                word = e.find('word').text
                if word == '-LRB-':
                    word = '('
                elif word == '-RRB-':
                    word = ')'
                if word == '.':
                    w.write(word + '\n')
                elif word == ',' or word == '?' or word == '\'' or word == ')':
                elif word == '(':
                    prev = word
                    if prev == '(':
                        w.write(' (' + word)
                        w.write(' ' + word)
                    prev = ''

def main():
    ca = CoreferenceAnalyser('nlp.txt.xml')

if __name__ == '__main__':

■ 結果
 Natural language processing.
 From Wikipedia, the free encyclopedia.
 Natural language processing (NLP) is a field of computer science, artificial intelligence, and linguistics concerned with the interactions between computers and human (natural) languages.
 As such, NLP is related to the area of humani-computer interaction.
 Many challenges in NLP involve natural language understanding, that is, enabling 「computers(computers)」 to derive meaning from human or natural language input, and others involve natural language generation.
 The history of NLP generally starts in the 1950s, although work can be found from earlier periods.
 In 1950, Alan Turing published an article titled `` Computing Machinery and Intelligence '' which proposed what is now called the 「Alan Turing(Turing)」 test as a criterion of intelligence.
 The Georgetown experiment in 1954 involved fully automatic translation of more than sixty Russian sentences into English.
 The authors claimed that within three or five years, 「a solved problem(machine translation)」 would be a solved problem.
 However, real progress was much slower, and after the ALPAC report in 1966, which found that ten year long research had failed to fulfill the expectations, funding for machine translation was dramatically reduced.
 Little further research in 「a solved problem(machine translation)」 was conducted until the late 1980s, when the first statistical machine translation systems were developed.
 Some notably successful NLP systems developed in the 1960s were SHRDLU, 「SHRDLU(a natural language system working in restricted `` blocks worlds '' with restricted vocabularies)」, and ELIZA, a simulation of a Rogerian psychotherapist, written by Joseph Weizenbaum between 1964 to 1966.
 Using almost no information about human thought or emotion, ELIZA sometimes provided a startlingly human-like interaction.
 When the `` patient '' exceeded the very small knowledge base, 「ELIZA(ELIZA)」 might provide a generic response, for example, responding to `` 「the `` patient ''(My)」 head hurts '' with `` Why do you say 「you(「My head(your)」 head)」 hurts? ''.
 During the 1970s many programmers began to write ` conceptual ontologies', which structured real-world information into computer-understandable data.
 Examples are MARGIE (Schank, 1975), SAM (Cullingford, 1978), PAM (Wilensky, 「1978(1978)」), TaleSpin (Meehan, 1976), QUALM (Lehnert, 1977), Politics (Carbonell, 1979), and Plot Units (「Lehnert(Lehnert 1981)」).
 During this time, many chatterbots were written including PARRY, Racter, and Jabberwacky.
 Up to 「the late 1980s(the 1980s)」, most 「NLP(NLP)」 systems were based on complex sets of hand-written rules.
 Starting in 「the late 1980s(the late 1980s)」, however, there was a revolution in NLP with the introduction of machine learning algorithms for language processing.
 This was due to both the steady increase in computational power resulting from Moore 's Law and the gradual lessening of the dominance of Chomskyan theories of linguistics (e.g. transformational grammar), whose theoretical underpinnings discouraged the sort of corpus linguistics that underlies the machine-learning approach to 「language processing(language processing)」.
 Some of the earliest-used machine learning 「machine learning algorithms for language processing(algorithms)」, such as decision trees, produced systems of hard if-then rules similar to existing hand-written rules.
 However, Part of speech tagging introduced the use of Hidden Markov Models to 「NLP(NLP)」, and increasingly, research has focused on 「statistical models(statistical models, which make soft, probabilistic decisions based on attaching real-valued weights to the features making up the input data)」.
 The cache language models upon which many speech recognition systems now rely are 「The cache language models upon which many speech recognition systems now rely(examples of such statistical models)」.
 Such models are generally more robust when given unfamiliar input, especially 「as input(input that contains errors (as is very common for real-world data -RRB-)」, and produce more reliable results when integrated into a larger system comprising multiple subtasks.
 Many of the notable early successes occurred in the field of 「a solved problem(「a solved problem(machine translation)」, due especially to work at IBM Research, where successively more complicated statistical models were developed)」.
 「many speech recognition systems(These systems)」 were able to take 「the advantage(advantage of existing multilingual textual corpora that had been produced by the Parliament of Canada and the European Union as a result of laws calling for the translation of all governmental proceedings into all official languages of the corresponding systems of government)」.
 However, most other systems depended on corpora specifically developed for the tasks implemented by 「many speech recognition systems(these systems)」, which was (and often continues to be) a major limitation in the success of 「many speech recognition systems(these systems)」.
 As a result, a great deal of research has gone into methods of more effectively learning from limited amounts of data.
 Recent research has increasingly focused on unsupervised and semi-supervised learning algorithms.
 Such algorithms are able to learn from 「data(data that has not been hand-annotated with the desired answers)」, or using a combination of annotated and non-annotated data.
 Generally, this task is much more difficult than supervised learning, and typically produces less accurate results for a given amount of input data.
 However, there is an enormous amount of non-annotated data available (including, among other things, the entire content of the World Wide Web), which can often make up for the inferior results.
 NLP using machine learning.
 Modern NLP algorithms are based on 「machine learning(「machine learning(machine learning)」, especially statistical machine learning)」.
 The paradigm of 「machine learning(machine learning)」 is different from that of most prior attempts at 「language processing(language processing)」.
 Prior implementations of language-processing tasks typically involved the direct hand coding of large sets of 「hard if-then rules similar to existing hand-written rules(rules)」.
 The machine-learning paradigm calls instead for using general learning algorithms - often, although not always, grounded in statistical inference - to automatically learn such rules through the analysis of large corpora of typical real-world examples.
 A corpus (plural, 「existing multilingual textual corpora that had been produced by the Parliament of Canada and the European Union as a result of laws calling for the translation of all governmental proceedings into all official languages of the corresponding systems of government(`` corpora '')」) is 「A corpus -LRB- plural , `` corpora '' -RRB-(a set of documents (or sometimes, individual sentences) that have been hand-annotated with the correct values to be learned)」.
 Many different classes of 「machine learning algorithms for language processing(machine learning algorithms)」 have been applied to NLP tasks.
 「machine learning algorithms for language processing(These algorithms)」 take as input a large set of `` features '' that are generated from 「the input data(the input data)」.
 Some of the earliest-used algorithms, such as 「decision trees(decision trees)」, produced systems of hard if-then rules similar to the systems of 「hand-written rules(hand-written rules)」 that were then common.
 Increasingly, however, research has focused on 「statistical models(「statistical models(statistical models)」, which make 「soft , probabilistic decisions(soft, probabilistic decisions)」 based on attaching 「real-valued weights(real-valued weights)」 to each input feature)」.
 Such models have the advantage that 「Some of the earliest-used algorithms , such as decision trees(they)」 can express the relative certainty of many different possible answers rather than only one, producing more reliable results when such a model is included as a component of a larger system.
 Systems based on machine-learning algorithms have many advantages over hand-produced rules : The learning procedures used during 「machine learning(machine learning)」 automatically focus on the most common cases, whereas when writing 「hard if-then rules similar to existing hand-written rules(rules)」 by hand it is often not obvious at all where the effort should be directed.
 Automatic learning 「The learning procedures used during machine learning(procedures)」 can make use of statistical inference algorithms to produce models that are robust to unfamiliar input (e.g. containing words or structures that have not been seen before) and to erroneous input (e.g. with misspelled words or words accidentally omitted).
 Generally, handling such input gracefully with 「hand-written rules(hand-written rules)」 -- or more generally, creating systems of 「hand-written rules(hand-written rules)」 that make soft decisions -- extremely difficult, error-prone and time-consuming.
 Systems based on automatically learning the rules can be made more accurate simply by supplying more input data.
 However, 「the systems(systems based on 「hand-written rules(hand-written rules)」)」 can only be made more accurate by increasing the complexity of 「the rules(「the rules(the rules)」, which is a much more difficult task)」.
 In particular, there is a limit to the complexity of systems based on hand-crafted rules, beyond which the systems become more and more unmanageable.
 However, creating more data to input to 「Systems based on machine-learning algorithms(machine-learning systems)」 simply requires a corresponding increase in the number of man-hours worked, generally without significant increases in the complexity of the annotation process.
 The subfield of NLP devoted to learning approaches is known as Natural Language Learning (NLL) and 「Natural Language Learning -LRB- NLL -RRB-(its)」 conference CoNLL and peak body SIGNLL are sponsored by ACL, recognizing also their links with Computational Linguistics and Language Acquisition.
 When the aims of computational language learning research is to understand more about human language acquisition, or psycholinguistics, NLL overlaps into the related field of Computational Psycholinguistics.