id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
38,400
import argparse import os import shutil import string import tempfile import time from bs_pyrouge import Rouge155 def rouge_results_to_str(results_dict): return ">> ROUGE-F(1/2/l): {:.2f}/{:.2f}/{:.2f}\nROUGE-R(1/2/3/l): {:.2f}/{:.2f}/{:.2f}\n".format( results_dict["rouge_1_f_score"] * 100, results...
null
38,401
import argparse import os import shutil import string import tempfile import time from bs_pyrouge import Rouge155 def count_tokens(tokens): def get_f1(text_a, text_b): tokens_a = text_a.lower().split() tokens_b = text_b.lower().split() if len(tokens_a) == 0 or len(tokens_b) == 0: return 1 if len(to...
null
38,402
from __future__ import print_function, unicode_literals, division import codecs import os import platform import re from functools import partial from subprocess import check_output from tempfile import mkdtemp import logging from pyrouge.utils import log from pyrouge.utils.file_utils import verify_dir REMAP = {"-lrb-"...
null
38,403
from __future__ import print_function, unicode_literals, division import codecs import logging import os import platform import re from functools import partial from subprocess import check_output from tempfile import mkdtemp from pyrouge.utils import log from pyrouge.utils.file_utils import verify_dir REMAP = {"-lrb-"...
null
38,404
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import glob import json import logging import os import shutil import string import tempfile import time from multiprocessing import Pool, cpu_count from pathlib import Path import rouge from bs_...
null
38,405
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import glob import json import logging import os import shutil import string import tempfile import time from multiprocessing import Pool, cpu_count from pathlib import Path import rouge from bs_...
null
38,406
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import glob import json import logging import os import shutil import string import tempfile import time from multiprocessing import Pool, cpu_count from pathlib import Path import rouge from bs_...
null
38,407
import argparse import os import tqdm from nltk.tokenize.treebank import TreebankWordDetokenizer from paddlenlp.transformers.prophetnet.tokenizer import ProphetNetTokenizer def uncased_preocess(fin, fout, keep_sep=False, max_len=512): def tokenize_with_bert_uncase(fin, fout, max_len=512): def tokenize_data(dataset): ...
null
38,408
from dataclasses import dataclass, field from typing import Optional import paddle from tqdm import tqdm from paddlenlp.data import Pad from paddlenlp.datasets import load_dataset from paddlenlp.trainer import PdArgumentParser, Trainer, TrainingArguments, set_seed from paddlenlp.transformers.prophetnet.modeling import ...
null
38,409
from dataclasses import dataclass, field from typing import Optional import paddle from tqdm import tqdm from paddlenlp.data import Pad from paddlenlp.datasets import load_dataset from paddlenlp.trainer import PdArgumentParser, Trainer, TrainingArguments, set_seed from paddlenlp.transformers.prophetnet.modeling import ...
null
38,410
import argparse import os import re import sys from os import listdir from os.path import isfile, join args = parser.parse_args() data_root_path = "data" files2rouge_template = ".*ROUGE-1 Average_F: (?P<rouge1_f>\d+(\.\d*)?|\.\d+).*ROUGE-2 Average_F: (?P<rouge2_f>\d+(\.\d*)?|\.\d+).*ROUGE-L Average_F: (?P<rougeL_f>\d+(...
null
38,411
import argparse import os import random import time from pprint import pprint import numpy as np import paddle from paddle.io import BatchSampler, DataLoader from rouge_score import rouge_scorer, scoring from tqdm import tqdm from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlen...
null
38,412
import argparse import os import random import time from pprint import pprint import numpy as np import paddle from paddle.io import BatchSampler, DataLoader from rouge_score import rouge_scorer, scoring from tqdm import tqdm from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlen...
null
38,413
import argparse import os import random import time from pprint import pprint import numpy as np import paddle from paddle.io import BatchSampler, DataLoader from rouge_score import rouge_scorer, scoring from tqdm import tqdm from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlen...
null
38,414
import collections import hashlib import json import os import subprocess import sys chunks_dir = os.path.join(finished_files_dir, "chunked") def chunk_file(set_name): in_file = finished_files_dir + os.sep + "%s.json" % set_name reader = open(in_file, "r") chunk = 0 finished = False while not finish...
null
38,415
import collections import hashlib import json import os import subprocess import sys The provided code snippet includes necessary dependencies for implementing the `tokenize_stories` function. Write a Python function `def tokenize_stories(stories_dir, tokenized_stories_dir)` to solve the following problem: Maps a whol...
Maps a whole directory of .story files to a tokenized version using Stanford CoreNLP Tokenizer
38,416
import collections import hashlib import json import os import subprocess import sys SENTENCE_START = "<s>" SENTENCE_END = "</s>" cnn_tokenized_stories_dir = "cnn_stories_tokenized_json" dm_tokenized_stories_dir = "dm_stories_tokenized_json" finished_files_dir = "finished_files_json" num_expected_cnn_stories = 92579 nu...
Reads the tokenized .story files corresponding to the urls listed in the url_file and writes them to a out_file.
38,417
import logging import os import pyrouge def print_results(article, abstract, decoded_output): print("") print(("ARTICLE: %s", article)) print(("REFERENCE SUMMARY: %s", abstract)) print(("GENERATED SUMMARY: %s", decoded_output)) print("")
null
38,418
import logging import os import pyrouge def rouge_eval(ref_dir, dec_dir): r = pyrouge.Rouge155() r.model_filename_pattern = "#ID#_reference.txt" r.system_filename_pattern = "(\d+)_decoded.txt" r.model_dir = ref_dir r.system_dir = dec_dir logging.getLogger("global").setLevel(logging.WARNING) # ...
null
38,419
import logging import os import pyrouge def rouge_log(results_dict, dir_to_write): log_str = "" for x in ["1", "2", "l"]: log_str += "\nROUGE-%s:\n" % x for y in ["f_score", "recall", "precision"]: key = "rouge_%s_%s" % (x, y) key_cb = key + "_cb" key_ce = ke...
null
38,420
import logging import os import pyrouge def calc_running_avg_loss(loss, running_avg_loss, step, decay=0.99): if running_avg_loss == 0: # on the first iteration just take the loss running_avg_loss = loss else: running_avg_loss = running_avg_loss * decay + (1 - decay) * loss running_avg_loss...
null
38,421
import logging import os import pyrouge def make_html_safe(s): s.replace("<", "&lt;") s.replace(">", "&gt;") return s def write_for_rouge(reference_sents, decoded_words, ex_index, _rouge_ref_dir, _rouge_dec_dir): decoded_sents = [] while len(decoded_words) > 0: try: fst_period_i...
null
38,422
import numpy as np import paddle import config def get_input_from_batch(batch): batch_size = len(batch.enc_lens) enc_batch = paddle.to_tensor(batch.enc_batch, dtype="int64") enc_padding_mask = paddle.to_tensor(batch.enc_padding_mask, dtype="float32") enc_lens = batch.enc_lens extra_zeros = None ...
null
38,423
import numpy as np import paddle import config def get_output_from_batch(batch): dec_batch = paddle.to_tensor(batch.dec_batch, dtype="int64") dec_padding_mask = paddle.to_tensor(batch.dec_padding_mask, dtype="float32") dec_lens = batch.dec_lens max_dec_len = np.max(dec_lens) dec_lens_var = paddle.t...
null
38,424
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np random.seed(123) def example_generator(data_path, single_pass): while True: filelist = glob.glob(data_path) # get the lis...
null
38,425
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np UNKNOWN_TOKEN = "[UNK]" def article2ids(article_words, vocab): ids = [] oovs = [] unk_id = vocab.word2id(UNKNOWN_TOKEN) ...
null
38,426
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np UNKNOWN_TOKEN = "[UNK]" def abstract2ids(abstract_words, vocab, article_oovs): ids = [] unk_id = vocab.word2id(UNKNOWN_TOKEN) ...
null
38,427
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np def outputids2words(id_list, vocab, article_oovs): words = [] for i in id_list: try: w = vocab.id2word(i) ...
null
38,428
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np SENTENCE_START = "<s>" SENTENCE_END = "</s>" def abstract2sents(abstract): cur = 0 sents = [] while True: try: ...
null
38,429
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np UNKNOWN_TOKEN = "[UNK]" def show_art_oovs(article, vocab): unk_token = vocab.word2id(UNKNOWN_TOKEN) words = article.split(" ")...
null
38,430
import csv import glob import io import json import queue import random import time from random import shuffle from threading import Thread import config import data import numpy as np UNKNOWN_TOKEN = "[UNK]" def show_abs_oovs(abstract, vocab, article_oovs): unk_token = vocab.word2id(UNKNOWN_TOKEN) words = abs...
null
38,431
import os import sys import paddle import paddle.nn.initializer as I import paddle.nn as nn import paddle.nn.functional as F import config def paddle2D_scatter_add(x_tensor, index_tensor, update_tensor, dim=0): dim0, dim1 = update_tensor.shape update_tensor = paddle.flatten(update_tensor, start_axis=0, stop_ax...
null
38,432
import argparse import json import math import os import time import paddle import paddle.distributed as dist import paddle.nn.functional as F from paddle.optimizer import AdamW from utils import compute_metrics, create_data_loader, print_args, select_sum, set_seed from paddlenlp.datasets import load_dataset from paddl...
null
38,433
import argparse import json import math import os import time import paddle import paddle.distributed as dist import paddle.nn.functional as F from paddle.optimizer import AdamW from utils import compute_metrics, create_data_loader, print_args, select_sum, set_seed from paddlenlp.datasets import load_dataset from paddl...
null
38,434
import random from functools import partial import numpy as np import paddle import paddle.distributed as dist from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler from rouge import Rouge from paddlenlp.data import Pad from paddlenlp.metrics import BLEU def print_args(args): print("----------- ...
null
38,435
import numpy as np from paddle_serving_server.web_service import Op, WebService from paddlenlp.data import Pad from paddlenlp.ops.ext_utils import load from paddlenlp.transformers import UNIMOTokenizer from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the...
Convert all examples into necessary features.
38,436
import numpy as np from paddle_serving_server.web_service import Op, WebService from paddlenlp.data import Pad from paddlenlp.ops.ext_utils import load from paddlenlp.transformers import UNIMOTokenizer from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the...
Batchify a batch of examples.
38,437
import numpy as np from paddle_serving_server.web_service import Op, WebService from paddlenlp.data import Pad from paddlenlp.ops.ext_utils import load from paddlenlp.transformers import UNIMOTokenizer from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the...
Post-process the decoded sequence. Truncate from the first <eos>.
38,438
import argparse import os from pprint import pprint import numpy as np from paddle import inference from paddlenlp.data import Pad from paddlenlp.ops.ext_utils import load from paddlenlp.transformers import UNIMOTokenizer The provided code snippet includes necessary dependencies for implementing the `setup_args` funct...
Setup arguments.
38,439
import argparse import os from pprint import pprint import numpy as np from paddle import inference from paddlenlp.data import Pad from paddlenlp.ops.ext_utils import load from paddlenlp.transformers import UNIMOTokenizer def load(name, build_dir=None, force=False, verbose=False, **kwargs): # TODO(guosheng): Need ...
Setup inference predictor.
38,440
import argparse import os from pprint import pprint import numpy as np from paddle import inference from paddlenlp.data import Pad from paddlenlp.ops.ext_utils import load from paddlenlp.transformers import UNIMOTokenizer def convert_example(example, tokenizer, max_seq_len=512, return_length=True): """Convert all e...
Use predictor to inference.
38,441
import argparse import os from pprint import pprint import paddle from paddlenlp.ops import FasterUNIMOText from paddlenlp.transformers import UNIMOLMHeadModel, UNIMOTokenizer from paddlenlp.utils.log import logger def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--model_name_...
null
38,442
import argparse import os from pprint import pprint import paddle from paddlenlp.ops import FasterUNIMOText from paddlenlp.transformers import UNIMOLMHeadModel, UNIMOTokenizer from paddlenlp.utils.log import logger logger = Logger() def do_predict(args): place = "gpu" place = paddle.set_device(place) mod...
null
38,443
import argparse def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model_type", default=None, type=str, required=True, help="Type of pre-trained model.") parser.add_argument( "--model_name_or_path", default=None, type=str, required...
null
38,444
import json import math import os import random import time import numpy as np import paddle from args import parse_args from datasets import load_dataset from paddle.io import DataLoader from paddlenlp.data import Dict, Pad, Stack from paddlenlp.metrics.squad import compute_prediction, squad_evaluate from paddlenlp.tr...
null
38,445
import json import math import os import random import time from functools import partial import numpy as np import paddle from args import parse_args from datasets import load_dataset from paddle.io import DataLoader from paddlenlp.data import DataCollatorWithPadding from paddlenlp.metrics.squad import compute_predict...
null
38,446
import argparse import os import paddle from run_squad import MODEL_CLASSES MODEL_CLASSES = { "bert": (BertForQuestionAnswering, BertTokenizer), "ernie": (ErnieForQuestionAnswering, ErnieTokenizer), "funnel": (FunnelForQuestionAnswering, FunnelTokenizer), } def parse_args(): parser = argparse.Argument...
null
38,447
import argparse def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model_type", default="bert", type=str, help="Type of pre-trained model.") parser.add_argument( "--model_name_or_path", default="bert-base-uncased", type=str, help="...
null
38,448
import argparse def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model_type", default=None, type=str, required=True, help="Type of pre-trained model.") parser.add_argument( "--model_name_or_path", default=None, type=str, required...
null
38,449
import json import math import os import random import time from functools import partial import numpy as np import paddle from args import parse_args from paddle.io import DataLoader from paddlenlp.data import Dict, Pad, Stack from paddlenlp.datasets import load_dataset from paddlenlp.transformers import ( BertFor...
null
38,450
import collections import copy import numpy as np import paddle from paddle import ParamAttr, tensor from paddle.common_ops_import import convert_dtype from paddle.nn import Layer, LayerList from paddle.nn import functional as F from paddle.nn.layer.common import Dropout, Linear from paddle.nn.layer.norm import LayerNo...
If `param_attr` is a list or tuple, convert every element in it to a ParamAttr instance. Otherwise, repeat `param_attr` `n` times to construct a list, and rename every one by appending a increasing index suffix to avoid having same names when `param_attr` contains a name. Parameters: param_attr (list|tuple|ParamAttr): ...
38,451
import collections import copy import numpy as np import paddle from paddle import ParamAttr, tensor from paddle.common_ops_import import convert_dtype from paddle.nn import Layer, LayerList from paddle.nn import functional as F from paddle.nn.layer.common import Dropout, Linear from paddle.nn.layer.norm import LayerNo...
Convert the attention mask to the target dtype we expect. Parameters: attn_mask (Tensor, optional): A tensor used in multi-head attention to prevents attention to some unwanted positions, usually the paddings or the subsequent positions. It is a tensor with shape broadcasted to `[batch_size, n_head, sequence_length, se...
38,452
from __future__ import absolute_import, division, print_function, unicode_literals import paddle def create_if_not_exists(dir): try: dir.mkdir(parents=True) except FileExistsError: pass return dir
null
38,453
from __future__ import absolute_import, division, print_function, unicode_literals import paddle def get_warmup_and_linear_decay(max_steps, warmup_steps): return lambda step: min(step / warmup_steps, 1.0 - (step - warmup_steps) / (max_steps - warmup_steps))
null
38,454
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,455
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,456
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,457
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,458
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,459
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,460
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,461
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,462
import argparse import collections import json import logging import os import re import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from roberta.modeling import RobertaForSequenceClassification from simnet.model import SimNet ...
null
38,463
import argparse import os import sys from functools import partial import paddle from paddlenlp.data import Pad, Stack, Tuple, Vocab from paddlenlp.datasets import load_dataset from model import SimNet from utils import CharTokenizer, convert_example The provided code snippet includes necessary dependencies for imple...
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,464
import numpy as np The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example(example, tokenizer, is_test=False, language="en")` to solve the following problem: Builds model inputs from a sequence for sequence classification t...
Builds model inputs from a sequence for sequence classification tasks. It use `jieba.cut` to tokenize text. Args: example(obj:`list[str]`): List of input data, containing text and label if it have label. tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string. is_test(obj:`False`, defaults...
38,465
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[List[str, str]]`): The prediction data whose each element is a text pair. Each text will be tokenized by jieba.lcut() function. tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string. Returns: examples (o...
38,466
import numpy as np def get_idx_from_word(word, word_to_idx, unk_word): if word in word_to_idx: return word_to_idx[word] return word_to_idx[unk_word]
null
38,467
import numpy as np def tokenizer_lac(string, lac): temp = "" res = [] for c in string: if "\u4e00" <= c <= "\u9fff": if temp != "": res.extend(lac.run(temp)) temp = "" res.append(c) else: temp += c if temp != "": ...
null
38,468
import numpy as np def punc_split(string, vocab_path): punc_set = set() with open(vocab_path, "r") as f: for token in f: punc_set.add(token.strip()) punc_set.add(" ") for ascii_num in range(65296, 65306): punc_set.add(chr(ascii_num)) for ascii_num in range...
null
38,469
import argparse import sys import paddle from paddlenlp.data import Pad, Stack, Tuple, Vocab from paddlenlp.datasets import load_dataset from model import SimNet from utils import CharTokenizer, preprocess_data The provided code snippet includes necessary dependencies for implementing the `interpret` function. Write ...
Predicts the data labels. Args: model (obj:`paddle.nn.Layer`): A model to classify texts. data (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object. A Example object contains `text`(word_ids) and `seq_len`(sequence length). label_map(obj:`dict`): The label id (key) to label str ...
38,470
import argparse import paddle import paddle.nn.functional as F from model import SimNet from utils import preprocess_prediction_data from paddlenlp.data import JiebaTokenizer, Pad, Stack, Tuple, Vocab The provided code snippet includes necessary dependencies for implementing the `predict` function. Write a Python func...
Predicts the data labels. Args: model (obj:`paddle.nn.Layer`): A model to classify texts. data (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object. A Example object contains `text`(word_ids) and `seq_len`(sequence length). label_map(obj:`dict`): The label id (key) to label str ...
38,471
import argparse import sys import paddle from paddlenlp.data import Pad, Stack, Tuple, Vocab from paddlenlp.datasets import load_dataset from model import SimNet from utils import CharTokenizer, preprocess_data The provided code snippet includes necessary dependencies for implementing the `interpret` function. Write ...
Predicts the data labels. Args: model (obj:`paddle.nn.Layer`): A model to classify texts. data (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object. A Example object contains `text`(word_ids) and `seq_len`(sequence length). label_map(obj:`dict`): The label id (key) to label str ...
38,472
import argparse import os from functools import partial import numpy as np import paddle from data import convert_pointwise_example as convert_example from data import create_dataloader, read_text_pair from model import PointwiseMatching from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset ...
Predicts the data labels. Args: model (obj:`SemanticIndexBase`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): co...
38,473
import paddle import numpy as np from paddlenlp.datasets import MapDataset def convert_pointwise_example(example, tokenizer, max_seq_length=512, is_test=False, language="en"): if language == "ch": q_name = "query" t_name = "title" l_name = "label" else: q_name = "sentence1" ...
null
38,474
import paddle import numpy as np from paddlenlp.datasets import MapDataset def convert_pairwise_example(example, tokenizer, max_seq_length=512, phase="train"): if phase == "train": query, pos_title, neg_title = example["query"], example["title"], example["neg_title"] pos_inputs = tokenizer(text=q...
null
38,475
import argparse import os import random import sys import time from functools import partial import numpy as np import paddle from data import convert_pointwise_example as convert_example from data import create_dataloader from paddlenlp.data import Pad, Stack, Tuple from paddlenlp.datasets import load_dataset from pad...
null
38,476
from io import open import os import os.path import json import string import numpy as np from sklearn.utils import check_random_state from LIME.exceptions import LimeError The provided code snippet includes necessary dependencies for implementing the `id_generator` function. Write a Python function `def id_generator(...
Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks.
38,477
from __future__ import absolute_import, division, print_function, unicode_literals import paddle def create_if_not_exists(dir): try: dir.mkdir(parents=True) except: pass return dir
null
38,479
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack from paddlenlp....
null
38,480
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack from paddlenlp....
null
38,481
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack from paddlenlp....
null
38,482
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack from paddlenlp....
null
38,483
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack from paddlenlp....
null
38,484
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret from tqdm import tqdm from paddlenlp.data import Dict, Pad, Stack from paddlenlp....
null
38,485
import argparse import logging import os import re import sys import time from pathlib import Path import paddle from paddle.io import DataLoader from roberta.modeling import RobertaForQuestionAnswering from saliency_map.utils import create_if_not_exists, get_warmup_and_linear_decay from squad import DuReaderChecklist ...
null
38,486
import argparse import logging import os import re import sys import time from pathlib import Path import paddle from paddle.io import DataLoader from roberta.modeling import RobertaForQuestionAnswering from saliency_map.utils import create_if_not_exists, get_warmup_and_linear_decay from squad import DuReaderChecklist ...
null
38,487
import argparse import json import logging import os import sys import time from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret, compute_prediction from paddlenlp.data import Dict, Pad from paddlenlp.transformers.rob...
null
38,488
import argparse import json import logging import os import sys import time from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret, compute_prediction from paddlenlp.data import Dict, Pad from paddlenlp.transformers.rob...
null
38,489
import argparse import json import logging import os import sys import time from functools import partial from pathlib import Path import paddle from roberta.modeling import RobertaForQuestionAnswering from squad import RCInterpret, compute_prediction from paddlenlp.data import Dict, Pad from paddlenlp.transformers.rob...
null
38,490
import collections import json import numpy as np from paddlenlp.datasets import DatasetBuilder The provided code snippet includes necessary dependencies for implementing the `compute_prediction_checklist` function. Write a Python function `def compute_prediction_checklist( examples, features, predictions,...
Post-processes the predictions of a question-answering model to convert them to answers that are substrings of the original contexts. This is the base postprocessing functions for models that only return start and end logits. Args: examples: The non-preprocessed dataset (see the main script for more information). featu...
38,493
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from rnn.model import BiLSTMAttentionModel, SelfInteractiveAttention from rnn.utils import CharTokenizer...
null
38,494
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from rnn.model import BiLSTMAttentionModel, SelfInteractiveAttention from rnn.utils import CharTokenizer...
null
38,495
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from rnn.model import BiLSTMAttentionModel, SelfInteractiveAttention from rnn.utils import CharTokenizer...
null
38,496
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from rnn.model import BiLSTMAttentionModel, SelfInteractiveAttention from rnn.utils import CharTokenizer...
null
38,497
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from rnn.model import BiLSTMAttentionModel, SelfInteractiveAttention from rnn.utils import CharTokenizer...
null
38,498
import argparse import collections import json import logging import os import sys from functools import partial from pathlib import Path import numpy as np import paddle from LIME.lime_text import LimeTextExplainer from rnn.model import BiLSTMAttentionModel, SelfInteractiveAttention from rnn.utils import CharTokenizer...
null
38,499
import argparse import os import random import sys import time from functools import partial import numpy as np import paddle import paddle.nn.functional as F from paddlenlp.data import Pad, Stack, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import LinearDecayWithWarmup from paddlenlp....
This function is the main part of the fine-tunning process
38,500
import numpy as np The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example(example, tokenizer, max_seq_length=512, is_test=False, language="ch")` to solve the following problem: Builds model inputs from a sequence or a pair...
Builds model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. And creates a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` It re...
38,501
from io import open import os import os.path import json import string import numpy as np from LIME.exceptions import LimeError from sklearn.utils import check_random_state The provided code snippet includes necessary dependencies for implementing the `id_generator` function. Write a Python function `def id_generator(...
Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks.
38,502
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...
sets random seed