ó <æCVc@sddlmZddlZddlZddlmZddlmZeje ƒZ de fd„ƒYZ de fd„ƒYZ d e fd „ƒYZd e fd „ƒYZd e fd„ƒYZd„Zd„Zd„Zd„Ze dkr’eƒndS(i’’’’(tprint_functionN(txrange(tDependencyGraphtDependencyScorerIcBs)eZdZd„Zd„Zd„ZRS(sÅ A scorer for calculated the weights on the edges of a weighted dependency graph. This is used by a ``ProbabilisticNonprojectiveParser`` to initialize the edge weights of a ``DependencyGraph``. While typically this would be done by training a binary classifier, any class that can return a multidimensional list representation of the edge weights can implement this interface. As such, it has no necessary fields. cCs"|jtkrtdƒ‚ndS(Ns*DependencyScorerI is an abstract interface(t __class__Rt TypeError(tself((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyt__init__%scCs tƒ‚dS(s :type graphs: list(DependencyGraph) :param graphs: A list of dependency graphs to train the scorer. Typically the edges present in the graphs can be used as positive training examples, and the edges not present as negative examples. N(tNotImplementedError(Rtgraphs((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyttrain)scCs tƒ‚dS(sJ :type graph: DependencyGraph :param graph: A dependency graph whose set of edges need to be scored. :rtype: A three-dimensional list of numbers. :return: The score is returned in a multidimensional(3) list, such that the outer-dimension refers to the head, and the inner-dimension refers to the dependencies. For instance, scores[0][1] would reference the list of scores corresponding to arcs from node 0 to node 1. The node's 'address' field can be used to determine its number identification. For further illustration, a score list corresponding to Fig.2 of Keith Hall's 'K-best Spanning Tree Parsing' paper: scores = [[[], [5], [1], [1]], [[], [], [11], [4]], [[], [10], [], [5]], [[], [8], [8], []]] When used in conjunction with a MaxEntClassifier, each score would correspond to the confidence of a particular edge being classified with the positive training examples. N(R(Rtgraph((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pytscore3s(t__name__t __module__t__doc__RR R (((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyRs   tNaiveBayesDependencyScorercBs)eZdZd„Zd„Zd„ZRS(s† A dependency scorer built around a MaxEnt classifier. In this particular class that classifier is a ``NaiveBayesClassifier``. It uses head-word, head-tag, child-word, and child-tag features for classification. >>> from nltk.parse.dependencygraph import DependencyGraph, conll_data2 >>> graphs = [DependencyGraph(entry) for entry in conll_data2.split('\n\n') if entry] >>> npp = ProbabilisticNonprojectiveParser() >>> npp.train(graphs, NaiveBayesDependencyScorer()) >>> parses = npp.parse(['Cathy', 'zag', 'hen', 'zwaaien', '.'], ['N', 'V', 'Pron', 'Adj', 'N', 'Punc']) >>> len(list(parses)) 1 cCsdS(N((R((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyRcsc CsŌddlm}g}x„|D]}x”|jjƒD]ƒ}xz|jjƒD]i\}}||dkrnd}nd}|jtd|dd|d d |dd |d ƒ|fƒqIWq3WqW|j|ƒ|_d S( ss Trains a ``NaiveBayesClassifier`` using the edges present in graphs list as positive examples, the edges not present as negative examples. Uses a feature vector of head-word, head-tag, child-word, and child-tag. :type graphs: list(DependencyGraph) :param graphs: A list of dependency graphs to train the scorer. i’’’’(tNaiveBayesClassifiertdepstTtFtatwordtbttagtctdN( t nltk.classifyRtnodestvaluestitemstappendtdictR t classifier( RR Rtlabeled_examplesR t head_nodet child_indext child_nodetlabel((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR fs       c Cs+g}xi|jjƒD]X}xO|jjƒD]>}|jtd|dd|dd|dd|dƒƒq,WqWg}g}d}x |jj|ƒD]Œ}tjd|jd ƒ|jd ƒƒ|jt j |jd ƒd ƒgƒ|d 7}|t |jƒkr—|j|ƒg}d}q—q—W|S( sĆ Converts the graph into a feature-based representation of each edge, and then assigns a score to each based on the confidence of the classifier in assigning it to the positive label. Scores are returned in a multidimensional list. :type graph: DependencyGraph :param graph: A dependency graph to score. :rtype: 3 dimensional list :return: Edge scores for the graph parameter. RRRRRRis %.4f %.4fRRg•dyįż„=i( RRRR R!tprob_classify_manytloggertdebugtprobtmathtlogtlen( RR tedgesR#R%t edge_scorestrowtcounttpdist((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR Šs*    %&   (R RRRR R (((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyRQs  $t DemoScorercBseZd„Zd„ZRS(cCstdƒdS(Ns Training...(tprint(RR ((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR ŗscCs[gdgdgdggggdgdgggdggdgggdgdggggS(Niii ii i((RR ((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR ½s(R RR R (((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR3¹s t ProbabilisticNonprojectiveParsercBsheZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z RS( s A probabilistic non-projective dependency parser. Nonprojective dependencies allows for "crossing branches" in the parse tree which is necessary for representing particular linguistic phenomena, or even typical parses in some languages. This parser follows the MST parsing algorithm, outlined in McDonald(2005), which likens the search for the best non-projective parse to finding the maximum spanning tree in a weighted directed graph. >>> class Scorer(DependencyScorerI): ... def train(self, graphs): ... pass ... ... def score(self, graph): ... return [ ... [[], [5], [1], [1]], ... [[], [], [11], [4]], ... [[], [10], [], [5]], ... [[], [8], [8], []], ... ] >>> npp = ProbabilisticNonprojectiveParser() >>> npp.train([], Scorer()) >>> parses = npp.parse(['v1', 'v2', 'v3'], [None, None, None]) >>> len(list(parses)) 1 Rule based example ------------------ >>> from nltk.grammar import DependencyGrammar >>> grammar = DependencyGrammar.fromstring(''' ... 'taught' -> 'play' | 'man' ... 'man' -> 'the' | 'in' ... 'in' -> 'corner' ... 'corner' -> 'the' ... 'play' -> 'golf' | 'dachshund' | 'to' ... 'dachshund' -> 'his' ... ''') >>> ndp = NonprojectiveDependencyParser(grammar) >>> parses = ndp.parse(['the', 'man', 'in', 'the', 'corner', 'taught', 'his', 'dachshund', 'to', 'play', 'golf']) >>> len(list(parses)) 4 cCstjdƒdS(s6 Creates a new non-projective parser. s#initializing prob. nonprojective...N(tloggingR)(R((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyRūscCs||_|jj|ƒdS(s Trains a ``DependencyScorerI`` from a set of ``DependencyGraph`` objects, and establishes this as the parser's scorer. This is used to initialize the scores on a ``DependencyGraph`` during the parsing procedure. :type graphs: list(DependencyGraph) :param graphs: A list of dependency graphs to train the scorer. :type dependency_scorer: DependencyScorerI :param dependency_scorer: A scorer which implements the ``DependencyScorerI`` interface. N(t_scorerR (RR tdependency_scorer((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR s cCs|jj|ƒ|_dS(s( Assigns a score to every edge in the ``DependencyGraph`` graph. These scores are generated via the parser's scorer which was assigned during the training process. :type graph: DependencyGraph :param graph: A dependency graph to assign scores to. N(R7R tscores(RR ((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pytinitialize_edge_scoress cCsPtjdƒx|D]}|j|ƒqW|j|ƒ|j||dƒdS(sL Takes a list of nodes that have been identified to belong to a cycle, and collapses them into on larger node. The arcs of all nodes in the graph must be updated to account for this. :type new_node: Node. :param new_node: A Node (Dictionary) to collapse the cycle nodes into. :type cycle_path: A list of integers. :param cycle_path: A list of node addresses, each of which is in the cycle. :type g_graph, b_graph, c_graph: DependencyGraph :param g_graph, b_graph, c_graph: Graphs which need to be updated. sCollapsing nodes...taddressN(R(R)tremove_by_addresstadd_nodet redirect_arcs(Rtnew_nodet cycle_pathtg_graphtb_graphtc_graphtcycle_node_index((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pytcollapse_nodess   c CsÅtjd|ƒ|j|ƒ}tjd|ƒtjd|jƒxłt|jƒD]č\}}xŁt|j|ƒD]Ä\}}tj|j||ƒ||krr||krr|j||rr|j||ƒ}tjd|j|||ƒg}x*|j||D]} |j| |ƒqW||j|| %stTEMPtNONEs g_graph: %ss b_graph: %ss c_graph: %ss Betas: %ssreplaced nodes %ssFinal scores: %ssRecovering parse...RsDone.N(RSRRGRtupdatet connect_graphR:R(R)R9RR-tpoptget_by_addressRdRftadd_arctcontains_cycleR=RPREtinsertR<R^(RttokensttagsRAtindexttokentoriginal_graphRBRCtvertextunvisited_verticest nr_verticestbetastcurrent_vertext current_nodet best_in_edget new_vertexR@R?t cycle_indextcycle_node_addressRItnode((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pytparseµsž          &         $ $ ( R RRRR R:RERPRFRHRdRfR‚(((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyR5És1    *    tNonprojectiveDependencyParsercBs eZdZd„Zd„ZRS(su A non-projective, rule-based, dependency parser. This parser will return the set of all possible non-projective parses based on the word-to-word relations defined in the parser's dependency grammar, and will allow the branches of the parse tree to cross in order to capture a variety of linguistic phenomena that a projective parser will not. cCs ||_dS(sæ Creates a new ``NonprojectiveDependencyParser``. :param dependency_grammar: a grammar of word-to-word relations. :type dependency_grammar: DependencyGrammar N(t_grammar(Rtdependency_grammar((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyRUsccstƒ|_xFt|ƒD]8\}}i|d6gd6dd6|d6|jj| 'play' | 'man' 'man' -> 'the' | 'in' 'in' -> 'corner' 'corner' -> 'the' 'play' -> 'golf' | 'dachshund' | 'to' 'dachshund' -> 'his' tthetmantintcornerttaughtthist dachshundttotplaytgolfsGraphs:(t nltk.grammarR²t fromstringR4RƒR‚(R²tgrammartndpR R ((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyRœüs   0  t__main__(t __future__RR+R6t nltk.compatRRÆRt getLoggerR R(tobjectRRR3R5RƒRR£R›Rœ(((sz/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/nonprojectivedependencyparser.pyt s"  8h’ƒ˜