Package: xpotato
POTATO: exPlainable infOrmation exTrAcTion framewOrkPOTATO is a human-in-the-loop XAI framework for extracting and evaluating interpretable graph features for any classification problem in Natural Language Processing.Built systemsTo get started with rule-systems we provide rule-based features prebuilt with POTATO on different datasets (e.g. our paperOffensive text detection on English Twitter with deep learning models and rule-based systemsfor the HASOC2021 shared task). If you are interested in that, you can go underfeatures/for more info!Install and Quick StartCheck out our quick demonstration (~2 min) video about the tool:https://youtu.be/PkQ71wUSeNUThere is a longer version with a detailed method description and presented background research (~1 hour):https://youtu.be/6R_V1WfIjsUSetupThe tool is heavily dependent upon thetuw-nlprepository. You can install tuw-nlp with pip:pip install tuw-nlpThen follow theinstructionsto setup the package.Then install POTATO from pip:pip install xpotatoOr you can install it from source:pip install -e .UsagePOTATO is an IE tool that works on graphs, currently we support three types of graphs: AMR, UD andFourlang.In the README we provide examples with fourlang semantic graphs. Make sure to follow the instructions in thetuw_nlprepo to be able to build fourlang graphs.If you are interested in AMR graphs, you can go to thehasocfolder To get started with rule-systems prebuilt with POTATO on the HASOC dataset (we also presented a paper namedOffensive text detection on English Twitter with deep learning models and rule-based systemsfor the HASOC2021 shared task).We also provide experiments on theCrowdTruthmedical relation extraction datasets with UD graphs, go to thecrowdtruthfolder for more info!POTATO can also handle unlabeled, or partially labeled data, seeadvancedmode to get to know more.To see complete working examples go under thenotebooks/folder to see experiments on HASOC and on the Semeval relation extraction dataset.First import packages from potato:fromxpotato.dataset.datasetimportDatasetfromxpotato.models.trainerimportGraphTrainerFirst we demonstrate POTATO's capabilities with a few sentences manually picked from the dataset.Note that we replaced the two entitites in question withXXXandYYY.sentences=[("Governments and industries in nations around the world are pouring XXX into YYY.","Entity-Destination(e1,e2)"),("The scientists poured XXX into pint YYY.","Entity-Destination(e1,e2)"),("The suspect pushed the XXX into a deep YYY.","Entity-Destination(e1,e2)"),("The Nepalese government sets up a XXX to inquire into the alleged YYY of diplomatic passports.","Other"),("The entity1 to buy papers is pushed into the next entity2.","Entity-Destination(e1,e2)"),("An unnamed XXX was pushed into the YYY.","Entity-Destination(e1,e2)"),("Since then, numerous independent feature XXX have journeyed into YYY.","Other"),("For some reason, the XXX was blinded from his own YYY about the incommensurability of time.","Other"),("Sparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week.","Other"),("Olympics have already poured one XXX into the YYY.","Entity-Destination(e1,e2)"),("After wrapping him in a light blanket, they placed the XXX in the YYY his father had carved for him.","Entity-Destination(e1,e2)"),("I placed the XXX in a natural YYY, at the base of a part of the fallen arch.","Entity-Destination(e1,e2)"),("The XXX was delivered from the YYY of Lincoln Memorial on August 28, 1963 as part of his famous March on Washington.","Other"),("The XXX leaked from every conceivable YYY.","Other"),("The scientists placed the XXX in a tiny YYY which gets channelled into cancer cells, and is then unpacked with a laser impulse.","Entity-Destination(e1,e2)"),("The level surface closest to the MSS, known as the XXX, departs from an YYY by about 100 m in each direction.","Other"),("Gaza XXX recover from three YYY of war.","Other"),("This latest XXX from the animation YYY at Pixar is beautiful, masterly, inspired - and delivers a powerful ecological message.","Other")]Initialize the dataset and also provide a label encoding. Then parse the sentences into graphs. Currently we provide three types of graphs:ud,fourlang,amr. Also provide the language you want to parse, currently we support English (en) and German (de).dataset=Dataset(sentences,label_vocab={"Other":0,"Entity-Destination(e1,e2)":1},lang="en")dataset.set_graphs(dataset.parse_graphs(graph_format="ud"))Check the dataset:df=dataset.to_dataframe()We can also check any of the graphs:Check any of the graphs parsedfromxpotato.models.utilsimportto_dotfromgraphvizimportSourceSource(to_dot(df.iloc[0].graph))RulesIf the dataset is prepared and the graphs are parsed, we can write rules to match labels. We can write rules either manually or extract
them automatically (POTATO also provides a frontend that tries to do both).The simplest rule would be just a node in the graph:# The syntax of the rules is List[List[rules that we want to match], List[rules that shouldn't be in the matched graphs], Label of the rule]rule_to_match=[[["(u_1 / into)"],[],"Entity-Destination(e1,e2)"]]Init the rule matcher:fromxpotato.graph_extractor.extractimportFeatureEvaluatorevaluator=FeatureEvaluator()Match the rules in the dataset:#match single featuredf=dataset.to_dataframe()evaluator.match_features(df,rule_to_match)SentencePredicted labelMatched rule0Governments and industries in nations around the world are pouring XXX into YYY.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']1The scientists poured XXX into pint YYY.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']2The suspect pushed the XXX into a deep YYY.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']3The Nepalese government sets up a XXX to inquire into the alleged YYY of diplomatic passports.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']4The entity1 to buy papers is pushed into the next entity2.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']5An unnamed XXX was pushed into the YYY.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']6Since then, numerous independent feature XXX have journeyed into YYY.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']7For some reason, the XXX was blinded from his own YYY about the incommensurability of time.8Sparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week.9Olympics have already poured one XXX into the YYY.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']10After wrapping him in a light blanket, they placed the XXX in the YYY his father had carved for him.11I placed the XXX in a natural YYY, at the base of a part of the fallen arch.12The XXX was delivered from the YYY of Lincoln Memorial on August 28, 1963 as part of his famous March on Washington.13The XXX leaked from every conceivable YYY.14The scientists placed the XXX in a tiny YYY which gets channelled into cancer cells, and is then unpacked with a laser impulse.Entity-Destination(e1,e2)[['(u_1 / into)'], [], 'Entity-Destination(e1,e2)']15The level surface closest to the MSS, known as the XXX, departs from an YYY by about 100 m in each direction.16Gaza XXX recover from three YYY of war.17This latest XXX from the animation YYY at Pixar is beautiful, masterly, inspired - and delivers a powerful ecological message.You can see in the dataset that the rules only matched the instances where the "into" node was present.One of the core features of our tool is that we are also able to match subgraphs. To describe a graph, we use thePENMANnotation.E.g. the string(u_1 / into :1 (u_3 / pour))would describe a graph with two nodes ("into" and "pour") and a single directed edge with the label "1" between them.#match a simple graph featureevaluator.match_features(df,[[["(u_1 / into :1 (u_2 / pour) :2 (u_3 / YYY))"],[],"Entity-Destination(e1,e2)"]])Describing a subgraph with the string "(u_1 / into :1 (u_2 / pour) :2 (u_3 / YYY))" will return only three examples instead of 9 (when we only had a single node as a feature)SentencePredicted labelMatched rule0Governments and industries in nations around the world are pouring XXX into YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / pour) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']1The scientists poured XXX into pint YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / pour) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']2The suspect pushed the XXX into a deep YYY.3The Nepalese government sets up a XXX to inquire into the alleged YYY of diplomatic passports.4The entity1 to buy papers is pushed into the next entity2.5An unnamed XXX was pushed into the YYY.6Since then, numerous independent feature XXX have journeyed into YYY.7For some reason, the XXX was blinded from his own YYY about the incommensurability of time.8Sparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week.9Olympics have already poured one XXX into the YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / pour) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']10After wrapping him in a light blanket, they placed the XXX in the YYY his father had carved for him.11I placed the XXX in a natural YYY, at the base of a part of the fallen arch.12The XXX was delivered from the YYY of Lincoln Memorial on August 28, 1963 as part of his famous March on Washington.13The XXX leaked from every conceivable YYY.14The scientists placed the XXX in a tiny YYY which gets channelled into cancer cells, and is then unpacked with a laser impulse.15The level surface closest to the MSS, known as the XXX, departs from an YYY by about 100 m in each direction.16Gaza XXX recover from three YYY of war.17This latest XXX from the animation YYY at Pixar is beautiful, masterly, inspired - and delivers a powerful ecological message.We can also add negated features that we don't want to match (e.g. this won't match the first row where 'pour' is present):#match a simple graph featureevaluator.match_features(df,[[["(u_1 / into :2 (u_3 / YYY))"],["(u_2 / pour)"],"Entity-Destination(e1,e2)"]])SentencePredicted labelMatched rule0Governments and industries in nations around the world are pouring XXX into YYY.1The scientists poured XXX into pint YYY.2The suspect pushed the XXX into a deep YYY.Entity-Destination(e1,e2)[['(u_1 / into :2 (u_3 / YYY))'], ['(u_2 / pour)'], 'Entity-Destination(e1,e2)']3The Nepalese government sets up a XXX to inquire into the alleged YYY of diplomatic passports.Entity-Destination(e1,e2)[['(u_1 / into :2 (u_3 / YYY))'], ['(u_2 / pour)'], 'Entity-Destination(e1,e2)']4The entity1 to buy papers is pushed into the next entity2.5An unnamed XXX was pushed into the YYY.Entity-Destination(e1,e2)[['(u_1 / into :2 (u_3 / YYY))'], ['(u_2 / pour)'], 'Entity-Destination(e1,e2)']6Since then, numerous independent feature XXX have journeyed into YYY.Entity-Destination(e1,e2)[['(u_1 / into :2 (u_3 / YYY))'], ['(u_2 / pour)'], 'Entity-Destination(e1,e2)']7For some reason, the XXX was blinded from his own YYY about the incommensurability of time.8Sparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week.9Olympics have already poured one XXX into the YYY.10After wrapping him in a light blanket, they placed the XXX in the YYY his father had carved for him.11I placed the XXX in a natural YYY, at the base of a part of the fallen arch.12The XXX was delivered from the YYY of Lincoln Memorial on August 28, 1963 as part of his famous March on Washington.13The XXX leaked from every conceivable YYY.14The scientists placed the XXX in a tiny YYY which gets channelled into cancer cells, and is then unpacked with a laser impulse.15The level surface closest to the MSS, known as the XXX, departs from an YYY by about 100 m in each direction.16Gaza XXX recover from three YYY of war.17This latest XXX from the animation YYY at Pixar is beautiful, masterly, inspired - and delivers a powerful ecological message.If we don't want to specify nodes, regex can also be used in place of the node and edge-names:#regex can be used to match any node (this will match instances where 'into' is connected to any node with '1' edge)evaluator.match_features(df,[[["(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))"],[],"Entity-Destination(e1,e2)"]])SentencePredicted labelMatched rule0Governments and industries in nations around the world are pouring XXX into YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']1The scientists poured XXX into pint YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']2The suspect pushed the XXX into a deep YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']3The Nepalese government sets up a XXX to inquire into the alleged YYY of diplomatic passports.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']4The entity1 to buy papers is pushed into the next entity2.5An unnamed XXX was pushed into the YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']6Since then, numerous independent feature XXX have journeyed into YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']7For some reason, the XXX was blinded from his own YYY about the incommensurability of time.8Sparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week.9Olympics have already poured one XXX into the YYY.Entity-Destination(e1,e2)[['(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))'], [], 'Entity-Destination(e1,e2)']10After wrapping him in a light blanket, they placed the XXX in the YYY his father had carved for him.11I placed the XXX in a natural YYY, at the base of a part of the fallen arch.12The XXX was delivered from the YYY of Lincoln Memorial on August 28, 1963 as part of his famous March on Washington.13The XXX leaked from every conceivable YYY.14The scientists placed the XXX in a tiny YYY which gets channelled into cancer cells, and is then unpacked with a laser impulse.15The level surface closest to the MSS, known as the XXX, departs from an YYY by about 100 m in each direction.16Gaza XXX recover from three YYY of war.17This latest XXX from the animation YYY at Pixar is beautiful, masterly, inspired - and delivers a powerful ecological message.We can also train regex rules from a training data, this will automatically replace regex '.*' with nodes that are
'good enough' statistically based on the provided dataframe.evaluator.train_feature("Entity-Destination(e1,e2)","(u_1 / into :1 (u_2 / .*) :2 (u_3 / YYY))",df)This returns '(u_1 / into :1 (u_2 / push|pour) :2 (u_3 / YYY))' (replaced '.*' withpushandpour)Learning rulesTo extract rules automatically, train the dataset with graph features and rank them based on relevancy:df=dataset.to_dataframe()trainer=GraphTrainer(df)#extract featuresfeatures=trainer.prepare_and_train()fromxpotato.dataset.utilsimportsave_dataframefromsklearn.model_selectionimporttrain_test_splittrain,val=train_test_split(df,test_size=0.2,random_state=1234)#save train and validation, this is important for the frontend to worksave_dataframe(train,'train.tsv')save_dataframe(val,'val.tsv')importjson#also save the ranked featureswithopen("features.json","w+")asf:json.dump(features,f)You can also save the parsed graphs for evaluation or for caching:importpicklewithopen("graphs.pickle","wb")asf:pickle.dump(val.graph,f)FrontendIf the DataFrame is ready with the parsed graphs, the UI can be started to inspect the extracted rules and modify them. The frontend is a streamlit app, the simplest way of starting it is (the training and the validation dataset must be provided):streamlit run frontend/app.py -- -t notebooks/train.tsv -v notebooks/val.tsv -g udit can be also started with the extracted features:streamlit run frontend/app.py -- -t notebooks/train.tsv -v notebooks/val.tsv -g ud -sr notebooks/features.jsonif you already used the UI and extracted the features manually and you want to load it, you can run:streamlit run frontend/app.py -- -t notebooks/train.tsv -v notebooks/val.tsv -g ud -sr notebooks/features.json -hr notebooks/manual_features.jsonAdvanced modeIf labels are not or just partially provided, the frontend can be started also inadvancedmode, where the user canannotatea few examples at the start, then the system gradually offers rules based on the provided examples.Dataset without labels can be initialized with:sentences=[("Governments and industries in nations around the world are pouring XXX into YYY.",""),("The scientists poured XXX into pint YYY.",""),("The suspect pushed the XXX into a deep YYY.",""),("The Nepalese government sets up a XXX to inquire into the alleged YYY of diplomatic passports.",""),("The entity1 to buy papers is pushed into the next entity2.",""),("An unnamed XXX was pushed into the YYY.",""),("Since then, numerous independent feature XXX have journeyed into YYY.",""),("For some reason, the XXX was blinded from his own YYY about the incommensurability of time.",""),("Sparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week.",""),("Olympics have already poured one XXX into the YYY.",""),("After wrapping him in a light blanket, they placed the XXX in the YYY his father had carved for him.",""),("I placed the XXX in a natural YYY, at the base of a part of the fallen arch.",""),("The XXX was delivered from the YYY of Lincoln Memorial on August 28, 1963 as part of his famous March on Washington.",""),("The XXX leaked from every conceivable YYY.",""),("The scientists placed the XXX in a tiny YYY which gets channelled into cancer cells, and is then unpacked with a laser impulse.",""),("The level surface closest to the MSS, known as the XXX, departs from an YYY by about 100 m in each direction.",""),("Gaza XXX recover from three YYY of war.",""),("This latest XXX from the animation YYY at Pixar is beautiful, masterly, inspired - and delivers a powerful ecological message.","")]Then, the frontend can be started:streamlit run frontend/app.py -- -t notebooks/unsupervised_dataset.tsv -g ud -m advancedOnce the frontend starts up and you define the labels, you are faced with the annotation interface. You can search elements by clicking on the appropriate column name and applying the desired filter. You can annotate instances by checking the checkbox at the beginning of the line. You can check multiple checkboxs at a time. Once you've selected the utterances you want to annotate, click on theAnnotatebutton. The annotated samples will appear in the lower table. You can clear the annotation of certain elements by selecting them in the second table and clickingClear annotation.Once you have some annotated data, you can train rules by clicking theTrain!button. It is recommended to set theRank features based on accuracyto True, if you have just a few samples. You will get a similar interface as in supervised mode, you can generate rule suggestions, and write your own rules as usual. Once you are satisfied with the rules, select each of them and clickannotate based on selected. This process might take a while if you are working with large data. You should get all the rule matches marked in the first and the second tables. You can order the tables by each column, so it's easier to check. You will have to manually accept the annotations generated this way for them to appear in the second table.You can read about the use of the advanced mode in thedocsEvaluateIf you have the features ready and you want to evaluate them on a test set, you can run:pythonscripts/evaluate.py-tud-fnotebooks/features.json-dnotebooks/val.tsvThe result will be acsvfile with the labels and the matched rules.ServiceIf you are ready with the extracted features and want to use our package in production for inference (generating predictions for sentences), we also provide a REST API built on POTATO (based onfastapi).First install FastAPI andUvicornpipinstallfastapi
pipinstall"uvicorn[standard]"To start the service, you should setlanguage,graph_typeand thefeaturesfor the service. This can be done through enviroment variables.Example:exportFEATURE_PATH=/home/adaamko/projects/POTATO/features/semeval/test_features.jsonexportGRAPH_FORMAT=udexportLANG=enThen, start the REST API:pythonservices/main.pyIt will start a service running onlocalhoston port8000(it will also initialize the correct models).Then you can use any client to make post requests:curl-XPOSTlocalhost:8000-H'Content-Type: application/json'-d'{"text":"The suspect pushed the XXX into a deep YYY.\nSparky Anderson is making progress in his XXX from YYY and could return to managing the Detroit Tigers within a week."}'The answer will be a list with the predicted labels (if none of the rules match, it will return "NONE"):["Entity-Destination(e1,e2)","NONE"]The streamlit frontend also has an inference mode, where the implemented rule-system can be used for inference. It can be started with:streamlitrunfrontend/app.py---hrfeatures/semeval/test_features.json-minferenceContributingWe welcome all contributions! Please fork this repository and create a branch for your modifications. We suggest getting in touch with us first, by opening an issue or by writing an email to Adam Kovacs or Gabor Recski atfirstname.lastname@tuwien.ac.atCitingIf you use the library, please cite ourpaperpublished in CIKM 2022:@inproceedings{Kovacs:2022,author={Kov\'{a}cs, \'{A}d\'{a}m and G\'{e}mes, Kinga and Ikl\'{o}di, Eszter and Recski, G\'{a}bor},title={POTATO: ExPlainable InfOrmation ExTrAcTion FramewOrk},year={2022},isbn={9781450392365},publisher={Association for Computing Machinery},address={New York, NY, USA},url={https://doi.org/10.1145/3511808.3557196},doi={10.1145/3511808.3557196},booktitle={Proceedings of the 31st ACM International Conference on Information & Knowledge Management},pages={4897–4901},numpages={5},keywords={explainability, explainable, hitl},location={Atlanta, GA, USA},series={CIKM '22}}LicenseMIT license