id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
38,503
import argparse import os import random from functools import partial import numpy as np import paddle from model import BiLSTMAttentionModel, SelfInteractiveAttention from utils import CharTokenizer, convert_example from paddlenlp.data import Pad, Stack, Tuple, Vocab from paddlenlp.datasets import load_dataset The pr...
Creats dataloader. Args: dataset(obj:`paddle.io.Dataset`): Dataset instance. trans_fn(obj:`callable`, optional, defaults to `None`): function to convert a data sample to input ids, etc. mode(obj:`str`, optional, defaults to obj:`train`): If mode is 'train', it will shuffle the dataset randomly. batch_size(obj:`int`, op...
38,504
import numpy as np The provided code snippet includes necessary dependencies for implementing the `preprocess_prediction_data` function. Write a Python function `def preprocess_prediction_data(data, tokenizer)` to solve the following problem: It process the prediction data as the format used as training. Args: data (o...
It process the prediction data as the format used as training. Args: data (obj:`List[str]`): The prediction data whose each element is a tokenized text. tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string. Returns: examples (obj:`List(Example)`): The processed data whose each element i...
38,508
import argparse import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_args` function. Write a Python function `def get_args()` to solve the following problem: get args Here is the function: def get_args(): """ get args """ parser = argparse...
get args
38,509
import argparse import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `data_load` function. Write a Python function `def data_load(args)` to solve the following problem: load result data from file Here is the function: def data_load(args): """ load resu...
load result data from file
38,510
import argparse import json import numpy as np The provided code snippet includes necessary dependencies for implementing the `analysis` function. Write a Python function `def analysis(args, instance, gold_list)` to solve the following problem: Analysis result according to result data Here is the function: def analy...
Analysis result according to result data
38,511
import argparse import json import math import os def get_args(): parser = argparse.ArgumentParser("map eval") parser.add_argument("--pred_path", required=True) parser.add_argument("--golden_path", required=True) parser.add_argument("--language", type=str, required=True, help="language that the model i...
null
38,512
import argparse import json import math import os The provided code snippet includes necessary dependencies for implementing the `_calc_MAP_by_bin` function. Write a Python function `def _calc_MAP_by_bin(top_p, length_adv, adv_attriRank_list, ori_attriRank_list)` to solve the following problem: This is our old way to ...
This is our old way to calculate MAP, which follows equation two in consistency section of README
38,513
import argparse import json import math import os def evids_load(args, path): golden_f = open(args.golden_path, "r") golden = {} ins_num = 0 for golden_line in golden_f.readlines(): line = json.loads(golden_line) if line["sample_type"] == "disturb": ins_num += 1 golde...
null
38,514
import argparse import json The provided code snippet includes necessary dependencies for implementing the `get_args` function. Write a Python function `def get_args()` to solve the following problem: get args Here is the function: def get_args(): """ get args """ parser = argparse.ArgumentParser("Ac...
get args
38,515
import argparse import json The provided code snippet includes necessary dependencies for implementing the `load_from_file` function. Write a Python function `def load_from_file(args)` to solve the following problem: load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_...
load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_id, rationales_list}, golden_label: {sent_id, label}, pred_label: {sent_id, label}
38,516
import argparse import json The provided code snippet includes necessary dependencies for implementing the `cal_acc` function. Write a Python function `def cal_acc(golden_label, pred_label)` to solve the following problem: The function actually calculate the accuracy. Here is the function: def cal_acc(golden_label, ...
The function actually calculate the accuracy.
38,517
from __future__ import print_function import argparse import json from collections import OrderedDict from paddlenlp.metrics.squad import squad_evaluate def calc_f1_score(answers, prediction): f1_scores = [] for ans in answers: ans_segs = _tokenize_chinese_chars(_normalize(ans)) prediction_segs ...
ref_ans: reference answers, dict pred_ans: predicted answer, dict return: f1_score: averaged F1 score em_score: averaged EM score total_count: number of samples in the reference dataset skip_count: number of samples skipped in the calculation due to unknown errors
38,518
from __future__ import print_function import argparse import json from collections import OrderedDict from paddlenlp.metrics.squad import squad_evaluate def read_dataset(file_path): f = open(file_path, "r") golden = {} for l in f.readlines(): ins = json.loads(l) golden[ins["sent_id"]] = ins...
null
38,519
from __future__ import print_function import argparse import json from collections import OrderedDict from paddlenlp.metrics.squad import squad_evaluate def read_model_prediction(file_path): f = open(file_path, "r") predict = {} for l in f.readlines(): ins = json.loads(l) predict[ins["id"]]...
null
38,520
from __future__ import print_function import argparse import json from collections import OrderedDict from paddlenlp.metrics.squad import squad_evaluate def read_temp(file_path): with open(file_path) as f1: result = json.loads(f1.read()) return result
null
38,521
from __future__ import print_function import argparse import json from collections import OrderedDict from paddlenlp.metrics.squad import squad_evaluate def get_args(): parser = argparse.ArgumentParser("mrc baseline performance eval") parser.add_argument("--golden_path", help="dataset file") parser.add_arg...
null
38,522
import argparse import json def get_args(): parser = argparse.ArgumentParser("F1 eval") parser.add_argument("--golden_path", required=True) parser.add_argument("--pred_path", required=True) parser.add_argument("--language", required=True, choices=["ch", "en"]) args = parser.parse_args() retur...
null
38,523
import argparse import json The provided code snippet includes necessary dependencies for implementing the `load_from_file` function. Write a Python function `def load_from_file(args)` to solve the following problem: Load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_...
Load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_id, rationales_list}, golden_label: {sent_id, label}, pred_label: {sent_id, label}
38,524
import argparse import json def _f1(_p, _r): def calc_f1(golden_evid, pred_evid): tp = set(pred_evid) & set(golden_evid) prec = len(tp) / len(pred_evid) if len(pred_evid) else 0 rec = len(tp) / len(golden_evid) if len(golden_evid) else 0 f1 = _f1(prec, rec) return f1
null
38,525
import argparse import json def _f1(_p, _r): if _p == 0 or _r == 0: return 0 return 2 * _p * _r / (_p + _r) The provided code snippet includes necessary dependencies for implementing the `calc_model_f1` function. Write a Python function `def calc_model_f1(golden_dict, pred_dict)` to solve the following...
:param golden_dict: dict :param pred_dict: dict :return: macro-f1, micro-f1
38,526
import argparse import json def get_args(): parser = argparse.ArgumentParser("F1 eval") parser.add_argument("--language", required=True, choices=["en", "ch"]) parser.add_argument("--golden_path", required=True) parser.add_argument("--pred_path", required=True) args = parser.parse_args() retur...
null
38,527
import argparse import json The provided code snippet includes necessary dependencies for implementing the `load_from_file` function. Write a Python function `def load_from_file(args)` to solve the following problem: Load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_...
Load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_id, rationales_list}, golden_label: {sent_id, label}, pred_label: {sent_id, label}
38,528
import argparse import json def calc_f1(golden_evid, pred_evid): tp = set(pred_evid) & set(golden_evid) prec = len(tp) / len(pred_evid) if len(pred_evid) else 0 rec = len(tp) / len(golden_evid) if len(golden_evid) else 0 f1 = _f1(prec, rec) return f1 def combine(cur_max_f1, union_set, golden_evid, p...
从golden_evids中找出与pred_evid f1最大的golden_evid
38,529
import argparse import json def _f1(_p, _r): if _p == 0 or _r == 0: return 0 return 2 * _p * _r / (_p + _r) The provided code snippet includes necessary dependencies for implementing the `calc_model_f1` function. Write a Python function `def calc_model_f1(golden_dict, pred_dict, golden_len)` to solve t...
:param golden_dict: dict :param pred_dict: dict :return: macro-f1, micro-f1
38,530
import argparse import json The provided code snippet includes necessary dependencies for implementing the `get_args` function. Write a Python function `def get_args()` to solve the following problem: get args Here is the function: def get_args(): """ get args """ parser = argparse.ArgumentParser("F1...
get args
38,531
import argparse import json The provided code snippet includes necessary dependencies for implementing the `load_from_file` function. Write a Python function `def load_from_file(args)` to solve the following problem: Load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_...
Load golden and pred data form file :return: golden_raw: {sent_id, rationales_lists}, pred_raw: {sent_id, rationales_list}, golden_label: {sent_id, label}, pred_label: {sent_id, label}
38,532
import argparse import json def _f1(_p, _r): if _p == 0 or _r == 0: return 0 return 2 * _p * _r / (_p + _r) The provided code snippet includes necessary dependencies for implementing the `calc_model_f1` function. Write a Python function `def calc_model_f1(golden_a_rationales, golden_b_rationales, pred_...
:param golden_dict: dict :param pred_dict: dict :return: macro-f1, micro-f1
38,533
import argparse import json def get_args(): parser = argparse.ArgumentParser("generate data") parser.add_argument("--pred_path", required=True) parser.add_argument("--data_dir", required=True) parser.add_argument("--data_dir2", required=True) parser.add_argument("--save_path", required=True) p...
null
38,534
import argparse import json def evids_load(path): evids = [] with open(path, "r") as f: for line in f.readlines(): dic = json.loads(line) evids.append(dic) return evids
null
38,535
import argparse import json def dataLoad(args): base_path = args.data_dir + "/" text_path = base_path + "rationale_text/dev/dev" text_exclusive_path = base_path + "rationale_exclusive_text/dev/dev" with open(text_path, "r") as f_text: text_dict_list = {} for line in f_text.readlines():...
null
38,536
import argparse import json def r_data_generation( args, evids, text_dict_list, text_exclusive_dict_list, text_dict_list2, text_exclusive_dict_list2 ): save_path = args.save_path f_save = open(save_path, "w") res_data = [] for ins in evids: temp = {} temp["id"] = ins["id"] ...
null
38,537
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,538
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,539
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,540
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,541
import argparse import json import math import os def get_args(): parser = argparse.ArgumentParser("generate data") parser.add_argument("--pred_path", required=True) parser.add_argument("--save_path", required=True) parser.add_argument("--language", required=True) parser.add_argument("--task", req...
null
38,542
import argparse import json import math import os def evids_load(path): evids = [] with open(path, "r") as f: for line in f.readlines(): dic = json.loads(line) evids.append(dic) return evids
null
38,543
import argparse import json import math import os def generate_for_senti(args, evid_dict, ratio): r = {} ex_r = {} label = evid_dict["pred_label"] char_attri = list(evid_dict["char_attri"].keys()) length = len(char_attri) rationale_ratio = ratio[0] toprationale_text, toprationale_exclusive_t...
null
38,544
import argparse import functools import json import os import sys import time from pathlib import Path import paddle from paddlenlp.data import Dict, Pad from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokenizer, RobertaTokenizer, ) from saliency_map.squad import RCInterpret, compute_prediction...
null
38,545
import argparse import functools import json import os import sys import time from pathlib import Path import paddle from paddlenlp.data import Dict, Pad from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokenizer, RobertaTokenizer, ) from saliency_map.squad import RCInterpret, compute_prediction...
null
38,546
import argparse import functools import json import os import sys import time from pathlib import Path import paddle from paddlenlp.data import Dict, Pad from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokenizer, RobertaTokenizer, ) from saliency_map.squad import RCInterpret, compute_prediction...
null
38,547
import argparse import functools import json import os import sys import time from pathlib import Path import paddle from paddlenlp.data import Dict, Pad from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokenizer, RobertaTokenizer, ) from saliency_map.squad import RCInterpret, compute_prediction...
null
38,548
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,549
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,550
import argparse import json import os import sys from functools import partial from pathlib import Path import paddle from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack, Tuple, Vocab from paddlenlp.datasets import DatasetBuilder from paddlenlp.transformers.roberta.tokenizer import ( RobertaBPETokeniz...
null
38,551
import json import os import pathlib import numpy as np import paddle from paddlenlp.datasets import load_dataset The provided code snippet includes necessary dependencies for implementing the `load_prompt_arguments` function. Write a Python function `def load_prompt_arguments(args)` to solve the following problem: Lo...
Load prompt and label words according to prompt index.
38,552
import json import os import pathlib import numpy as np import paddle from paddlenlp.datasets import load_dataset def save_data(data, save_path, save_file=None): if save_file is not None: pathlib.Path(save_path).mkdir(parents=True, exist_ok=True) save_path = os.path.join(save_path, save_file) wi...
Combine unsupervised data and corresponding predicted labels and save one example per line.
38,553
import json import os import pathlib import numpy as np import paddle from paddlenlp.datasets import load_dataset LABEL_TO_STANDARD = { "tnews": { "news_story": "100", "news_culture": "101", "news_entertainment": "102", "news_sports": "103", "news_finance": "104", "ne...
Extract predicted labels and save as the format required by FewCLUE.
38,554
import json import numpy as np from paddlenlp.datasets import MapDataset, load_dataset def extend_with_pseudo_data(data_ds, pseudo_path, labels_to_ids): """ Extend train dataset with pseudo labeled examples if exists. """ if pseudo_path is None: return data_ds with open(pseudo_path, "r", enc...
Load fewclue datasets and convert them to the standard format of PET.
38,556
import json import os import pathlib import numpy as np import paddle from paddlenlp.datasets import load_dataset def save_data(data, save_path, save_file=None): if save_file is not None: pathlib.Path(save_path).mkdir(parents=True, exist_ok=True) save_path = os.path.join(save_path, save_file) wi...
Combine unsupervised data and corresponding predicted labels and save one example per line.
38,557
import json import os import pathlib import numpy as np import paddle from paddlenlp.datasets import load_dataset LABEL_TO_STANDARD = { "tnews": { "news_story": "100", "news_culture": "101", "news_entertainment": "102", "news_sports": "103", "news_finance": "104", "ne...
Extract predicted labels and save as the format required by FewCLUE.
38,558
import json from functools import partial import paddle from paddlenlp.dataaug import WordDelete, WordInsert, WordSubstitute, WordSwap from paddlenlp.datasets import MapDataset, load_dataset def extend_with_pseudo_data(data_ds, pseudo_path, labels_to_ids): """ Extend train dataset with pseudo labeled examples i...
Load fewclue datasets and convert them to the standard format of PET.
38,562
import json from functools import partial import paddle from paddlenlp.dataaug import WordDelete, WordInsert, WordSubstitute, WordSwap from paddlenlp.datasets import MapDataset, load_dataset def extend_with_pseudo_data(data_ds, pseudo_path, labels_to_ids): """ Extend train dataset with pseudo labeled examples i...
Load fewclue datasets and convert them to the standard format of PET.
38,563
import os import random import numpy as np import paddle from data import InputFeatures from paddle.io import DataLoader from paddle.optimizer.lr import LambdaDecay from paddlenlp.datasets import MapDataset The provided code snippet includes necessary dependencies for implementing the `set_seed` function. Write a Pyth...
set random seed
38,564
import os import random import numpy as np import paddle from data import InputFeatures from paddle.io import DataLoader from paddle.optimizer.lr import LambdaDecay from paddlenlp.datasets import MapDataset The provided code snippet includes necessary dependencies for implementing the `check_args` function. Write a Py...
check output_dir and make it when not exist
38,565
import os import random import numpy as np import paddle from data import InputFeatures from paddle.io import DataLoader from paddle.optimizer.lr import LambdaDecay from paddlenlp.datasets import MapDataset class InputFeatures(dict): """ Data structure of every wrapped example or a batch of examples as the inp...
null
38,566
import os import random import numpy as np import paddle from data import InputFeatures from paddle.io import DataLoader from paddle.optimizer.lr import LambdaDecay from paddlenlp.datasets import MapDataset def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None): if isinstance(d...
null
38,567
import csv import json import os from abc import abstractmethod from collections import defaultdict from dataclasses import dataclass, field import paddle import pandas as pd from paddle.metric import Accuracy from paddlenlp.datasets import MapDataset from paddlenlp.metrics import AccuracyAndF1, Mcc, PearsonAndSpearman...
Read datasets from files. Args: dataset (str): The dataset name in lowercase. data_path (str): The path to the dataset directory, including train, dev or test file. splits (list): Which file(s) of dataset to read, such as ['train', 'dev', 'test'].
38,568
import argparse import os from functools import partial import numpy as np import paddle import paddle.nn as nn from data import METRIC_MAPPING, TASK_MAPPING, InputFeatures, load_dataset from template import ManualTemplate from tokenizer import MLMTokenizerWrapper from utils import ( LinearSchedulerWarmup, chec...
null
38,569
import argparse import os from functools import partial import numpy as np import paddle import paddle.nn as nn from data import METRIC_MAPPING, TASK_MAPPING, InputFeatures, load_dataset from template import ManualTemplate from tokenizer import MLMTokenizerWrapper from utils import ( LinearSchedulerWarmup, chec...
Compute the loss proposed in RGL method.
38,570
import argparse import io import os import random import time from functools import partial import numpy as np import paddle import pgl import yaml from data import GraphDataLoader, PredictData, TrainData, batch_fn from easydict import EasyDict as edict from models import ErnieSageForLinkPrediction from paddlenlp.trans...
null
38,571
import argparse import io import os import random import time from functools import partial import numpy as np import paddle import pgl import yaml from data import GraphDataLoader, PredictData, TrainData, batch_fn from easydict import EasyDict as edict from models import ErnieSageForLinkPrediction from paddlenlp.trans...
null
38,572
import os import numpy as np import paddle import pgl from paddle.io import Dataset from pgl.sampling import graphsage_sample def batch_fn(batch_ex, samples, base_graph, term_ids): batch_src = [] batch_dst = [] batch_neg = [] for batch in batch_ex: batch_src.append(batch[0]) batch_dst.a...
null
38,573
import argparse import io import os from functools import partial from io import open import numpy as np import pgl import yaml from easydict import EasyDict as edict from pgl.graph_kernel import alias_sample_build_table from pgl.utils.logger import log from paddlenlp.transformers import ErnieTinyTokenizer, ErnieTokeni...
null
38,574
import argparse import io import os from functools import partial from io import open import numpy as np import pgl import yaml from easydict import EasyDict as edict from pgl.graph_kernel import alias_sample_build_table from pgl.utils.logger import log from paddlenlp.transformers import ErnieTinyTokenizer, ErnieTokeni...
null
38,575
import paddle import paddle.nn as nn import paddle.nn.functional as F class SoftmaxWithCrossEntropy(nn.Layer): """softmax with cross entropy loss""" def __init__(self, config): super(SoftmaxWithCrossEntropy, self).__init__() def forward(self, logits, label): return F.cross_entropy(logits, la...
Choose different type of loss by config Args: config (Dict): config file. Raises: ValueError: invalid loss type. Returns: Class: the real class object.
38,576
from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from models import ScoreModelOutput from paddle.io import Dataset import paddlenlp.trainer.trainer as trainer from paddlenlp.data import DataCollator from paddlen...
null
38,577
from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from models import ScoreModelOutput from paddle.io import Dataset import paddlenlp.trainer.trainer as trainer from paddlenlp.data import DataCollator from paddlen...
null
38,578
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
Re-tokenize a batch of input ids from one tokenizer to another.
38,579
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
Gather log probabilities of the given labels from the logits.
38,580
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
null
38,581
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
null
38,582
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
null
38,583
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
Just a copy of single training step complete code in Trainer.train while loop which including forward+backward+step, while wraps the inputs and outputs to make the complicated copied code no need to change. Maybe a better way is to add fine-grained methods including these steps to Trainer which is similar to DeepSpeed ...
38,584
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
null
38,585
import copy import itertools import math import os import time from contextlib import contextmanager from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F import tqdm from data import DummyDataset, PromptOnlyBatch fr...
Check if two tokenizers are the same.
38,586
from __future__ import annotations import abc import bisect import copy import os import warnings from fractions import Fraction from typing import Any, Callable, ClassVar, Collection, Iterable, Iterator, List from weakref import WeakValueDictionary import numpy as np import paddle from paddle.io import Dataset, Iterab...
null
38,587
from __future__ import annotations import abc import bisect import copy import os import warnings from fractions import Fraction from typing import Any, Callable, ClassVar, Collection, Iterable, Iterator, List from weakref import WeakValueDictionary import numpy as np import paddle from paddle.io import Dataset, Iterab...
null
38,588
from __future__ import annotations import abc import bisect import copy import os import warnings from fractions import Fraction from typing import Any, Callable, ClassVar, Collection, Iterable, Iterator, List from weakref import WeakValueDictionary import numpy as np import paddle from paddle.io import Dataset, Iterab...
null
38,589
from __future__ import annotations import abc import bisect import copy import os import warnings from fractions import Fraction from typing import Any, Callable, ClassVar, Collection, Iterable, Iterator, List from weakref import WeakValueDictionary import numpy as np import paddle from paddle.io import Dataset, Iterab...
Parse dataset path and its proportion and optionally additional arguments from a string. Args: string (str): Dataset string in the format of ``dataset_name[:proportion[:dataset_path]]``.
38,590
import argparse import os import time import paddle from datasets import load_dataset from paddle.io import DataLoader from paddlenlp.data import DataCollatorForTokenClassification from paddlenlp.metrics import ChunkEvaluator from paddlenlp.transformers import ( BertForTokenClassification, BertTokenizer, Er...
null
38,591
import argparse import paddle from datasets import load_dataset from paddle.io import DataLoader from paddlenlp.data import DataCollatorForTokenClassification from paddlenlp.transformers import BertForTokenClassification, BertTokenizer def parse_decodes(input_words, id2label, decodes, lens): decodes = [x for batch ...
null
38,592
import argparse import paddle from datasets import load_dataset from paddle.io import DataLoader from paddlenlp.data import Dict, Pad, Stack from paddlenlp.metrics import ChunkEvaluator from paddlenlp.transformers import BertForTokenClassification, BertTokenizer def do_eval(args): paddle.set_device(args.device) ...
null
38,593
import json import logging import os import random from dataclasses import dataclass from typing import List import numpy as np import paddle import tabulate from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler from uie.evaluation import constants from uie.evaluation.sel2record import MapConfig, Reco...
Set logger
38,594
import json import logging import os import random from dataclasses import dataclass from typing import List import numpy as np import paddle import tabulate from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler from uie.evaluation import constants from uie.evaluation.sel2record import MapConfig, Reco...
Write prediction to output_dir Args: eval_prediction (dict): - `record` (list(dict)), each element is extraction reocrd - `sel` (list(str)): each element is sel expression - `metric` (dict) output_dir (str): Output directory path prefix (str, optional): prediction file prefix. Defaults to 'eval'. Write prediction to fi...
38,595
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
Mapping generated spot-asoc result to Entity/Relation/Event
38,596
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
Check two span whether overlap or not Args: x (Tuple[int, int]): start, end including position of span x y (Tuple[int, int]): start, end including position of span y x: (3, 4), y: (4, 5) -> True x: (3, 3), y: (4, 5) -> False Returns: bool: two span whether overlap or not
38,597
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
Convert start, end (inlcuding) tuple to index list Args: matched (Tuple[int, int]): start and end position tuple (3, 4) -> [3, 4] (3, 3) -> [3] Returns: List[int]: List of index
38,598
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
Convert text span string to token list Args: text (string): text span string span_to_token_strategy (str, optional): Defaults to 'space'. - space: split text to tokens using space - list: split text to toekns as list Raises: NotImplementedError: No implemented span_to_token_strategy Returns: list(str): list of token
38,599
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
null
38,600
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
null
38,601
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
null
38,602
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
null
38,603
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
add right bracket to fix ill-formed expression
38,604
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
get str from sel tree
38,605
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
null
38,606
from typing import Tuple, List, Dict from collections import defaultdict, OrderedDict, Counter import os import numpy import logging import re import json from nltk.tree import ParentedTree from uie.evaluation.constants import span_start, type_start, type_end, null_span, offset_map_strategy from uie.evaluation.scorer i...
Convert spot asoc instance to target string
38,607
import sys from collections import defaultdict from copy import deepcopy from typing import Dict, List def tuple_offset(offset): if isinstance(offset, tuple): return offset else: return tuple(offset)
null
38,608
import sys from collections import defaultdict from copy import deepcopy from typing import Dict, List def warning_tp_increment(gold, pred, prefix): sys.stderr.write(f"{prefix} TP Increment Warning, Gold Offset: {gold['offset']}\n") sys.stderr.write(f"{prefix} TP Increment Warning, Pred Offset: {pred['offset']...
null
38,609
import copy from typing import List, Dict from collections import defaultdict import yaml import json import os from uie.evaluation.sel2record import RecordSchema, merge_schema def main_entity_relation(schema_file, schema_name, instances, output_folder): schema = yaml.load(open(schema_file, encoding="utf8"), Loader...
null