code stringlengths 17 6.64M |
|---|
def gen_graph(branches, g=None, init_root=0, pre=''):
num_branches = [branch2num(i, init_root) for i in branches]
all_nodes = [j for branch in num_branches for j in branch]
all_nodes = np.unique(all_nodes)
all_nodes = all_nodes.tolist()
if (g is None):
g = ig.Graph()
for k in all_nodes... |
def c_factor(n):
'\n Average path length of unsuccesful search in a binary search tree given n points\n \n Parameters\n ----------\n n : int\n Number of data points for the BST.\n\n Returns\n -------\n float\n Average path length of unsuccesful search in a BST\n \n ... |
class iForest(object):
'\n Creates an iForest object. This object holds the data as well as the trained trees (iTree objects).\n\n Attributes\n ----------\n X : list\n Data used for training. It is a list of list of floats.\n nobjs: int\n Size of the dataset.\n sample: int\n ... |
class Node(object):
"\n A single node from each tree (each iTree object). Nodes containe information on hyperplanes used for data division, date to be passed to left and right nodes, whether they are external or internal nodes.\n\n Attributes\n ----------\n e: int\n Depth of the tree to which t... |
class iTree(object):
'\n A single tree in the forest that is build using a unique subsample.\n\n Attributes\n ----------\n exlevel: int\n Extension level used in the splitting criteria.\n e: int\n Depth of tree\n X: list\n Data present at the root node of this tree.\n siz... |
class PathFactor(object):
"\n Given a single tree (iTree objext) and a data point x = [x1,x2,...,xn], compute the legth of the path traversed by the point on the tree when it reaches an external node.\n\n Attributes\n ----------\n path_list: list\n A list of strings 'L' or 'R' which traces the ... |
def all_branches(node, current=[], branches=None):
'\n Utility function used in generating a graph visualization. It returns all the branches of a given tree so they can be visualized.\n\n Parameters\n ----------\n node: Node object\n\n Returns\n -------\n list\n list of branches that ... |
def read(filename):
return open(os.path.join(prjdir, filename)).read()
|
class FormanRicci():
def __init__(self, G: nx.Graph, weight='weight', method='augmented', verbose='ERROR'):
'A class to compute Forman-Ricci curvature for all nodes and edges in G.\n\n Parameters\n ----------\n G : NetworkX graph\n A given NetworkX graph, unweighted graph ... |
@lru_cache(_cache_maxsize)
def _get_single_node_neighbors_distributions(node, direction='successors'):
'Get the neighbor density distribution of given node `node`.\n\n Parameters\n ----------\n node : int\n Node index in Networkit graph `_Gk`.\n direction : {"predecessors", "successors"}\n ... |
def _distribute_densities(source, target):
"Get the density distributions of source and target node, and the cost (all pair shortest paths) between\n all source's and target's neighbors. Notice that only neighbors with top `_nbr_topk` edge weights.\n\n Parameters\n ----------\n source : int\n S... |
@lru_cache(_cache_maxsize)
def _source_target_shortest_path(source, target):
'Compute pairwise shortest path from `source` to `target` by BidirectionalDijkstra via Networkit.\n\n Parameters\n ----------\n source : int\n Source node index in Networkit graph `_Gk`.\n target : int\n Target ... |
def _get_all_pairs_shortest_path():
'Pre-compute all pairs shortest paths of the assigned graph `_Gk`.'
logger.trace('Start to compute all pair shortest path.')
global _Gk
t0 = time.time()
apsp = nk.distance.APSP(_Gk).run().getDistances()
logger.trace(('%8f secs for all pair by NetworKit.' % (... |
def _optimal_transportation_distance(x, y, d):
"Compute the optimal transportation distance (OTD) of the given density distributions by CVXPY.\n\n Parameters\n ----------\n x : (m,) numpy.ndarray\n Source's density distributions, includes source and source's neighbors.\n y : (n,) numpy.ndarray\... |
def _sinkhorn_distance(x, y, d):
"Compute the approximate optimal transportation distance (Sinkhorn distance) of the given density distributions.\n\n Parameters\n ----------\n x : (m,) numpy.ndarray\n Source's density distributions, includes source and source's neighbors.\n y : (n,) numpy.ndarr... |
def _average_transportation_distance(source, target):
'Compute the average transportation distance (ATD) of the given density distributions.\n\n Parameters\n ----------\n source : int\n Source node index in Networkit graph `_Gk`.\n target : int\n Target node index in Networkit graph `_Gk... |
def _compute_ricci_curvature_single_edge(source, target):
'Ricci curvature computation for a given single edge.\n\n Parameters\n ----------\n source : int\n Source node index in Networkit graph `_Gk`.\n target : int\n Target node index in Networkit graph `_Gk`.\n\n Returns\n ------... |
def _wrap_compute_single_edge(stuff):
'Wrapper for args in multiprocessing.'
return _compute_ricci_curvature_single_edge(*stuff)
|
def _compute_ricci_curvature_edges(G: nx.Graph, weight='weight', edge_list=[], alpha=0.5, method='OTDSinkhornMix', base=math.e, exp_power=2, proc=mp.cpu_count(), chunksize=None, cache_maxsize=1000000, shortest_path='all_pairs', nbr_topk=3000):
'Compute Ricci curvature for edges in given edge lists.\n\n Parame... |
def _compute_ricci_curvature(G: nx.Graph, weight='weight', **kwargs):
'Compute Ricci curvature of edges and nodes.\n The node Ricci curvature is defined as the average of node\'s adjacency edges.\n\n Parameters\n ----------\n G : NetworkX graph\n A given directional or undirectional NetworkX gr... |
def _compute_ricci_flow(G: nx.Graph, weight='weight', iterations=20, step=1, delta=0.0001, surgery=((lambda G, *args, **kwargs: G), 100), **kwargs):
'Compute the given Ricci flow metric of each edge of a given connected NetworkX graph.\n\n Parameters\n ----------\n G : NetworkX graph\n A given dir... |
class OllivierRicci():
"A class to compute Ollivier-Ricci curvature for all nodes and edges in G.\n Node Ricci curvature is defined as the average of all it's adjacency edge.\n\n "
def __init__(self, G: nx.Graph, weight='weight', alpha=0.5, method='OTDSinkhornMix', base=math.e, exp_power=2, proc=mp.cpu... |
def set_verbose(verbose='ERROR'):
'Set up the verbose level of the GraphRicciCurvature.\n\n Parameters\n ----------\n verbose : {"INFO", "TRACE","DEBUG","ERROR"}\n Verbose level. (Default value = "ERROR")\n - "INFO": show only iteration process log.\n - "TRACE": show detailed... |
def cut_graph_by_cutoff(G_origin, cutoff, weight='weight'):
'Remove graph\'s edges with "weight" greater than "cutoff".\n\n Parameters\n ----------\n G_origin : NetworkX graph\n A graph with ``weight`` as Ricci flow metric to cut.\n cutoff : float\n A threshold to remove all edges with "... |
def get_rf_metric_cutoff(G_origin, weight='weight', cutoff_step=0.025, drop_threshold=0.01):
'Get good clustering cutoff points for Ricci flow metric by detect the change of modularity while removing edges.\n\n Parameters\n ----------\n G_origin : NetworkX graph\n A graph with "weight" as Ricci fl... |
def ARI(G, clustering, clustering_label='club'):
'\n Computer the Adjust Rand Index (clustering accuracy) of "clustering" with "clustering_label" as ground truth.\n\n Parameters\n ----------\n G : NetworkX graph\n A given NetworkX graph with node attribute "clustering_label" as ground truth.\n ... |
def my_surgery(G_origin: nx.Graph(), weight='weight', cut=0):
'A simple surgery function that remove the edges with weight above a threshold\n\n Parameters\n ----------\n G_origin : NetworkX graph\n A graph with ``weight`` as Ricci flow metric to cut.\n weight:\n The edge weight used as ... |
def check_accuracy(G_origin, weight='weight', clustering_label='value', plot_cut=True):
'To check the clustering quality while cut the edges with weight using different threshold\n\n Parameters\n ----------\n G_origin : NetworkX graph\n A graph with ``weight`` as Ricci flow metric to cut.\n wei... |
def show_results(G, curvature='ricciCurvature'):
print('Karate Club Graph, first 5 edges: ')
for (n1, n2) in list(G.edges())[:5]:
print(('Ricci curvature of edge (%s,%s) is %f' % (n1, n2, G[n1][n2][curvature])))
plt.subplot(2, 1, 1)
ricci_curvtures = nx.get_edge_attributes(G, curvature).values... |
def draw_graph(G, clustering_label='club'):
'\n A helper function to draw a nx graph with community.\n '
complex_list = nx.get_node_attributes(G, clustering_label)
le = preprocessing.LabelEncoder()
node_color = le.fit_transform(list(complex_list.values()))
nx.draw_spring(G, nodelist=G.nodes(... |
def ARI(G, clustering, clustering_label='club'):
'\n Computer the Adjust Rand Index (clustering accuracy) of "clustering" with "clustering_label" as ground truth.\n\n Parameters\n ----------\n G : NetworkX graph\n A given NetworkX graph with node attribute "clustering_label" as ground truth.\n ... |
def my_surgery(G_origin: nx.Graph(), weight='weight', cut=0):
'A simple surgery function that remove the edges with weight above a threshold\n\n Parameters\n ----------\n G_origin : NetworkX graph\n A graph with ``weight`` as Ricci flow metric to cut.\n weight: str\n The edge weight used... |
def check_accuracy(G_origin, weight='weight', clustering_label='value', plot_cut=True):
'To check the clustering quality while cut the edges with weight using different threshold\n\n Parameters\n ----------\n G_origin : NetworkX graph\n A graph with ``weight`` as Ricci flow metric to cut.\n wei... |
def clean_graph(G):
for (n1, n2) in G.edges():
del G[n1][n2]['ricciCurvature']
del G[n1][n2]['original_RC']
G[n1][n2]['weight'] = 1
for n in G.nodes():
del G.nodes[n]['ricciCurvature']
|
def test_compute_ricci_curvature():
G = nx.Graph()
G.add_edges_from([(1, 2), (2, 3), (3, 4), (2, 4)])
G.add_node(5)
frc = FormanRicci(G, method='1d')
frc.compute_ricci_curvature()
frc_edges = list(nx.get_edge_attributes(frc.G, 'formanCurvature').values())
frc_nodes = list(nx.get_node_attri... |
def test_compute_ricci_curvature_edges():
G = nx.karate_club_graph()
for (n1, n2, d) in G.edges(data=True):
d.clear()
orc = OllivierRicci(G, method='OTD', alpha=0.5)
output = orc.compute_ricci_curvature_edges([(0, 1)])
npt.assert_almost_equal(output[(0, 1)], 0.111111)
|
def test_compute_ricci_curvature():
G = nx.karate_club_graph()
for (n1, n2, d) in G.edges(data=True):
d.clear()
orc = OllivierRicci(G, method='OTD', alpha=0.5)
Gout = orc.compute_ricci_curvature()
rc = list(nx.get_edge_attributes(Gout, 'ricciCurvature').values())
ans = [0.111111, (- 0.... |
def test_compute_ricci_curvature_directed():
Gd = nx.DiGraph()
Gd.add_edges_from([(0, 1), (1, 2), (2, 3), (1, 3), (3, 1)])
orc = OllivierRicci(Gd, method='OTD', alpha=0.5)
Gout = orc.compute_ricci_curvature()
rc = list(nx.get_edge_attributes(Gout, 'ricciCurvature').values())
ans = [(- 0.499999... |
def test_compute_ricci_curvature_ATD():
G = nx.karate_club_graph()
for (n1, n2, d) in G.edges(data=True):
d.clear()
orc = OllivierRicci(G, alpha=0.5, method='ATD', verbose='INFO')
orc.compute_ricci_curvature()
Gout = orc.compute_ricci_curvature()
rc = list(nx.get_edge_attributes(Gout, ... |
def test_compute_ricci_flow():
G = nx.karate_club_graph()
for (n1, n2, d) in G.edges(data=True):
d.clear()
orc = OllivierRicci(G, method='OTD', alpha=0.5)
Gout = orc.compute_ricci_flow(iterations=3)
rf = list(nx.get_edge_attributes(Gout, 'weight').values())
ans = [0.584642, 1.222957, 0... |
def test_ricci_community_all_possible_clusterings():
G = nx.karate_club_graph()
for (n1, n2, d) in G.edges(data=True):
d.clear()
orc = OllivierRicci(G, exp_power=1, alpha=0.5)
orc.compute_ricci_flow(iterations=40)
cc = orc.ricci_community_all_possible_clusterings()
cuts = [x[0] for x i... |
def test_ricci_community():
G = nx.karate_club_graph()
for (n1, n2, d) in G.edges(data=True):
d.clear()
orc = OllivierRicci(G, exp_power=1, alpha=0.5)
(cut, clustering) = orc.ricci_community()
cut_ans = 1.2613588421005884
clustering_ans = {0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12:... |
def fix_bad_unicode(text, normalization='NFC'):
return fix_text(text, normalization=normalization)
|
def fix_strange_quotes(text):
'\n Replace strange quotes, i.e., 〞with a single quote \' or a double quote " if it fits better.\n '
text = constants.SINGLE_QUOTE_REGEX.sub("'", text)
text = constants.DOUBLE_QUOTE_REGEX.sub('"', text)
return text
|
def replace_urls(text, replace_with=''):
'\n Replace all URLs in ``text`` str with ``replace_with`` str.\n '
return constants.URL_REGEX.sub(replace_with, text)
|
def replace_emails(text, replace_with=''):
'\n Replace all emails in ``text`` str with ``replace_with`` str.\n '
return constants.EMAIL_REGEX.sub(replace_with, text)
|
def remove_substrings(text, to_replace, replace_with=''):
'\n Remove (or replace) substrings from a text.\n Args:\n text (str): raw text to preprocess\n to_replace (iterable or str): substrings to remove/replace\n replace_with (str): defaults to an empty string but\n you repl... |
def remove_emoji(text):
return remove_substrings(text, UNICODE_EMOJI['en'])
|
def remove_number_or_digit(text, replace_with=''):
return re.sub(constants.BANGLA_DIGIT_REGEX, replace_with, text)
|
def remove_punctuations(text, replace_with=''):
for punc in corpus.punctuations:
print(punc)
text = text.replace(punc, replace_with)
return text
|
class CleanText(object):
def __init__(self, fix_unicode=True, unicode_norm=True, unicode_norm_form='NFKC', remove_url=False, remove_email=False, remove_number=False, remove_digits=False, remove_emoji=False, remove_punct=False, replace_with_url='<URL>', replace_with_email='<EMAIL>', replace_with_number='<NUMBER>'... |
class BengaliCorpus():
punctuations: str = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~।ঃ'
letters: str = 'অআইঈউঊঋএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহড়ঢ়য়ৎংঃঁ'
digits: str = '০১২৩৪৫৬৭৮৯'
vowels: str = 'া ি ী ু ৃ ে ৈ ো ৌ'
stopwords: List[str] = bengali_stopwords
|
def _read_corpus(files: List[str], tokenizer=None):
for (i, file) in tqdm(enumerate(files)):
with open(file) as f:
text = f.read()
if tokenizer:
tokens = tokenizer(text)
else:
tokens = default_tokenizer.tokenize(text)
(yield g... |
class BengaliDoc2vec():
def __init__(self, model_path: str='', tokenizer: Callable=None):
if ((model_path == '') or (model_path == ModelTypeEnum.NEWS_DOC2VEC)):
model_path = download_model(ModelTypeEnum.NEWS_DOC2VEC)
if (model_path == ModelTypeEnum.WIKI_DOC2VEC):
model_pat... |
class BengaliDoc2vecTrainer():
def __init__(self, tokenizer: Callable=None):
self.tokenizer = tokenizer
def train(self, text_files, checkpoint_path='ckpt', vector_size=100, min_count=2, epochs=10):
"Train doc2vec with custom text files\n\n Args:\n text_files (str): path con... |
class BengaliFasttext():
def __init__(self, model_path: str=''):
if (not model_path):
model_path = download_model(ModelTypeEnum.FASTTEXT)
self.model = fasttext.load_model(model_path)
def get_word_vector(self, word: str) -> np.ndarray:
'generate word vector from given inpu... |
class FasttextTrainer():
def train(self, data, model_name, epoch, lr=0.05, dim=300, ws=5, minCount=5, minn=3, maxn=6, neg=5, wordNgrams=1, loss='ns', bucket=2000000, thread=(multiprocessing.cpu_count() - 1)):
'train fasttext with raw text data\n\n Args:\n data (str): raw text data path\... |
class BengaliGlove():
def __init__(self, glove_vector_path: str=''):
if (not glove_vector_path):
glove_vector_path = download_model(ModelTypeEnum.GLOVE)
self.embedding_dict = self._get_embedding_dict(glove_vector_path)
def get_word_vector(self, word: str) -> np.ndarray:
w... |
class BengaliWord2Vec():
def __init__(self, model_path: str=''):
if (not model_path):
model_path = download_model(ModelTypeEnum.WORD2VEC)
self.model = Word2Vec.load(model_path)
def get_word_vector(self, word: str) -> np.ndarray:
vector = self.model.wv[word]
return... |
class MyCorpus():
'An iterator that yields sentences (lists of str).\n We used NLTKTokenizer from bnlp to tokenize sentence words\n '
def __init__(self, data_path):
self.data_path = data_path
self.bnltk = NLTKTokenizer()
def __iter__(self):
for line in open(self.data_path):... |
class Word2VecTraining():
def train(self, data_path, model_name, vector_name, vector_size=100, alpha=0.025, min_alpha=0.0001, sg=0, hs=0, negative=5, ns_exponent=0.75, window=5, min_count=5, max_vocab_size=None, workers=3, epochs=5, sample=0.001, cbow_mean=1, compute_loss=True, callbacks=()):
'train beng... |
class BengaliNER():
def __init__(self, model_path: str='', tokenizer: Callable=None):
if (not model_path):
model_path = download_model('NER')
self.model = load_pickle_model(model_path)
self.tokenizer = (tokenizer if tokenizer else BasicTokenizer())
def tag(self, text: str... |
class BengaliPOS():
def __init__(self, model_path: str='', tokenizer: Callable=None):
if (not model_path):
model_path = download_model('POS')
self.model = load_pickle_model(model_path)
self.tokenizer = (tokenizer if tokenizer else BasicTokenizer())
def tag(self, text: str... |
class CRFTaggerTrainer():
def train(self, model_name, train_data, test_data, average='micro'):
(X_train, y_train) = transform_to_dataset(train_data)
(X_test, y_test) = transform_to_dataset(test_data)
print(len(X_train))
print(len(X_test))
print('Training Started........')
... |
def convert_to_unicode(text):
"Converts `text` to Unicode (if it's not already), assuming utf-8 input."
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Uns... |
def whitespace_tokenize(text: str) -> List[str]:
'Runs basic whitespace cleaning and splitting on a piece of text.'
text = text.strip()
if (not text):
return []
tokens = text.split()
return tokens
|
def _is_punctuation(char):
'Checks whether `chars` is a punctuation character.'
cp = ord(char)
if (((cp >= 33) and (cp <= 47)) or ((cp >= 58) and (cp <= 64)) or ((cp >= 91) and (cp <= 96)) or ((cp >= 123) and (cp <= 126))):
return True
cat = unicodedata.category(char)
if cat.startswith('P'... |
class BasicTokenizer():
'Runs basic tokenization (punctuation splitting, lower casing, etc.).'
def __call__(self, text: str) -> List[str]:
return self.tokenize(text)
def tokenize(self, text: str) -> List[str]:
'Tokenizes a piece of text.'
text = convert_to_unicode(text)
t... |
class NLTKTokenizer():
def word_tokenize(self, text: str) -> List[str]:
text = text.replace('.', DUMMYTOKEN)
text = text.replace('।', '.')
tokens = nltk.word_tokenize(text)
new_tokens = []
for token in tokens:
token = token.replace('.', '।')
token =... |
class SentencepieceTokenizer():
def __init__(self, model_path: str=''):
if (not model_path):
model_path = download_model(ModelTypeEnum.SENTENCEPIECE)
self.model = bsp.SentencePieceProcessor()
self.model.Load(model_path)
def tokenize(self, text: str) -> List[str]:
... |
class SentencepieceTrainer():
def __init__(self, data, vocab_size, model_prefix):
self.data = data
self.vocab_size = vocab_size
self.model_prefix = model_prefix
def train(self):
train_args = ((((('--model_prefix=' + self.model_prefix) + ' --input=') + self.data) + ' --vocab_s... |
class ModelTypeEnum():
NER = 'NER'
POS = 'POS'
SENTENCEPIECE = 'SPM'
FASTTEXT = 'FASTTEXT'
GLOVE = 'GLOVE'
NEWS_DOC2VEC = 'NEWS_DOC2VEC'
WIKI_DOC2VEC = 'WIKI_DOC2VEC'
WORD2VEC = 'WORD2VEC'
|
class ModelInfo():
'Class for various model name and their URLs\n '
__url_dict = {'NER': {'name': 'bn_ner.pkl', 'type': 'single', 'url': 'https://raw.githubusercontent.com/sagorbrur/bnlp/master/model/bn_ner.pkl'}, 'POS': {'name': 'bn_pos.pkl', 'type': 'single', 'url': 'https://raw.githubusercontent.com/sag... |
def _create_dirs(model_name: str) -> str:
'Create directories for downloading models\n\n Args:\n model_name (str): Name of the model\n\n Returns:\n str: Absolute path where model can be downloaded\n '
model_dir = os.path.join(os.path.expanduser('~'), 'bnlp', 'models')
os.makedirs(mo... |
def _unzip_file(zip_file_path: str, unzip_dir: str='') -> None:
'Function to extract archives in .zip format\n\n Args:\n zip_file_path (str): Path of archive to be extracted\n unzip_dir (str, optional): Directory where archive will be extracted. Defaults to "".\n\n Raises:\n zip_error: ... |
def _download_file(file_url: str, file_path: str) -> str:
'Function to download file\n\n Args:\n file_url (str): URL of the file\n file_path (str): Path where file will be downloaded\n\n Raises:\n network_error: Download related error\n\n Returns:\n str: Path where the file is... |
def _download_zip_model(model_url: str, model_path: str) -> str:
'Download and extract model archive and return extracted path.\n\n Args:\n model_url (str): URL of the model\n model_path (str): Path where model will be downloaded\n\n Returns:\n str: Path where model is extracted after d... |
def download_model(name: str) -> str:
'Download and extract model if necessary\n\n Args:\n name (str): _description_\n\n Returns:\n str: _description_\n '
(model_name, model_type, model_url) = ModelInfo.get_model_info(name)
model_path = _create_dirs(model_name)
if (model_type ==... |
def download_all_models() -> None:
'Download and extract all available models for BNLP\n '
model_keys = ModelInfo.get_all_models()
for model_key in model_keys:
download_model(model_key)
|
def features(sentence, index):
'sentence: [w1, w2, ...], index: the index of the word'
return {'word': sentence[index], 'is_first': (index == 0), 'is_last': (index == (len(sentence) - 1)), 'is_capitalized': (sentence[index][0].upper() == sentence[index][0]), 'is_all_caps': (sentence[index].upper() == sentence... |
def transform_to_dataset(tagged_sentences):
(X, y) = ([], [])
for tagged in tagged_sentences:
try:
X.append([features(untag(tagged), index) for index in range(len(tagged))])
y.append([tag for (_, tag) in tagged])
except Exception as e:
print(e)
return (X... |
def load_pickle_model(model_path: str) -> CRF:
with open(model_path, 'rb') as pkl_model:
model = pickle.load(pkl_model)
return model
|
class TestDocVec(unittest.TestCase):
def setUp(self):
self.doc2vec = BengaliDoc2vec()
self.document = 'রাষ্ট্রবিরোধী ও উসকানিমূলক বক্তব্য দেওয়ার অভিযোগে গাজীপুরের গাছা থানায় ডিজিটাল নিরাপত্তা আইনে করা মামলায় আলোচিত ‘শিশুবক্তা’ রফিকুল ইসলামের বিরুদ্ধে অভিযোগ গঠন করেছেন আদালত। ফলে মামলার আনুষ্ঠানিক... |
class TestBengaliFasttext(unittest.TestCase):
def setUp(self):
self.fasttext = BengaliFasttext()
def test_generate_word_vector(self):
word = 'আমি'
vector = self.fasttext.generate_word_vector(word)
self.assertEqual(vector.shape, (300,))
|
class TestBengaliGlove(unittest.TestCase):
def setUp(self):
self.glove = BengaliGlove()
def test_get_word_vector(self):
word = 'আমি'
vector = self.glove.get_word_vector(word)
self.assertEqual(vector.shape, (100,))
|
class TestBengaliWord2Vec(unittest.TestCase):
def setUp(self):
self.word2vec = BengaliWord2Vec()
def test_get_word_vector(self):
word = 'আমি'
vector = self.word2vec.get_word_vector(word)
self.assertEqual(vector.shape, (100,))
def test_get_most_similar_words(self):
... |
class TestBengaliNER(unittest.TestCase):
def setUp(self):
self.ner = BengaliNER()
def test_tag(self):
text = 'সে ঢাকায় থাকে।'
tags = self.ner.tag(text)
self.assertEqual(tags, [('সে', 'O'), ('ঢাকায়', 'S-LOC'), ('থাকে', 'O')])
|
class TestBengaliNER(unittest.TestCase):
def setUp(self):
self.ner = BengaliPOS()
def test_tag(self):
text = 'আমি ভাত খাই।'
tags = self.ner.tag(text)
self.assertEqual(tags, [('আমি', 'PPR'), ('ভাত', 'NC'), ('খাই', 'VM'), ('।', 'PU')])
|
class TestBasicTokenizer(unittest.TestCase):
def setUp(self):
self.basic_tokenizer = BasicTokenizer()
def test_basic_tokenizer_with_sample_bangla_text(self):
text = 'আমি ভাত খাই।'
tokens = self.basic_tokenizer(text)
self.assertEqual(tokens, ['আমি', 'ভাত', 'খাই', '।'])
de... |
class TestBasicTokenizer(unittest.TestCase):
def setUp(self):
self.nltk_tokenizer = NLTKTokenizer()
def test_nltk_word_tokenizer_with_sample_bangla_text(self):
text = 'আমি ভাত খাই।'
tokens = self.nltk_tokenizer.word_tokenize(text)
self.assertEqual(tokens, ['আমি', 'ভাত', 'খাই'... |
class TestSentencepieceTokenizer(unittest.TestCase):
def setUp(self):
self.bsp = SentencepieceTokenizer()
self.input_text = 'সে বাজারে যায়।'
self.input_text_gt_tokens = ['▁সে', '▁বাজারে', '▁যায়', '।']
def test_sentencepiece_tokenizer_with_input_bangla_text_and_trained_model(self):
... |
def compute_intermediate_size(n):
return ((int((math.ceil(((n * 8) / 3)) + 255)) // 256) * 256)
|
def read_json(path):
with open(path, 'r') as f:
return json.load(f)
|
def write_json(text, path):
with open(path, 'w') as f:
json.dump(text, f)
|
def write_model(model_path, input_base_path, model_size):
assert (model_size in NUM_SHARDS)
os.makedirs(model_path, exist_ok=True)
params = read_json(os.path.join(input_base_path, 'params.json'))
num_shards = NUM_SHARDS[model_size]
n_layers = params['n_layers']
n_heads = params['n_heads']
... |
def write_tokenizer(tokenizer_path, input_tokenizer_path):
os.makedirs(tokenizer_path, exist_ok=True)
write_json({}, os.path.join(tokenizer_path, 'special_tokens_map.json'))
write_json({'bos_token': '', 'eos_token': '', 'model_max_length': int(1e+30), 'tokenizer_class': 'LlamaTokenizer', 'unk_token': ''},... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', help='Location of LLaMA weights, which contains tokenizer.model and model folders')
parser.add_argument('--model_size', choices=['7B', '13B', '30B', '65B', 'tokenizer_only'])
parser.add_argument('--output_dir', help='Loc... |
def encode_prompt(prompt_instructions):
'Encode multiple prompt instructions into a single string.'
prompt = (open('./prompt.txt').read() + '\n')
for (idx, task_dict) in enumerate(prompt_instructions):
(instruction, input, output) = (task_dict['instruction'], task_dict['input'], task_dict['output'... |
def post_process_gpt3_response(num_prompt_instructions, response):
if (response is None):
return []
raw_instructions = (f'{(num_prompt_instructions + 1)}. Instruction:' + response['text'])
raw_instructions = re.split('###', raw_instructions)
instructions = []
for (idx, inst) in enumerate(r... |
def find_word_in_string(w, s):
return re.compile('\\b({0})\\b'.format(w), flags=re.IGNORECASE).search(s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.