---
license: apache-2.0
----
- [1.Differences from knowlm-13b-zhixi](#1differences-from-knowlm-13b-zhixi)
- [2. Information Extraction Template](#2-information-extraction-template)
- [3.Common relationship types](#3common-relationship-types)
- [4.Datasets](#4datasets)
- [5.Convert script](#5convert-script)
- [6.Usage](#6usage)
- [7.Evaluate](#7evaluate)
# 1.Differences from knowlm-13b-zhixi
Compared to zjunlp/knowlm-13b-zhixi, zjunlp/knowlm-13b-ie exhibits slightly stronger practicality in information extraction but with a decrease in its general applicability.
zjunlp/knowlm-13b-ie samples around 10% of the data from Chinese-English information extraction datasets, which then undergo negative sampling. For instance, if dataset A contains labels [a, b, c, d, e, f], we first sample 10% of the data from A. For a given sample 's', it might only contain labels a and b. We randomly add relationships that it doesn't originally have, such as c and d, from the specified list of relation candidates. When encountering these additional relationships, the model might output text similar to 'NAN'.This method equips the model with the ability to generate 'NAN' outputs to a certain extent, enhancing its information extraction capability while weakening its generalization ability.
# 2. Information Extraction Template
The template `template` is used to construct the instruction `instruction` for input to the model. It consists of three parts:
1. Task description
2. List of candidate labels {s_schema} (optional)
3. Structural output format {s_format}
Template with specified list of candidate labels:
```json
NER: "You are an expert specialized in entity extraction. With the candidate entity types list: {s_schema}, please extract possible entities from the input below, outputting NAN if a certain entity does not exist. Respond in the format {s_format}."
RE: "You are an expert in extracting relation triples. With the candidate relation list: {s_schema}, please extract the possible head entities and tail entities from the input below and provide the corresponding relation triples. If a relation does not exist, output NAN. Please answer in the {s_format} format."
EE: "You are a specialist in event extraction. Given the candidate event dictionary: {s_schema}, please extract any possible events from the input below. If an event does not exist, output NAN. Please answer in the format of {s_format}."
EET: "As an event analysis specialist, you need to review the input and determine possible events based on the event type directory: {s_schema}. All answers should be based on the {s_format} format. If the event type does not match, please mark with NAN."
EEA: "You are an expert in event argument extraction. Given the event dictionary: {s_schema1}, and the event type and trigger words: {s_schema2}, please extract possible arguments from the following input. If an event argument does not exist, output NAN. Please respond in the {s_format} format."
```
Template without specifying a list of candidate labels:
```json
NER: "Analyze the text content and extract the clear entities. Present your findings in the {s_format} format, skipping any ambiguous or uncertain parts."
RE: "Please extract all the relation triples from the text and present the results in the format of {s_format}. Ignore those entities that do not conform to the standard relation template."
EE: "Please analyze the following text, extract all identifiable events, and present them in the specified format {s_format}. If certain information does not constitute an event, simply skip it."
EET: "Examine the following text content and extract any events you deem significant. Provide your findings in the {s_format} format."
EEA: "Please extract possible arguments based on the event type and trigger word {s_schema2} from the input below. Answer in the format of {s_format}."
```
Candidate Labels {s_schema}
```json
NER(Ontonotes): ["date", "organization", "person", "geographical social political", "national religious political", "facility", "cardinal", "location", "work of art", ...]
RE(NYT): ["ethnicity", "place lived", "geographic distribution", "company industry", "country of administrative divisions", "administrative division of country", ...]
EE(ACE2005): {"declare bankruptcy": ["organization"], "transfer ownership": ["artifact", "place", "seller", "buyer", "beneficiary"], "marry": ["person", "place"], ...}
EET(GENIA): ["cell type", "cell line", "protein", "RNA", "DNA"]
EEA(ACE2005): {"declare bankruptcy": ["organization"], "transfer ownership": ["artifact", "place", "seller", "buyer", "beneficiary"], "marry": ["person", "place"], ...}
```
Structural Output Format {s_format}
```json
NER: (Entity,Entity Type)
RE: (Subject,Relation,Object)
EE: (Event Trigger,Event Type,Argument1#Argument Role1;Argument2#Argument Role2)
EET: (Event Trigger,Event Type)
EEA: (Event Trigger,Event Type,Argument1#Argument Role1;Argument2#Argument Role2)
```
For a more comprehensive understanding of the templates, please refer to the files [ner_converter.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert/converter/ner_converter.py)、[re_converter.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert/converter/re_converter.py)、[ee_converter.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert/converter/ee_converter.py)、[eet_converter.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert/converter/eet_converter.py)、[eea_converter.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert/converter/eea_converter.py) and [configs](https://github.com/zjunlp/DeepKE/tree/main/example/llm/InstructKGC/configs).
# 3.Common relationship types
```python
wiki_cate_schema_en = {
'Person': ['place of birth', 'date of birth', 'country of citizenship', 'occupation', 'work', 'achievement', 'ancestral home', 'position', 'spouse', 'parent', 'alternative name', 'affiliated organization', 'date of death', 'sibling', 'place of death'],
'Geographic_Location': ['located in', 'alternative name', 'population', 'capital', 'area', 'achievement', 'length', 'width', 'elevation'],
'Building': ['located in', 'alternative name', 'achievement', 'event', 'creation time', 'width', 'length', 'creator', 'height', 'area', 'named after'],
'Works': ['author', 'publication date', 'alternative name', 'country of origin', 'based on', 'cast member', 'publisher', 'achievement', 'performer', 'director', 'producer', 'screenwriter', 'tracklist', 'composer', 'lyricist', 'production company', 'box office', 'publishing platform'],
'Creature': ['distribution', 'parent taxon', 'length', 'main food source', 'alternative name', 'taxon name', 'weight', 'width', 'height'],
'Artificial_Object': ['alternative name', 'brand', 'production date', 'made from material', 'country of origin', 'has use', 'manufacturer', 'discoverer or inventor'],
'Natural_Science': ['alternative name', 'properties', 'composition', 'product', 'has use', 'country of origin', 'discoverer or inventor', 'causes'],
'Organization': ['located in', 'alternative name', 'has subsidiary', 'date of incorporation', 'product', 'achievement', 'member', 'founded by', 'dissolution time', 'event'],
'Transport': ['located in', 'inception', 'connecting line', 'date of official opening', 'pass', 'area', 'alternative name', 'length', 'width', 'achievement', 'class of station'],
'Event': ['participant', 'scene', 'occurrence time', 'alternative name', 'sponsor', 'casualties', 'has cause', 'has effect', 'organizer', 'award received', 'winner'],
'Astronomy': ['alternative name', 'of', 'time of discovery or invention', 'discoverer or inventor', 'name after', 'absolute magnitude', 'diameter', 'mass'],
'Medicine': ['symptoms', 'alternative name', 'affected body part', 'possible consequences', 'etiology']
}
```
Here [schema](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/schema.py) provides 12 text topics and common relationship types under the topic.
# 4.Datasets
| Name | Download | Quantity | Description |
| ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| InstructIE-train | [Google drive](https://drive.google.com/file/d/1VX5buWC9qVeVuudh_mhc_nC7IPPpGchQ/view?usp=drive_link)
[HuggingFace](https://huggingface.co/datasets/zjunlp/KnowLM-IE)
[Baidu Netdisk](https://pan.baidu.com/s/1xXVrjkinw4cyKKFBR8BwQw?pwd=x4s7) | 30w+ | InstructIE train set, which is constructed by weak supervision and may contain some noisy data |
| InstructIE-valid | [Google drive](https://drive.google.com/file/d/1EMvqYnnniKCGEYMLoENE1VD6DrcQ1Hhj/view?usp=drive_link)
[HuggingFace](https://huggingface.co/datasets/zjunlp/KnowLM-IE)
[Baidu Netdisk](https://pan.baidu.com/s/11u_f_JT30W6B5xmUPC3enw?pwd=71ie) | 2000+ | InstructIE validation set |
| InstructIE-test | [Google drive](https://drive.google.com/file/d/1WdG6_ouS-dBjWUXLuROx03hP-1_QY5n4/view?usp=drive_link)
[HuggingFace](https://huggingface.co/datasets/zjunlp/KnowLM-IE)
[Baidu Netdisk](https://pan.baidu.com/s/1JiRiOoyBVOold58zY482TA?pwd=cyr9) | 2000+ | InstructIE test set |
| train.json, valid.json | [Google drive](https://drive.google.com/file/d/1vfD4xgToVbCrFP2q-SD7iuRT2KWubIv9/view?usp=sharing) | 5,000 | Preliminary training set and test set for the task "Instruction-Driven Adaptive Knowledge Graph Construction" in [CCKS2023 Open Knowledge Graph Challenge](https://tianchi.aliyun.com/competition/entrance/532080/introduction), randomly selected from instruct_train.json |
- `InstrumentIE-train` contains two files: `InstrumentIE-zh.json` and `InstrumentIE-en.json`, each of which contains the following fields: `'id'` (unique identifier), `'cate'` (text category), `'entity'` and `'relation'` (triples) fields. The extracted instructions and output can be freely constructed through `'entity'` and `'relation'`.
- `InstrumentIE-valid` and `InstrumentIE-test` are validation sets and test sets, respectively, including bilingual `zh` and `en`.
- `train.json`: Same fields as `KnowLM-IE.json`, `'instruction'` and `'output'` have only one format, and extraction instructions and outputs can also be freely constructed through `'relation'`.
- `valid.json`: Same fields as `train.json`, but with more accurate annotations achieved through crowdsour
Explanation of each field
| Field | Description |
| :---------: | :----------------------------------------------------------: |
| id | Unique identifier |
| cate | text topic of input (12 topics in total) |
| input | Model input text (need to extract all triples involved within) |
| instruction | Instruction for the model to perform the extraction task |
| output | Expected model output |
| entity | entities(entity, entity_type) |
| relation | Relation triples(head, relation, tail) involved in the input |
Example of data
```json
{
"id": "6e4f87f7f92b1b9bd5cb3d2c3f2cbbc364caaed30940a1f8b7b48b04e64ec403",
"cate": "Person",
"input": "Dionisio Pérez Gutiérrez (born 1872 in Grazalema (Cádiz) - died 23 February 1935 in Madrid) was a Spanish writer, journalist, and gastronome. He has been called \"one of Spain's most authoritative food writers\" and was an early adopter of the term Hispanidad.\nHis pen name, \"Post-Thebussem\", was chosen as a show of support for Mariano Pardo de Figueroa, who went by the handle \"Dr. Thebussem\".",
"entity": [
{"entity": "Dionisio Pérez Gutiérrez", "entity_type": "human"},
{"entity": "Post-Thebussem", "entity_type": "human"},
{"entity": "Grazalema", "entity_type": "geographic_region"},
{"entity": "Cádiz", "entity_type": "geographic_region"},
{"entity": "Madrid", "entity_type": "geographic_region"},
{"entity": "gastronome", "entity_type": "event"},
{"entity": "Spain", "entity_type": "geographic_region"},
{"entity": "Hispanidad", "entity_type": "architectural_structure"},
{"entity": "Mariano Pardo de Figueroa", "entity_type": "human"},
{"entity": "23 February 1935", "entity_type": "time"}
],
"relation": [
{"head": "Dionisio Pérez Gutiérrez", "relation": "country of citizenship", "tail": "Spain"},
{"head": "Dionisio Pérez Gutiérrez", "relation": "place of birth", "tail":"Grazalema"},
{"head": "Dionisio Pérez Gutiérrez", "relation": "place of death", "tail": "Madrid"},
{"head": "Mariano Pardo de Figueroa", "relation": "country of citizenship", "tail": "Spain"},
{"head": "Dionisio Pérez Gutiérrez", "relation": "alternative name", "tail": "Post-Thebussem"},
{"head": "Dionisio Pérez Gutiérrez", "relation": "date of death", "tail": "23 February 1935"}
]
}
```
# 5.Convert script
**Training Data Transformation**
Before inputting data into the model, it needs to be formatted to include `instruction` and `input` fields. To assist with this, we offer a script [kg2instruction/convert.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert.py), which can batch convert data into a format directly usable by the model.
> Before using the [kg2instruction/convert.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert.py) script, please ensure you have referred to the [data](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/data) directory. Please consult `sample.json` to understand the format of the data before conversion, `schema.json` illustrates the organization of the schema, and `processed.json` describes the format of the data after conversion.
```bash
python kg2instruction/convert.py \
--src_path data/NER/sample.json \
--tgt_path data/NER/processed.json \
--schema_path data/NER/schema.json \
--language zh \ # Specifies the language for the conversion script and template, options are ['zh', 'en']
--task NER \ # Specifies the task type: one of ['RE', 'NER', 'EE', 'EET', 'EEA']
--sample -1 \ # If -1, randomly samples one of 20 instruction and 4 output formats; if a specific number, uses the corresponding instruction format, range is -1<=sample<20
--neg_ratio 1 \ # Sets the negative sampling ratio for all samples
--neg_schema 1 \ # Sets the negative sampling ratio from the schema
--random_sort # Determines whether to randomly sort the list of schemas in the instruction
```
**Negative Sampling**: Assuming dataset A contains labels [a, b, c, d, e, f], for a given sample s, it might involve only labels a and b. Our objective is to randomly introduce some relationships from the candidate relationship list that were originally unrelated to s, such as c and d. However, it's worth noting that in the output, the labels for c and d either won't be included, or they will be output as `NAN`.
The `schema_path` specifies the path to a schema file (a JSON file). The schema file consists of three lines of JSON strings, organized in a fixed format. Taking Named Entity Recognition (NER) as an example, the meanings of each line are as follows:
```
["BookTitle", "Address", "Movie", ...] # List of entity types
[] # Empty list
{} # Empty dictionary
```
More
```
For Relation Extraction (RE) tasks:
[] # Empty list
["Founder", "Number", "RegisteredCapital", ...] # List of relation types
{} # Empty dictionary
For Event Extraction (EE) tasks:
["Social Interaction-Thanks", "Organizational Action-OpeningCeremony", "Competition Action-Withdrawal", ...] # List of event types
["DismissingParty", "TerminatingParty", "Reporter", "ArrestedPerson"] # List of argument roles
{"OrganizationalRelation-Layoff": ["LayoffParty", "NumberLaidOff", "Time"], "LegalAction-Sue": ["Plaintiff", "Defendant", "Time"], ...} # Dictionary of event types
For EET tasks:
["Social Interaction-Thanks", "Organizational Action-OpeningCeremony", "Competition Action-Withdrawal", ...] # List of event types
[] # Empty list
{} # Empty dictionary
For Event Extraction with Arguments (EEA) tasks:
["Social Interaction-Thanks", "Organizational Action-OpeningCeremony", "Competition Action-Withdrawal", ...] # List of event types
["DismissingParty", "TerminatingParty", "Reporter", "ArrestedPerson"] # List of argument roles
{"OrganizationalRelation-Layoff": ["LayoffParty", "NumberLaidOff", "Time"], "LegalAction-Sue": ["Plaintiff", "Defendant", "Time"], ...} # Dictionary of event types
```
For more detailed information on the schema file, you can refer to the `schema.json` file in the respective task directories under the [data](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/data) directory.
**Testing Data Transformation**
For test data, you can use the [kg2instruction/convert_test.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/convert_test.py) script, which does not require the data to contain label fields (`entity`, `relation`, `event`), just the input field and the corresponding schema_path.
```bash
python kg2instruction/convert_test.py \
--src_path data/NER/sample.json \
--tgt_path data/NER/processed.json \
--schema_path data/NER/schema.json \
--language zh \
--task NER \
--sample 0
```
**Data Transformation Examples**
Here is an example of data conversion for Named Entity Recognition (NER) task:
```json
Before Transformation:
{
"input": "In contrast, the rain-soaked battle between Qingdao Sea Bulls and Guangzhou Songri Team, although also ended in a 0:0 draw, was uneventful.",
"entity": [{"entity": "Guangzhou Songri Team", "entity_type": "Organizational Structure"}, {"entity": "Qingdao Sea Bulls", "entity_type": "Organizational Structure"}]
}
After Transformation:
{
"id": "e88d2b42f8ca14af1b77474fcb18671ed3cacc0c75cf91f63375e966574bd187",
"instruction": "Please identify and list the entity types mentioned in the given text ['Organizational Structure', 'Person', 'Geographical Location']. If a type doesn't exist, please indicate it as NAN. Provide your answer in the format (entity, entity type).",
"input": "In contrast, the rain-soaked battle between Qingdao Sea Bulls and Guangzhou Songri Team, although also ended in a 0:0 draw, was uneventful.",
"output": "(Qingdao Sea Bulls,Organizational Structure)\n(Guangzhou Songri Team,Organizational Structure)\nNAN\nNAN"
}
```
Before conversion, the data format needs to adhere to the structure specified in the `DeepKE/example/llm/InstructKGC/data` directory for each task (such as NER, RE, EE). Taking NER task as an example, the input text should be labeled as the `input` field, and the annotated data should be labeled as the `entity` field, which is a list of dictionaries containing multiple key-value pairs for `entity` and `entity_type`.
After data conversion, you will obtain structured data containing the `input` text, `instruction` (providing detailed instructions about candidate entity types ['Organization', 'Person', 'Location'] and the expected output format), and `output` (listing all entity information recognized in the `input` in the form of (entity, entity type)).
# 6.Usage
We provide a script, [inference.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/src/inference.py), for direct inference using the `zjunlp/knowlm-13b-ie model`. Please refer to the [README.md](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/README.md) for environment configuration and other details.
```bash
CUDA_VISIBLE_DEVICES="0" python src/inference.py \
--model_name_or_path 'models/knowlm-13b-ie' \
--model_name 'llama' \
--input_file 'data/NER/processed.json' \
--output_file 'results/ner_test.json' \
--fp16
```
If GPU memory is not enough, you can use `--bits 8` or `--bits 4`.
# 7.Evaluate
We provide a script at [evaluate.py](https://github.com/zjunlp/DeepKE/blob/main/example/llm/InstructKGC/kg2instruction/evaluate.py) to convert the string output of the model into a list and calculate F1
```bash
python kg2instruction/evaluate.py \
--standard_path data/NER/processed.json \
--submit_path data/NER/processed.json \
--task NER \
--language zh
```