Skip to main content

Compute distance between all nodes of a tree, and estimate an histogram that can be used as features for other models.

Project description

PyPI version PyPi downloads DOI

node-distance: Tree node distances as features

Compute distance between all nodes of a tree, and estimate an histogram that can be used as features for other models.

Toy Text Corpus

corpus = "Als Ada Lovelace auf einem Ball den Mathematiker Charles Babbage traf, der sie einlud, die von ihm erfundene „Differenzmaschine“ anzusehen, war sie hellauf begeistert. Die Maschine konnte selbstständig addieren und subtrahieren, doch Ada war klar, dass die Möglichkeiten damit noch lange nicht erschöpft waren. Sie träumte davon, dass eine solche Maschine eines Tages sogar Musik abspielen könnte, und ersann so die Idee eines modernen Computers. 1845 legte sie den ersten Algorithmus zur maschinellen Berechnung der Bernoulli-Zahlen vor und wird daher von vielen als erste Computerprogrammiererin der Welt gefeiert."

(Source: DWDS, Wort des Tages, "Algorithmus, der", 27.11.2021, URL: https://www.dwds.de/adt )

Extract the graph edges from a dependency tree with SpaCy/Stanza/Trankit

  • We assume that NodeIDs are numbers [1,2,3,...] starting with 1. The NodeIDs are equivalent to the TokenIDs in Conll-U.
  • An graph edge is a tuple (ParentID, NodeID)

Example, SpaCy:

# load the SpaCy model
import de_dep_news_trf
model = de_dep_news_trf.load()
# extract the edges for each sentence
import node_distance as nd
all_edges, num_nodes = nd.extract_edges_from_spacy(corpus, model)

Example, stanza:

# load the stanza model
import stanza
model = stanza.Pipeline(
    lang='de', processors='tokenize,mwt,pos,lemma,depparse',
    tokenize_pretokenized=False)
# extract the edges for each sentence
import node_distance as nd
all_edges, num_nodes = nd.extract_edges_from_stanza(corpus, model)

Example, trankit:

# load the trankit model
import trankit
model = trankit.Pipeline(lang='german', gpu=False, cache_dir='./cache')
# extract the edges for each sentence
import node_distance as nd
all_edges, num_nodes = nd.extract_edges_from_trankit(corpus, model)

num_nodes with the number of tokens/nodes in each sentence. all_edges contains lists of edges for each sentence, e.g.

# Edges of the 3rd sentence
edges = all_edges[2]
# Edge between the 6th token/node and its parent node
edge = edges[6]
parent_id, node_id = edge

Compute Shortest Paths between Nodes

Compute node distances and the corresponding token distances

import node_distance as nd
nodedist, tokendist, indicies = nd.node_token_distances(all_edges, num_nodes, cutoff=25)

Histograms as Features

The Distribution of node distances:

import node_distance as nd
xobs, pdf, _ = nd.nodedist_distribution(nodedist, xmin=1, xmax=12)

import matplotlib.pyplot as plt
plt.bar(xobs, pdf);
plt.title("distribution of node distances");
plt.xlabel("node distance");
plt.ylabel("PDF");
plt.show();

Distribution of token distance vs node distance:

import node_distance as nd
xobs, pdf, _ = nd.tokenvsnode_distribution(tokendist, nodedist, xmin=-5, xmax=15)

import matplotlib.pyplot as plt
plt.bar(xobs, pdf);
plt.title("Distribution of token distance vs node distance");
plt.xlabel("token distance minus node distance");
plt.ylabel("PDF");
plt.show();

Appendix

Installation

The node-distance git repo is available as PyPi package

pip install node-distance
pip install git+ssh://git@github.com/ulf1/node-distance.git

Install a virtual environment

It is recommended to install python packages into a seperate virtual environement. (If your git repo is stored in a folder with whitespaces, then don't use the subfolder .venv. Use an absolute path without whitespaces.)

python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt --no-cache-dir
pip install -r requirements-dev.txt --no-cache-dir
pip install -r requirements-demo.txt --no-cache-dir

The usage example and demo notebooks might require spacy, stanza and trankit to be installed. You should download the pretrained models beforehand, e.g. pretrained models for German:

python -m spacy download de_dep_news_trf
python -c "import stanza; stanza.download(lang='de')"
python -c "import trankit; trankit.Pipeline(lang='german', gpu=False, cache_dir='./cache')"

Python commands

  • Jupyter for the examples: jupyter lab
  • Check syntax: flake8 --ignore=F401 --exclude=$(grep -v '^#' .gitignore | xargs | sed -e 's/ /,/g')
  • Run Unit Tests: PYTHONPATH=. pytest

Publish

python setup.py sdist 
twine upload -r pypi dist/*

Clean up

find . -type f -name "*.pyc" | xargs rm
find . -type d -name "__pycache__" | xargs rm -r
rm -r .pytest_cache
rm -r .venv

Support

Please open an issue for support.

Contributing

Please contribute using Github Flow. Create a branch, add commits, and open a pull request.

Acknowledgements

The "Evidence" project was funded by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) - 433249742 (GU 798/27-1; GE 1119/11-1).

Maintenance

  • till 31.Aug.2023 (v0.1.0) the code repository was maintained within the DFG project 433249742
  • since 01.Sep.2023 (v0.2.0) the code repository is maintained by Ulf Hamster.

Citation

You can cite the following paper if you want to use this repository in your research work.

@inproceedings{hamster-2022-everybody,
    title = "Everybody likes short sentences - A Data Analysis for the Text Complexity {DE} Challenge 2022",
    author = "Hamster, Ulf A.",
    booktitle = "Proceedings of the GermEval 2022 Workshop on Text Complexity Assessment of German Text",
    month = sep,
    year = "2022",
    address = "Potsdam, Germany",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.germeval-1.2",
    pages = "10--14",
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

node-distance-0.2.0.tar.gz (10.5 kB view details)

Uploaded Source

File details

Details for the file node-distance-0.2.0.tar.gz.

File metadata

  • Download URL: node-distance-0.2.0.tar.gz
  • Upload date:
  • Size: 10.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.9.6 requests/2.31.0 setuptools/59.6.0 requests-toolbelt/1.0.0 tqdm/4.65.0 CPython/3.10.6

File hashes

Hashes for node-distance-0.2.0.tar.gz
Algorithm Hash digest
SHA256 a1a271d85f80d590efc34622e9d50903e1d8a3f584dc11f06c1498b84e34c631
MD5 a5fd741232b051c0f97fbdf252e41a6c
BLAKE2b-256 eba0938ff1c9efba446fe32648a6540afab950bcf9f200498d0c11877b05c1c9

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page