repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/preprocess.py
# coding=utf-8
15
7
14
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/universal_datamodule/universal_datamodule.py
from pytorch_lightning import LightningDataModule from typing import Optional from torch.utils.data import DataLoader, DistributedSampler from fengshen.models.megatron import mpu def get_consume_samples(data_model: LightningDataModule) -> int: if hasattr(data_model.trainer.lightning_module, 'consumed_samples'): ...
7,829
40.210526
112
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/universal_datamodule/universal_sampler.py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
5,181
40.126984
89
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/universal_datamodule/__init__.py
from .universal_datamodule import UniversalDataModule from .universal_sampler import PretrainingSampler, PretrainingRandomSampler __all__ = ['UniversalDataModule', 'PretrainingSampler', 'PretrainingRandomSampler']
215
42.2
83
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/mmap_dataloader/mmap_index_dataset.py
import numpy as np import torch from typing import List from torch.utils.data import Dataset class MMapIndexDataset(Dataset): # datapaths 是所有的内存映射文件的路径 # input_tensor_name 是输入的tensor的名字 例如 ['input_ids'] 会存储在对应的文件里面 def __init__(self, datapaths: List[str], input_tensor_name: List[str]): dict_idx_fp...
1,815
32.62963
81
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/mmap_dataloader/mmap_datamodule.py
from typing import Optional from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader from fengshen.data.mmap_index_dataset import MMapIndexDataset class MMapDataModule(LightningDataModule): @ staticmethod def add_data_specific_args(parent_args): parser = parent_args.ad...
2,461
34.681159
94
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/dreambooth_datasets/dreambooth_datasets.py
# -*- encoding: utf-8 -*- ''' Copyright 2022 The International Digital Economy Academy (IDEA). CCNL team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.o...
6,386
33.711957
118
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/t5_dataloader/t5_datasets.py
# coding=utf8 import json from torch.utils.data import Dataset, DataLoader from tqdm import tqdm from transformers import BertTokenizer, MT5Config, MT5Tokenizer, BatchEncoding import torch import pytorch_lightning as pl import numpy as np from itertools import chain import sys sys.path.append('../../') def compute_in...
25,946
45.087034
127
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/t5_dataloader/t5_gen_datasets.py
# -*- encoding: utf-8 -*- ''' @File : t5_gen_datasets.py @Time : 2022/10/24 19:29 @Author : He Junqing @Version : 1.0 @Contact : [email protected] @License : (C)Copyright 2022-2023, CCNL-IDEA ''' from logging import exception from transformers import ( BertTokenizer, MT5Config, MT5To...
13,701
33.954082
101
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/taiyi_stable_diffusion_datasets/taiyi_datasets.py
from torch.utils.data import Dataset, ConcatDataset import os from concurrent.futures import ProcessPoolExecutor import pandas as pd def add_data_args(parent_args): parser = parent_args.add_argument_group('taiyi stable diffusion data args') # 支持传入多个路径,分别加载 parser.add_argument( "--datasets_path", t...
6,417
35.885057
117
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/task_dataloader/medicalQADataset.py
# coding=utf8 import os import pytorch_lightning as pl from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from transformers import AutoTokenizer class GPT2QADataset(Dataset): ''' Dataset Used for yuyuan medical qa task. Just surpport small datasets, when deal with large datasets it may...
5,285
37.304348
102
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/task_dataloader/task_datasets.py
# coding=utf8 from torch.utils.data import Dataset, DataLoader from tqdm import tqdm from transformers import AutoTokenizer import json import torch import pytorch_lightning as pl import os class AbstractCollator: """ collector for summary task """ def __init__(self, tokenizer, max_enc_length, max_de...
7,832
36.84058
114
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/task_dataloader/__init__.py
# coding=utf-8 from .task_datasets import LCSTSDataModel, LCSTSDataset __all__ = ['LCSTSDataModel', 'LCSTSDataset']
116
28.25
55
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/hubert/hubert_dataset.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import logging import os import sys from typing import Any, List, Optional, Union import numpy as np import torch import to...
13,124
35.256906
86
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/clip_dataloader/flickr.py
from torch.utils.data import Dataset, DataLoader from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ CenterCrop from transformers import BertTokenizer import pytorch_lightning as pl from PIL import Image import os class flickr30k_CNA(Dataset): def _...
3,812
34.971698
112
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/bart_dataset.py
"""BART Style dataset. Modified from fairseq.""" import numpy as np import torch import math import re from fengshen.data.megatron_dataloader.dataset_utils import ( get_samples_mapping ) class BartDataset(torch.utils.data.Dataset): def __init__(self, name, indexed_dataset, data_prefix, num_...
18,396
40.434685
103
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/dataset_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors, and NVIDIA. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
30,965
38.247148
103
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/utils.py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
903
35.16
74
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/bert_dataset.py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
8,121
40.228426
94
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/blendable_dataset.py
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
2,208
32.984615
78
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/__init__.py
from . import indexed_dataset
30
14.5
29
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/megatron_dataloader/indexed_dataset.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # copied from fairseq/fairseq/data/indexed_dataset.py # Removed IndexedRawTextDataset since it relied on Fairseq dictionary # other slight mo...
18,859
31.1843
80
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/data_utils/sop_utils.py
# copy from megatron def get_a_and_b_segments(sample, np_rng): """Divide sample into a and b segments.""" # Number of sentences in the sample. n_sentences = len(sample) # Make sure we always have two sentences. assert n_sentences > 1, 'make sure each sample has at least two sentences.' # Firs...
912
26.666667
79
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/data_utils/common_utils.py
def padding_to_maxlength(ids, max_length, pad_id): cur_len = len(ids) len_diff = max_length - len(ids) return ids + [pad_id] * len_diff, [1] * cur_len + [0] * len_diff
180
35.2
68
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/data_utils/truncate_utils.py
def truncate_segments(tokens_a, tokens_b, len_a, len_b, max_num_tokens, np_rng): """Truncates a pair of sequences to a maximum sequence length.""" # print(len_a, len_b, max_num_tokens) assert len_a > 0 if len_a + len_b <= max_num_tokens: return False while len_a + len_b > max_num_tokens: ...
579
28
80
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/data_utils/token_type_utils.py
def create_tokens_and_tokentypes(tokens_a, tokens_b, cls_id, sep_id): """Merge segments A and B, add [CLS] and [SEP] and build tokentypes.""" tokens = [] tokentypes = [] # [CLS]. tokens.append(cls_id) tokentypes.append(0) # Segment A. for token in tokens_a: tokens.append(token) ...
639
23.615385
75
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/data_utils/sentence_split.py
import re class ChineseSentenceSplitter(object): def merge_symmetry(self, sentences, symmetry=('“', '”')): # '''合并对称符号,如双引号''' effective_ = [] merged = True for index in range(len(sentences)): if symmetry[0] in sentences[index] and symmetry[1] not in sentences[index]: ...
1,457
39.5
108
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/data_utils/mask_utils.py
import collections import numpy as np MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def is_start_piece(piece): """Check if the current word piece is the starting piece (BERT).""" # When a word has been split into # WordPieces,...
11,400
38.863636
103
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/sequence_tagging_dataloader/sequence_tagging_collator.py
from dataclasses import dataclass from torch.utils.data._utils.collate import default_collate import copy import torch import numpy as np @dataclass class CollatorForLinear: args = None tokenizer = None label2id = None def __call__(self, samples): cls_token = "[CLS]" sep_token = "[SEP...
10,403
36.970803
133
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/sequence_tagging_dataloader/sequence_tagging_datasets.py
from torch.utils.data import Dataset from fengshen.metric.utils_ner import get_entities import os def get_datasets(args): processor = DataProcessor(args.data_dir, args.decode_type) train_data = TaskDataset(processor=processor, mode="train") valid_data = TaskDataset(processor=processor, mode="dev") te...
4,409
37.017241
108
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/bert_dataloader/preprocessing.py
import re import json import multiprocessing from tqdm import tqdm from pathlib import Path from itertools import chain _SPLIT_DATA_PATH = '/data1/datas/wudao_180g' def cut_sent(path): """ 中文分句,默认?、。、!、省略号分句,考虑双引号包裹的句子 采用分割替换的方式 """ path = Path(path) # print(path) save_path = str(Path('/d...
3,724
32.558559
130
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/data/bert_dataloader/load.py
import os import re from pathlib import Path import glob from tqdm import tqdm from contextlib import ExitStack import datasets import multiprocessing from typing import cast, TextIO from itertools import chain import json from concurrent.futures import ProcessPoolExecutor from random import shuffle from pytorch_lightn...
6,756
32.616915
124
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/base.py
_CONFIG_MODEL_TYPE = 'fengshen_model_type' _CONFIG_TOKENIZER_TYPE = 'fengshen_tokenizer_type'
94
30.666667
50
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/test.py
from fengshen.pipelines.text_classification import TextClassificationPipeline import argparse from datasets import load_dataset # 预测 支持批量 # pipe = TextClassificationPipeline( # model='/data/gaoxinyu/pretrained_model/deberta-base-sp', device=-1) # print(pipe(['今天心情不好</s>今天很开心', '今天心情很好</s>今天很开心'])) # 训练 支持各种超参调整 ...
717
33.190476
107
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/test_tagging.py
from fengshen.pipelines.sequence_tagging import SequenceTaggingPipeline import argparse import os total_parser = argparse.ArgumentParser("test") total_parser = SequenceTaggingPipeline.add_pipeline_specific_args(total_parser) args = total_parser.parse_args() args.data_dir="/cognitive_comp/lujunyu/data_zh/NER_Aligned/we...
805
34.043478
112
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/sequence_tagging.py
import torch import torch.nn.functional as F from torch.utils.data._utils.collate import default_collate from dataclasses import dataclass from typing import Dict, List, Union from fengshen.models.tagging_models.bert_for_tagging import BertLinear,BertCrf,BertSpan,BertBiaffine from fengshen.data.sequence_tagging_datalo...
12,608
39.156051
154
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/text_classification.py
import torch from torch.utils.data._utils.collate import default_collate from dataclasses import dataclass from typing import Dict, List from .base import ( _CONFIG_MODEL_TYPE, _CONFIG_TOKENIZER_TYPE) from fengshen.models.roformer import RoFormerForSequenceClassification from fengshen.models.longformer import L...
9,274
38.468085
106
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/tcbert.py
# coding=utf-8 # Copyright 2021 The IDEA Authors. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by a...
5,390
38.350365
116
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/multiplechoice.py
# coding=utf-8 # Copyright 2021 The IDEA Authors. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by a...
7,967
39.653061
116
py
Fengshenbang-LM
Fengshenbang-LM-main/fengshen/pipelines/information_extraction.py
from logging import basicConfig import torch from torch import nn import json from tqdm import tqdm import os import numpy as np from transformers import BertTokenizer import pytorch_lightning as pl from pytorch_lightning import trainer, loggers from transformers import AlbertTokenizer from transformers import AutoCon...
4,151
36.071429
127
py
TFusion
TFusion-master/__init__.py
1
0
0
py
TFusion
TFusion-master/TrackViz/pre_process/market_answer_predict.py
from profile.fusion_param import ctrl_msg, get_fusion_param from train.st_filter import train_tracks from util.file_helper import read_lines import numpy as np from util.serialize import pickle_save def save_market_train_truth(): ctrl_msg['data_folder_path'] = 'market_market-train' fusion_param = get_fusion...
8,645
40.171429
92
py
TFusion
TFusion-master/TrackViz/pre_process/__init__.py
0
0
0
py
TFusion
TFusion-master/TrackViz/profile/fusion_param.py
ctrl_msg = { 'data_folder_path': 'market_market-test', 'cv_num': 0, 'ep': 0, 'en': 0 } update_msg = {} def get_fusion_param(): origin_dict = { 'renew_pid_path': 'data/' + ctrl_msg['data_folder_path'] + '/renew_pid.log', 'renew_ac_path': 'data/' + ctrl_msg['data_folder_path'] + '/r...
3,550
52.80303
130
py
TFusion
TFusion-master/TrackViz/profile/__init__.py
0
0
0
py
TFusion
TFusion-master/TrackViz/post_process/grid_summary.py
from util.file_helper import read_lines, write def avg_acc(grid_eval_path): grid_infos = read_lines(grid_eval_path) before_vision_accs = [0.0, 0.0, 0.0] before_fusion_accs = [0.0, 0.0, 0.0] after_vision_accs = [0.0, 0.0, 0.0] after_fusion_accs = [0.0, 0.0, 0.0] i_cv_cnt = 0 for i, grid_inf...
1,724
44.394737
144
py
TFusion
TFusion-master/TrackViz/post_process/track_prob.py
# coding=utf-8 from util.serialize import pickle_load def binary_search(a, target): # 不同于普通的二分查找,目标是寻找target最适合的index low = 0 high = len(a) - 1 while low <= high: mid = (low + high) // 2 mid_val = a[mid] if mid_val < target: low = mid + 1 elif mid_val > tar...
2,487
36.134328
111
py
TFusion
TFusion-master/TrackViz/post_process/__init__.py
0
0
0
py
TFusion
TFusion-master/TrackViz/util/str_helper.py
def folder(path): final_slash_idx = -1 for i, c in enumerate(path): if c == '/': final_slash_idx = i if final_slash_idx == -1: return path else: return path[: final_slash_idx] if __name__ == '__main__': print(folder('data/top10/test.txt'))
298
20.357143
40
py
TFusion
TFusion-master/TrackViz/util/file_helper.py
import os def write_line(path, content): with open(path, "a+") as dst_file: dst_file.write(content + '\n') def write(path, content): with open(path, "a+") as dst_file: dst_file.write(content) def read_lines(path): with open(path) as f: content = list() while 1: ...
1,627
20.706667
40
py
TFusion
TFusion-master/TrackViz/util/viz.py
import matplotlib.pyplot as plt import seaborn as sns import numpy as np def draw_line(y_s, x_s, y_label, x_label, y_titles, title, line_color=None): # plt.subplots() plt.subplots(figsize=(6, 5)) sns.set(font_scale=2.4) line_styles = ['--', '-'] for i in range(len(y_s)): plt.plot(x_s, y_s[...
1,198
32.305556
106
py
TFusion
TFusion-master/TrackViz/util/__init__.py
0
0
0
py
TFusion
TFusion-master/TrackViz/util/serialize.py
import os import pickle import random def random6(): return random.randint(100000, 999999) def pickle_save(path, obj): try: with open(path, 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', path, e) return ...
493
18
56
py
TFusion
TFusion-master/TrackViz/train/st_estim.py
#coding=utf-8 from random import randint import shutil from profile.fusion_param import ctrl_msg from util.file_helper import read_lines, safe_remove, safe_mkdir from util.serialize import pickle_save from util.str_helper import folder def prepare_rand_folder(fusion_param): rand_predict_path = fusion_param['ren...
3,995
41.063158
120
py
TFusion
TFusion-master/TrackViz/train/st_filter.py
# coding=utf-8 from post_process.track_prob import track_score from profile.fusion_param import get_fusion_param, ctrl_msg from util.file_helper import read_lines, read_lines_and, write, safe_remove from util.serialize import pickle_load import numpy as np import os def smooth_score(c1, c2, time1, time2, camera_delt...
19,506
45.556086
145
py
TFusion
TFusion-master/TrackViz/train/__init__.py
0
0
0
py
TFusion
TFusion-master/TrackViz/ctrl/transfer.py
import os from ctrl.img_st_fusion import init_strict_img_st_fusion from profile.fusion_param import ctrl_msg, get_fusion_param from util.file_helper import safe_mkdir def fusion_dir_prepare(source, target): fusion_data_path = '/home/cwh/coding/TrackViz/data/' fusion_train_dir = fusion_data_path + '/' + sourc...
6,036
46.535433
135
py
TFusion
TFusion-master/TrackViz/ctrl/__init__.py
0
0
0
py
TFusion
TFusion-master/TrackViz/ctrl/img_st_fusion.py
#coding=utf-8 import shutil import os from profile.fusion_param import get_fusion_param, ctrl_msg from train.st_estim import get_predict_delta_tracks, prepare_rand_folder, prepare_diff_folder from train.st_filter import fusion_st_img_ranker, fusion_st_gallery_ranker # need to run on src directory from util.file_help...
8,198
39.191176
107
py
TFusion
TFusion-master/rank-reid/rank_reid.py
import sys from baseline.evaluate import market_result_eval, grid_result_eval from pretrain.eval import train_pair_predict,test_pair_predict, train_rank_predict, test_rank_predict from transfer.simple_rank_transfer import rank_transfer_2dataset def get_source_target_info(source, target): source_model_path = '/ho...
5,831
52.018182
160
py
TFusion
TFusion-master/rank-reid/transfer/__init__.py
0
0
0
py
TFusion
TFusion-master/rank-reid/transfer/simple_rank_transfer.py
import os import utils.cuda_util import numpy as np from keras import Input from keras import backend as K from keras.applications.resnet50 import preprocess_input, ResNet50 from keras.callbacks import EarlyStopping, ReduceLROnPlateau from keras.engine import Model from keras.layers import Flatten, Lambda, Dense, Conv2...
11,654
43.484733
136
py
TFusion
TFusion-master/rank-reid/baseline/evaluate.py
from __future__ import division, print_function, absolute_import import os import numpy as np import tensorflow as tf from keras.applications.resnet50 import preprocess_input from keras.backend.tensorflow_backend import set_session from keras.models import Model from keras.preprocessing import image from utils.file_...
7,555
31.568966
96
py
TFusion
TFusion-master/rank-reid/baseline/__init__.py
0
0
0
py
TFusion
TFusion-master/rank-reid/baseline/train.py
from __future__ import division, print_function, absolute_import import os from random import shuffle import numpy as np import tensorflow as tf from keras.applications.resnet50 import ResNet50 from keras.applications.resnet50 import preprocess_input from keras.backend.tensorflow_backend import set_session from keras...
5,745
33.407186
120
py
TFusion
TFusion-master/rank-reid/pretrain/pair_train.py
import os import numpy as np from keras import Input from keras import backend as K from keras.applications.resnet50 import preprocess_input from keras.callbacks import EarlyStopping, ReduceLROnPlateau from keras.engine import Model from keras.layers import Lambda, Dense, Dropout, Flatten from keras.models import load...
10,663
40.173745
121
py
TFusion
TFusion-master/rank-reid/pretrain/eval.py
# coding=utf-8 import os from keras import backend as K from keras.engine import Model from keras.models import load_model from keras.preprocessing import image from baseline.evaluate import train_predict, test_predict, grid_result_eval, market_result_eval from transfer.simple_rank_transfer import cross_entropy_loss ...
4,102
38.07619
108
py
TFusion
TFusion-master/rank-reid/pretrain/__init__.py
0
0
0
py
TFusion
TFusion-master/rank-reid/utils/file_helper.py
import os def write_line(path, content): with open(path, "a+") as dst_file: dst_file.write(content + '\n') def write(path, content): with open(path, "a+") as dst_file: dst_file.write(content) def read_lines(path): with open(path) as f: content = list() while 1: ...
1,627
20.706667
40
py
TFusion
TFusion-master/rank-reid/utils/cuda_util.py
import os from keras.backend import set_session os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "0" import tensorflow as tf config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.6 set_session(tf.Session(config=config))
302
26.545455
64
py
TFusion
TFusion-master/rank-reid/utils/__init__.py
0
0
0
py
hyperopt
hyperopt-master/setup.py
import re import setuptools with open("hyperopt/__init__.py", encoding="utf8") as f: version = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1) if version is None: raise ImportError("Could not find __version__ in hyperopt/__init__.py") setuptools.setup( name="hyperopt", version=versio...
2,132
32.857143
87
py
hyperopt
hyperopt-master/docs/autogen.py
# This file has been taken from Keras' `docs` module found here: # https://github.com/keras-team/keras/blob/master/docs/autogen.py # import re import inspect import os import shutil EXCLUDE = {} PAGES = [ # { # 'page': 'target.md', # 'classes': [ # ], # 'functions': [ # ...
12,407
32.994521
87
py
hyperopt
hyperopt-master/docs/__init__.py
0
0
0
py
hyperopt
hyperopt-master/hyperopt/main.py
#!/usr/bin/env python """ Entry point for bin/* scripts """ from future import standard_library import logging import os from . import utils from .base import SerialExperiment import sys standard_library.install_aliases() logger = logging.getLogger(__name__) try: import cloudpickle as pickler except Exception a...
3,818
26.875912
88
py
hyperopt
hyperopt-master/hyperopt/base.py
"""Base classes / Design The design is that there are three components fitting together in this project: - Trials - a list of documents including at least sub-documents: ['spec'] - the specification of hyper-parameters for a job ['result'] - the result of Domain.evaluate(). Typically includes: ['statu...
34,793
33.552135
93
py
hyperopt
hyperopt-master/hyperopt/tpe.py
""" Graphical model (GM)-based optimization algorithm using Theano """ from past.utils import old_div import logging import time import numpy as np from scipy.special import erf from . import pyll from .pyll import scope from .pyll.stochastic import implicit_stochastic from .base import miscs_to_idxs_vals from .base ...
32,594
33.059561
93
py
hyperopt
hyperopt-master/hyperopt/mongoexp.py
""" Mongodb-based Trials Object =========================== Components involved: - mongo e.g. mongod ... - driver e.g. hyperopt-mongo-search mongo://address bandit_json bandit_algo_json - worker e.g. hyperopt-mongo-worker --loop mongo://address Mongo ===== Mongo (daemon process mongod) is used for IP...
49,421
33.976645
115
py
hyperopt
hyperopt-master/hyperopt/criteria.py
"""Criteria for Bayesian optimization """ from past.utils import old_div import numpy as np import scipy.stats def EI_empirical(samples, thresh): """Expected Improvement over threshold from samples (See example usage in EI_gaussian_empirical) """ improvement = np.maximum(samples - thresh, 0) retu...
2,655
26.381443
78
py
hyperopt
hyperopt-master/hyperopt/rdists.py
""" Extra distributions to complement scipy.stats """ from past.utils import old_div import numpy as np import numpy.random as mtrand import scipy.stats from scipy.stats import rv_continuous # , rv_discrete from scipy.stats._continuous_distns import lognorm_gen as scipy_lognorm_gen class loguniform_gen(rv_continuou...
8,791
30.740072
82
py
hyperopt
hyperopt-master/hyperopt/exceptions.py
""" """ class BadSearchSpace(Exception): """Something is wrong in the description of the search space""" class DuplicateLabel(BadSearchSpace): """A search space included a duplicate label""" class InvalidTrial(ValueError): """Non trial-like object used as Trial""" def __init__(self, msg, obj): ...
1,132
21.66
75
py
hyperopt
hyperopt-master/hyperopt/plotting.py
""" Functions to visualize an Experiment. """ import pickle try: unicode = unicode except NameError: basestring = (str, bytes) else: basestring = basestring # -- don't import this here because it locks in the backend # and we want the unittests to be able to set the backend # TODO: this is really bad ...
7,865
29.488372
119
py
hyperopt
hyperopt-master/hyperopt/pyll_utils.py
from past.builtins import basestring from functools import partial, wraps from .base import DuplicateLabel from .pyll.base import Apply, Literal, MissingArgument from .pyll import scope from .pyll import as_apply def validate_label(f): @wraps(f) def wrapper(label, *args, **kwargs): is_real_string = is...
7,429
28.601594
88
py
hyperopt
hyperopt-master/hyperopt/progress.py
""" Progress is reported using context managers. A progress context manager takes an `initial` and a `total` argument and should yield an object with an `update(n)` method. """ import contextlib from tqdm import tqdm from .std_out_err_redirect_tqdm import std_out_err_redirect_tqdm @contextlib.contextmanager def tq...
898
22.051282
68
py
hyperopt
hyperopt-master/hyperopt/vectorize.py
import sys import numpy as np from .pyll import Apply from .pyll import as_apply from .pyll import dfs from .pyll import toposort from .pyll import scope from .pyll import stochastic stoch = stochastic.implicit_stochastic_symbols def ERR(msg): print("hyperopt.vectorize.ERR", msg, file=sys.stderr) @scope.defi...
16,760
37.619816
88
py
hyperopt
hyperopt-master/hyperopt/utils.py
from future import standard_library from past.builtins import basestring from past.utils import old_div import datetime import numpy as np import logging import os import shutil import sys import uuid import numpy from . import pyll from contextlib import contextmanager standard_library.install_aliases() def _get_ra...
7,894
27.919414
125
py
hyperopt
hyperopt-master/hyperopt/hp.py
""" Support nicer user syntax: from hyperopt import hp hp.uniform('x', 0, 1) """ from .pyll_utils import hp_choice as choice from .pyll_utils import hp_randint as randint from .pyll_utils import hp_pchoice as pchoice from .pyll_utils import hp_uniform as uniform from .pyll_utils import hp_uniformint as uniform...
671
32.6
53
py
hyperopt
hyperopt-master/hyperopt/graph_viz.py
""" Use graphviz's dot language to express the relationship between hyperparamters in a search space. """ from future import standard_library import io from .pyll_utils import expr_to_config standard_library.install_aliases() def dot_hyperparameters(expr): """ Return a dot language specification of a graph...
2,534
30.296296
83
py
hyperopt
hyperopt-master/hyperopt/spark.py
import copy import threading import time import timeit import traceback from hyperopt import base, fmin, Trials from hyperopt.base import validate_timeout, validate_loss_threshold from hyperopt.utils import coarse_utcnow, _get_logger, _get_random_id try: from py4j.clientserver import ClientServer from pyspark...
23,095
39.02773
103
py
hyperopt
hyperopt-master/hyperopt/rand.py
""" Random search - presented as hyperopt.fmin_random """ import logging import numpy as np from . import pyll from .base import miscs_update_idxs_vals logger = logging.getLogger(__name__) def suggest(new_ids, domain, trials, seed): rng = np.random.default_rng(seed) rval = [] for ii, new_id in enumerat...
1,088
26.923077
86
py
hyperopt
hyperopt-master/hyperopt/atpe.py
""" Implements the ATPE algorithm. See https://www.electricbrain.io/blog/learning-to-optimize and https://www.electricbrain.io/blog/optimizing-optimization to learn more """ __authors__ = "Bradley Arsenault" __license__ = "3-clause BSD License" __contact__ = "github.com/hyperopt/hyperopt" from hyperop...
67,630
40.721777
202
py
hyperopt
hyperopt-master/hyperopt/early_stop.py
import logging logger = logging.getLogger(__name__) def no_progress_loss(iteration_stop_count=20, percent_increase=0.0): """ Stop function that will stop after X iteration if the loss doesn't increase Parameters ---------- iteration_stop_count: int search will stop if the loss doesn't im...
1,637
33.851064
111
py
hyperopt
hyperopt-master/hyperopt/std_out_err_redirect_tqdm.py
"""Redirecting writing to tqdm (the progressbar). See here: https://github.com/tqdm/tqdm#redirecting-writing """ import contextlib import sys from tqdm import tqdm class DummyTqdmFile: """Dummy file-like that will write to tqdm.""" file = None def __init__(self, file): self.file = file de...
1,094
22.804348
65
py
hyperopt
hyperopt-master/hyperopt/__init__.py
from .base import STATUS_STRINGS from .base import STATUS_NEW from .base import STATUS_RUNNING from .base import STATUS_SUSPENDED from .base import STATUS_OK from .base import STATUS_FAIL from .base import JOB_STATES from .base import JOB_STATE_NEW from .base import JOB_STATE_RUNNING from .base import JOB_STATE_DONE f...
909
20.666667
44
py
hyperopt
hyperopt-master/hyperopt/fmin.py
from future import standard_library import functools import inspect import logging import os import sys import time from timeit import default_timer as timer import numpy as np from hyperopt import tpe, exceptions from hyperopt.base import validate_timeout, validate_loss_threshold from . import pyll from .utils impo...
22,699
35.495177
109
py
hyperopt
hyperopt-master/hyperopt/algobase.py
""" Support code for new-style search algorithms. """ import copy from collections import deque import numpy as np from . import pyll from .base import miscs_update_idxs_vals __authors__ = "James Bergstra" __license__ = "3-clause BSD License" __contact__ = "github.com/hyperopt/hyperopt" class ExprEvaluator: de...
10,344
39.096899
88
py
hyperopt
hyperopt-master/hyperopt/anneal.py
# TODO: add this to documentation """ Annealing algorithm for hyperopt Annealing is a simple but effective variant on random search that takes some advantage of a smooth response surface. The simple (but not overly simple) code of simulated annealing makes this file a good starting point for implementing new search a...
14,079
34.288221
86
py
hyperopt
hyperopt-master/hyperopt/ipy.py
"""Utilities for Parallel Model Selection with on Author: James Bergstra <[email protected]> Licensed: MIT """ from time import sleep, time import numpy as np from .base import Trials from .base import Domain from .base import JOB_STATE_NEW from .base import JOB_STATE_RUNNING from .base import JOB_STATE_DONE ...
8,500
32.868526
88
py
hyperopt
hyperopt-master/hyperopt/mix.py
import numpy as np def suggest(new_ids, domain, trials, seed, p_suggest): """Return the result of a randomly-chosen suggest function For example to search by sometimes using random search, sometimes anneal, and sometimes tpe, type: fmin(..., algo=partial(mix.suggest, ...
1,089
30.142857
77
py
hyperopt
hyperopt-master/hyperopt/sklearn.py
"""Scikit-learn integration. This class is based on :class:`sklearn.model_selection._search.BaseSearchCV` and inspired by :class:sklearn.model_selection._search_successive_halving.BaseSuccessiveHalving`. """ import numpy as np from sklearn.model_selection._search import is_classifier from sklearn.model_selection._sea...
9,643
34.19708
102
py