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 |
|---|---|---|---|---|---|---|
FragmentVC | FragmentVC-main/preprocess.py | #!/usr/bin/env python3
"""Precompute Wav2Vec features."""
import os
import json
from pathlib import Path
from tempfile import mkstemp
from multiprocessing import cpu_count
import tqdm
import torch
from torch.utils.data import DataLoader
from jsonargparse import ArgumentParser, ActionConfigFile
from models import loa... | 3,318 | 25.766129 | 85 | py |
FragmentVC | FragmentVC-main/models/utils.py | """Useful utilities."""
import math
import torch
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR
from fairseq.models.wav2vec import Wav2Vec2Model
def load_pretrained_wav2vec(ckpt_path):
"""Load pretrained Wav2Vec model."""
ckpt = torch.load(ckpt_path)
model = Wav2Vec2Mod... | 2,140 | 33.532258 | 116 | py |
FragmentVC | FragmentVC-main/models/model.py | """FragmentVC model architecture."""
from typing import Tuple, List, Optional
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .convolutional_transformer import Smoother, Extractor
class FragmentVC(nn.Module):
"""
FragmentVC uses Wav2Vec feature of the source speaker to q... | 4,523 | 29.362416 | 88 | py |
FragmentVC | FragmentVC-main/models/convolutional_transformer.py | """Convolutional transsformer"""
from typing import Optional, Tuple
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module, Dropout, LayerNorm, Conv1d, MultiheadAttention
class Smoother(Module):
"""Convolutional Transformer Encoder Layer"""
def __init__(self, d_model: int, nhe... | 3,526 | 28.889831 | 84 | py |
FragmentVC | FragmentVC-main/models/__init__.py | from .model import FragmentVC
from .utils import *
| 51 | 16.333333 | 29 | py |
FragmentVC | FragmentVC-main/data/intra_speaker_dataset.py | """Dataset for reconstruction scheme."""
import json
import random
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import torch
from tqdm import tqdm
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
class IntraSpeakerDataset(Dataset):
"""Dataset for rec... | 4,148 | 31.928571 | 84 | py |
FragmentVC | FragmentVC-main/data/utils.py | """Utilities for data manipulation."""
from typing import Union
from pathlib import Path
import librosa
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from scipy.signal import lfilter
matplotlib.use("Agg")
def load_wav(
audio_path: Union[str, Path], sample_rate: int, trim: bool = Fal... | 3,008 | 31.010638 | 82 | py |
FragmentVC | FragmentVC-main/data/preprocess_dataset.py | """Precompute Wav2Vec features and spectrograms."""
from copy import deepcopy
from pathlib import Path
import torch
from librosa.util import find_files
import sox
from .utils import load_wav, log_mel_spectrogram
class PreprocessDataset(torch.utils.data.Dataset):
"""Prefetch audio data for preprocessing."""
... | 2,354 | 26.068966 | 87 | py |
FragmentVC | FragmentVC-main/data/__init__.py | from .preprocess_dataset import PreprocessDataset
from .intra_speaker_dataset import IntraSpeakerDataset, collate_batch
from .utils import *
| 141 | 34.5 | 69 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/utils.py | # coding=utf-8
# Copyleft 2019 Project LXRT
import sys
import csv
import base64
import time
import torch
import numpy as np
from tqdm import tqdm
csv.field_size_limit(sys.maxsize)
FIELDNAMES = ["img_id", "img_h", "img_w", "objects_id", "objects_conf",
"attrs_id", "attrs_conf", "num_boxes", "boxes", "fea... | 9,752 | 38.646341 | 138 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/param.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import argparse
import random
import numpy as np
import torch
import logging
logging.basicConfig(level=logging.INFO)
def get_optimizer(optim):
# Bind the optimizer
if optim == 'rms':
print("Optimizer: Using RMSProp")
optimizer = torch.optim.RMSpro... | 6,424 | 38.906832 | 117 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tools/create_open_image_data_lxmert_style.py | #{'img_id': 'COCO_train2014_000000318556', 'labelf': {'vqa': [{'no': 1}, {'yes': 1}, {'no': 1}, {'blue': 1, 'blue and white': 0.3}]}, 'sentf': {'mscoco': ['A very clean and well decorated empty bathroom', 'A blue and white bathroom with butterfly themed wall tiles.', 'A bathroom with a border of butterflies and blue pa... | 1,689 | 48.705882 | 610 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tools/sharearray.py | # Copyright 2017 Brendan Shillingford
#
# 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 applicable law or agreed to ... | 15,374 | 35.007026 | 84 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tools/create_cc_data_lxmert_style.py | #{'img_id': 'COCO_train2014_000000318556', 'labelf': {'vqa': [{'no': 1}, {'yes': 1}, {'no': 1}, {'blue': 1, 'blue and white': 0.3}]}, 'sentf': {'mscoco': ['A very clean and well decorated empty bathroom', 'A blue and white bathroom with butterfly themed wall tiles.', 'A bathroom with a border of butterflies and blue pa... | 1,319 | 54 | 610 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tools/convert_nlvr2_lxmert_style.py | #{'img_id': 'COCO_train2014_000000318556', 'labelf': {'vqa': [{'no': 1}, {'yes': 1}, {'no': 1}, {'blue': 1, 'blue and white': 0.3}]}, 'sentf': {'mscoco': ['A very clean and well decorated empty bathroom', 'A blue and white bathroom with butterfly themed wall tiles.', 'A bathroom with a border of butterflies and blue pa... | 1,668 | 45.361111 | 610 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tools/convert_tsv_to_h5.py | import sys
import csv
import base64
import time
import torch
import numpy as np
from src.utils import load_obj_tsv_save_to_h5
load_obj_tsv_save_to_h5(
"data/mscoco_imgfeat/train2014_obj36.tsv",
"data/mscoco_imgfeat/train2014_obj36.h5",
"data/mscoco_imgfeat/train2014_obj36.json",
82783
)
load_obj_t... | 1,165 | 20.592593 | 47 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/pretrain/box.py | import torch
import numpy
import numpy as np
def heuristic_filter(box_a, box_b, image_size, threshhold = 0.15):
# center_mass
box_a_x_center = (box_a[0] + box_a[2]) / 2
box_b_x_center = (box_b[0] + box_b[2]) / 2
box_a_y_center = (box_a[1] + box_a[3]) / 2
box_b_y_center = (box_b[1] + box_b[3]) / 2
... | 7,027 | 40.099415 | 135 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/pretrain/tag_data_utilis.py | import numpy as np
import torch.nn as nn
from param import args
from lxrt.entry import LXRTEncoder
from lxrt.modeling import BertLayerNorm, GeLU
from lxrt.tokenization import BertTokenizer
import torch
import numpy as np
from collections import defaultdict
import numpy
import random
'''
Given that tags will be extensi... | 8,378 | 44.291892 | 152 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/pretrain/text_data.py | import random
from torch.utils.data import Dataset
from lxrt.tokenization import BertTokenizer
import logging
from lxmert_data import InputExample
import json
from param import args
from lxmert_data import InputFeatures, random_word
import os
from src.tools import sharearray
import gc
from tqdm import tqdm
import numpy... | 18,260 | 38.270968 | 182 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/pretrain/qa_answer_table.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import torch
class AnswerTable:
ANS_CONVERT = {
"a man": "man",
"the man": "man",
"a woman": "woman",
"the woman": "woman",
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '... | 13,691 | 34.842932 | 147 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/pretrain/lxmert_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
from collections import defaultdict
import json
import random
import numpy as np
from torch.utils.data import Dataset
import torch
from param import args
from src.pretrain.qa_answer_table import AnswerTable
from src.utils import load_obj_tsv
from copy import deepcopy
impor... | 42,230 | 43.453684 | 630 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/pretrain/lxmert_pretrain.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import collections
import os
import random
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import json
from param import args
from pretrain.lxmert_data import LXMERTDataset, LXMERTTorchDataset, LXMERTEvalu... | 21,642 | 41.189084 | 320 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/symbolic_vocabulary.py | from param import args
class SymbolicVocab:
def __init__(self, object_path, attribute_path, cls_token="[CLS]", sep_token="[SEP]", mask_token="[MASK]", take_fisrt = True):
attributes = []
with open(attribute_path) as f:
for line in f:
attr = line.strip("\n")
... | 1,892 | 30.032787 | 130 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/optimization.py | # coding=utf-8
# Copyright 2019 project LXRT
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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:/... | 8,058 | 42.798913 | 141 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/entry.py | # coding=utf-8
# Copyright 2021 Project Unsupervised VisualBERT
# Copyright 2019 project LXRT.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may... | 11,480 | 37.016556 | 125 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/tokenization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... | 15,388 | 38.560411 | 133 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/modeling.py | # coding=utf-8
# Copyright 2019 project LXRT.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, 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 ... | 69,048 | 45.124916 | 308 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/h5_data.py | import h5py
from copy import deepcopy
import numpy as np
import json
from torch.utils.data import Dataset
import torch
import random
from param import args
from tqdm import tqdm
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import gc
from src.tools import sharearray
import os
def chunks(l... | 17,660 | 44.518041 | 225 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/lxrt/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
import json
import logging
import os
import shutil
import tempfile
from functools import wraps
from hashlib import sha256
import sys
from i... | 8,209 | 32.104839 | 112 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tasks/vqa_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import os
import pickle
import numpy as np
import torch
from torch.utils.data import Dataset
import h5py
from copy import deepcopy
from param import args
from utils import load_obj_tsv
from pretrain.tag_data_utilis import create_tags
from lxrt.tokenization imp... | 10,280 | 34.329897 | 221 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tasks/vqa_model.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import torch.nn as nn
from param import args
from lxrt.entry import LXRTEncoder, convert_sents_to_features_tensors, convert_tags_to_tensorts, pad_np_arrays
from lxrt.modeling import BertLayerNorm, GeLU
from lxrt.tokenization import BertTokenizer
import numpy as np
# Max l... | 2,612 | 34.310811 | 192 | py |
visualbert | visualbert-master/unsupervised_visualbert/src/tasks/vqa.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import os
import collections
import torch
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
import h5py
import pandas as pd
from param import args
from pretrain.qa_answer_table import load_lxmert_qa, load_lxmert_from_sgg_and_lx... | 8,707 | 36.86087 | 125 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/vg_gqa_imgfeat/extract_gqa_image.py | # !/usr/bin/env python
# The root of bottom-up-attention repo. Do not need to change if using provided docker file.
BUTD_ROOT = '/opt/butd/'
import os, sys
sys.path.insert(0, BUTD_ROOT + "/tools")
os.environ['GLOG_minloglevel'] = '2'
import _init_paths
from fast_rcnn.config import cfg, cfg_from_file, cfg_from_list
f... | 6,511 | 35.58427 | 113 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2/nlvr/nlvr2/eval/compute_category_accuracy.py | import json
import numpy as np
import sys
# Preds file
preds = dict()
with open(sys.argv[1]) as infile:
for line in infile:
identifier, assignment = line.strip().split(',')
preds[identifier] = assignment
# Annotations file
sent_to_annot = dict()
categories = set()
with open(sys.argv[2]) as infile... | 1,791 | 29.896552 | 119 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2/nlvr/nlvr2/eval/metrics.py | import json
import sys
# Load the predictions file. Assume it is a CSV.
predictions = { }
for line in open(sys.argv[1]).readlines():
if line:
splits = line.strip().split(",")
# We assume identifiers are in the format "split-####-#-#.png".
identifier = splits[0]
prediction = splits[1]
predictions[... | 1,887 | 30.466667 | 87 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2/nlvr/nlvr2/eval/compute_filtered_accuracy.py | import json
import numpy as np
import sys
# Preds file
preds = dict()
with open(sys.argv[1]) as infile:
for line in infile:
identifier, assignment = line.strip().split(',')
preds[identifier] = assignment
# Labels file
corrects = list()
with open(sys.argv[2]) as infile:
for line in infile:
... | 666 | 24.653846 | 56 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2/nlvr/nlvr2/util/download_images.py | import imagehash
import json
import os
import progressbar
import signal
import socket
import sys
import requests
from PIL import Image
json_file = sys.argv[1]
save_dir = sys.argv[2]
split_name = json_file.split(".")[0]
HEADER = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTM... | 4,183 | 34.457627 | 184 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2/nlvr/nlvr2/data/filter_data.py | import json
import os
def filter_examples(filename, balanced):
with open(filename) as infile:
original_examples = [json.loads(line) for line in infile if line]
pair_labels = dict()
for example in original_examples:
urls = example["left_url"], example["right_url"]
identifier = examp... | 1,912 | 39.702128 | 120 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2/process_raw_data_scripts/process_dataset.py | import json
import os
NLVR2_DATA_ROOT = '../nlvr/nlvr2/data'
split2fname = {
'train': 'train',
'valid': 'dev',
'test': 'test1',
#'hidden': 'test2'
}
for split, fname in split2fname.items():
with open(os.path.join(NLVR2_DATA_ROOT, fname + '.json')) as f:
new_data = []
for i, line i... | 927 | 28.935484 | 67 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/gqa/process_raw_data_scripts/process_data.py | from pathlib import Path
import json
GQA_ROOT = '../'
path = Path(GQA_ROOT + 'data')
split2name = {
'train': 'train',
'valid': 'val',
'testdev': 'testdev',
'test': 'test',
'challenge': 'challenge'
}
for split, name in split2name.items():
with open(path / ("%s_balanced_questions.json" % na... | 822 | 25.548387 | 65 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/gqa/process_raw_data_scripts/process_submit_data.py | from pathlib import Path
import json
GQA_ROOT = '../'
path = Path(GQA_ROOT + 'data')
split2name = {
'submit': 'submission_all_questions.json'
}
for split, name in split2name.items():
with open(path / ("%s" % name)) as f:
data = json.load(f)
new_data = []
for key, datum in data.ite... | 727 | 25.962963 | 60 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/gqa/process_raw_data_scripts/process_data_all.py | from pathlib import Path
import json
GQA_ROOT = '../'
path = Path(GQA_ROOT + 'data')
split2name = {
'train': 'train',
'valid': 'val',
'testdev': 'testdev',
}
for split, name in split2name.items():
new_data = []
if split == 'train':
paths = list((path / 'train_all_questions').iterdir()... | 1,014 | 26.432432 | 62 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/nlvr2_imgfeat/extract_nlvr2_image.py | # !/usr/bin/env python
# The root of bottom-up-attention repo. Do not need to change if using provided docker file.
BUTD_ROOT = '/opt/butd/'
# SPLIT to its folder name under IMG_ROOT
SPLIT2DIR = {
'train': 'train',
'valid': 'dev',
'test': 'test1',
'hidden': 'test2', # Please correct w... | 7,358 | 35.430693 | 113 | py |
visualbert | visualbert-master/unsupervised_visualbert/data/mscoco_imgfeat/extract_coco_image.py | # !/usr/bin/env python
# The root of bottom-up-attention repo. Do not need to change if using provided docker file.
BUTD_ROOT = '/opt/butd/'
# SPLIT to its folder name under IMG_ROOT
SPLIT2DIR = {
'train': 'train2014',
'valid': 'val2014',
'test': 'test2015',
}
import os, sys
sys.path.... | 6,810 | 35.42246 | 113 | py |
visualbert | visualbert-master/visualbert/models/model_wrapper.py | # Handles model training (optimizer), loading, saving
import argparse
import os
import shutil
from copy import deepcopy
import multiprocessing
import numpy as np
import pandas as pd
import torch
from allennlp.common.params import Params
from allennlp.training.learning_rate_schedulers import LearningRateScheduler
from... | 10,127 | 39.674699 | 134 | py |
visualbert | visualbert-master/visualbert/models/model.py | # Modified from VCR.
from typing import Dict, List, Any
import os
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.parallel
from allennlp.data.vocabulary import Vocabulary
from allennlp.models.model import Model
from allennlp.modules import TextFieldEmbedder, Seq2SeqEncoder, FeedFor... | 14,578 | 42.912651 | 215 | py |
visualbert | visualbert-master/visualbert/models/__init__.py |
# You can add more models in this folder. like
# from models.no_question import model
# from models.no_vision_at_all import model
# from models.old_model import model
# from models.bottom_up_top_down import model
# from models.revisiting_vqa_baseline import model
# from models.mlb import model | 295 | 36 | 50 | py |
visualbert | visualbert-master/visualbert/models/train.py | """
Training script. Should be pretty adaptable to whatever.
"""
import argparse
import os
import shutil
from copy import deepcopy
import multiprocessing
import numpy as np
import pandas as pd
import torch
from allennlp.common.params import Params
from allennlp.training.learning_rate_schedulers import LearningRateSche... | 16,973 | 39.901205 | 166 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... | 13,112 | 42.134868 | 139 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/__main__.py | # coding: utf8
def main():
import sys
try:
from .convert_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
except ModuleNotFoundError:
print("pytorch_pretrained_bert can only be used from the commandline to convert TensorFlow models in PyTorch, "
"In that case, i... | 932 | 39.565217 | 137 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/tokenization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# 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/LICENS... | 14,261 | 37.13369 | 133 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/modeling.py | # coding=utf-8
# Modified by Harold. Added VisualBERT.
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance ... | 84,216 | 48.077506 | 259 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/fine_tuning.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, 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 cop... | 27,941 | 42.187017 | 139 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
import os
import logging
import shutil
import tempfile
import json
from urllib.parse import urlparse
from pathlib import Path
from typing ... | 8,021 | 32.425 | 98 | py |
visualbert | visualbert-master/visualbert/pytorch_pretrained_bert/__init__.py | __version__ = "0.4.0"
from .tokenization import BertTokenizer, BasicTokenizer, WordpieceTokenizer
from .modeling import (BertConfig, BertModel, BertForPreTraining,
BertForMaskedLM, BertForNextSentencePrediction,
BertForSequenceClassification, BertForMultipleChoice,
... | 478 | 52.222222 | 76 | py |
visualbert | visualbert-master/visualbert/dataloaders/vcr.py | # Modifed from R2C
"""
Dataloaders for VCR
"""
import json
import pickle
import os
from collections import defaultdict
import numpy as np
import numpy
import torch
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField, ListField, LabelField, SequenceLabelField, ArrayField, MetadataField
fro... | 20,515 | 42.191579 | 168 | py |
visualbert | visualbert-master/visualbert/dataloaders/flickr_dataset.py | import os
from torch.utils.data import Dataset
import numpy as np
import random
import json
from collections import defaultdict
from tqdm import tqdm
import json
import os
import numpy as np
import numpy
import torch
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField, ListField, Label... | 11,696 | 40.626335 | 158 | py |
visualbert | visualbert-master/visualbert/dataloaders/box_utils.py | import os
import random
import numpy as np
import scipy
import warnings
from torchvision.datasets.folder import default_loader
from torchvision.transforms import functional
USE_IMAGENET_PRETRAINED = True
##### Image
def load_image(img_fn):
"""Load the specified image and return a [H,W,3] Numpy array.
"""
... | 2,765 | 35.88 | 119 | py |
visualbert | visualbert-master/visualbert/dataloaders/nlvr_dataset.py | import os
from torch.utils.data import Dataset
import numpy as np
import random
import json
from collections import defaultdict
from tqdm import tqdm
import json
import os
import numpy as np
import numpy
import torch
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField, ListField, Label... | 9,904 | 44.645161 | 196 | py |
visualbert | visualbert-master/visualbert/dataloaders/bert_field.py | from typing import Dict, List, Optional
import textwrap
from overrides import overrides
from spacy.tokens import Token as SpacyToken
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.data.fields.sequence_field import SequenceField
from allennlp.data.tokenizers.token import Token
from al... | 8,295 | 40.273632 | 119 | py |
visualbert | visualbert-master/visualbert/dataloaders/vcr_data_utils.py | # This is adapted data/get_bert_embedding/from vcr_loader.py from R2C. Renamed to make
import json
from collections import defaultdict
from tqdm import tqdm
from .bert_data_utils import InputExample, InputFeatures
GENDER_NEUTRAL_NAMES = ['Casey', 'Riley', 'Jessie', 'Jackie', 'Avery', 'Jaime', 'Peyton', 'Kerry', 'Jo... | 7,436 | 42.747059 | 204 | py |
visualbert | visualbert-master/visualbert/dataloaders/vqa_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
from torch.utils.data import Dataset
import numpy as np
from copy import deepcopy
import torch
from torch.util... | 14,744 | 41.615607 | 184 | py |
visualbert | visualbert-master/visualbert/dataloaders/bert_data_utils.py | # Functions to convert raw strings into BERT input feature (InputFeatures' class method)
# Some functions for reading image features
# To take care of padding, we will use AllenNLP's Field;
# Caveat: we pad sequences with zero with one exception: BERT's pre-training language model objective mask's padding should be -1... | 21,319 | 39.378788 | 130 | py |
visualbert | visualbert-master/visualbert/dataloaders/__init__.py | 0 | 0 | 0 | py | |
visualbert | visualbert-master/visualbert/dataloaders/coco_dataset.py | import os
import random
import json
from collections import defaultdict
from tqdm import tqdm
import numpy as np
import numpy
import torch
from torch.utils.data import Dataset
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField, ListField, LabelField, SequenceLabelField, ArrayField, Meta... | 21,482 | 45.600868 | 205 | py |
visualbert | visualbert-master/visualbert/dataloaders/mask_utils.py | import numpy as np
import matplotlib
from matplotlib import path
matplotlib.use('agg')
def _spaced_points(low, high,n):
""" We want n points between low and high, but we don't want them to touch either side"""
padding = (high-low)/(n*2)
return np.linspace(low + padding, high-padding, num=n)
def make_mask... | 1,253 | 31.153846 | 93 | py |
visualbert | visualbert-master/visualbert/dataloaders/flickr_ban/utils.py | # Copied from https://github.com/jnhwkim/ban-vqa
"""
This code is extended from Hengyuan Hu's repository.
https://github.com/hengyuan-hu/bottom-up-attention-vqa
"""
from __future__ import print_function
import errno
import os
import re
import collections
import numpy as np
import operator
import functools
from PIL imp... | 9,306 | 29.817881 | 107 | py |
visualbert | visualbert-master/visualbert/dataloaders/flickr_ban/dataset.py | # Modified from https://github.com/jnhwkim/ban-vqa
"""
This code is modified from Hengyuan Hu's repository.
https://github.com/hengyuan-hu/bottom-up-attention-vqa
"""
from __future__ import print_function
import os
import json
import _pickle as cPickle
import pickle
import numpy as np
from visualbert.dataloaders.flick... | 23,011 | 35.8192 | 149 | py |
visualbert | visualbert-master/visualbert/utils/pytorch_misc.py | """
Question relevance model
"""
# Make stuff
import os
import re
import shutil
import time
import numpy as np
import pandas as pd
import torch
from allennlp.common.util import START_SYMBOL, END_SYMBOL
from allennlp.nn.util import device_mapping
from allennlp.training.trainer import move_optimizer_to_cuda
from torch.... | 15,975 | 38.156863 | 122 | py |
visualbert | visualbert-master/visualbert/utils/detector.py | """
ok so I lied. it's not a detector, it's the resnet backbone
"""
import torch
import torch.nn as nn
import torch.nn.parallel
from torchvision.models import resnet
from utils.pytorch_misc import Flattener
import torch.utils.model_zoo as model_zoo
#from config_vcr import USE_IMAGENET_PRETRAINED
from utils.pytorch_m... | 6,108 | 41.131034 | 139 | py |
visualbert | visualbert-master/visualbert/utils/__init__.py | 0 | 0 | 0 | py | |
visualbert | visualbert-master/visualbert/utils/get_image_features/get_mask.py | #!/usr/bin/env python2
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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 ... | 12,823 | 31.383838 | 107 | py |
visualbert | visualbert-master/visualbert/utils/get_image_features/get_mask_utils.py | # Modified by Harold. Courtesy of the author of VCR
"""
Detect the images from a dataframe, saving masks to a json.
"""
from collections import defaultdict
import cv2 # NOQA (Must import before importing caffe2 due to bug in cv2)
import logging
import os
import time
from caffe2.python import workspace
from detectro... | 14,915 | 38.989276 | 268 | py |
visualbert | visualbert-master/visualbert/utils/get_image_features/extract_image_features_nlvr.py | # Modified by Harold
#!/usr/bin/env python2
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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
#... | 11,369 | 31.485714 | 107 | py |
skccm | skccm-master/setup.py | import os
from distutils.core import setup
# Get version and release info, which is all stored in shablona/version.py
ver_file = os.path.join('skccm', 'version.py')
with open(ver_file) as f:
exec(f.read())
opts = dict(name=NAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
... | 804 | 26.758621 | 74 | py |
skccm | skccm-master/docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# skccm documentation build configuration file, created by
# sphinx-quickstart on Tue Jan 24 16:48:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... | 5,151 | 28.953488 | 79 | py |
skccm | skccm-master/skccm/data.py | #
# Data for analyzing causality.
# By Nick Cortale
#
# Paper:
# Detecting Causality in Complex Ecosystems
# George Sugihara et al. 2012
#
# Thanks to Kenneth Ells and Dylan McNamara
#
import numpy as np
from numpy import genfromtxt
from scipy import integrate
def coupled_logistic(rx1, rx2, b12, b21, ts_length,rando... | 5,461 | 24.170507 | 79 | py |
skccm | skccm-master/skccm/skccm.py | #
# Data for analyzing causality.
# By Nick Cortale
#
# Classes:
# ccm
# embed
#
# Paper:
# Detecting Causality in Complex Ecosystems
# George Sugihara et al. 2012
#
# Thanks to Kenneth Ells and Dylan McNamara
#
# Notes:
# Originally I thought this can be made way faster by only calculting the
# distances once and th... | 9,086 | 25.80531 | 86 | py |
skccm | skccm-master/skccm/utilities.py | #
# Metrics for scoring predictions from CCM
#
import numpy as np
from scipy import stats as stats
def corrcoef(preds, actual):
"""Correlation Coefficient between predicted and actual values.
Parameters
----------
preds : 1d array
Predicted values.
actual : 1d array
Actual values ... | 7,238 | 21.481366 | 78 | py |
skccm | skccm-master/skccm/version.py | from os.path import join as pjoin
# Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z"
_version_major = 0
_version_minor = 2
_version_micro = '' # use '' for first of series, number for 1 and above
_version_extra = 'dev'
#_version_extra = '' # Uncomment this for full releases
# Construct ful... | 1,871 | 30.728814 | 76 | py |
skccm | skccm-master/skccm/__init__.py | from .skccm import CCM, Embed
| 30 | 14.5 | 29 | py |
skccm | skccm-master/skccm/paper.py | #
# Data for analyzing causality.
# By Nick Cortale
#
# Classes:
# ccm
# embed
#
# Paper:
# Detecting Causality in Complex Ecosystems
# George Sugihara et al. 2012
#
# Thanks to Kenneth Ells and Dylan McNamara
#
# Notes:
# Originally I thought this can be made way faster by only calculting the
# distances once and t... | 9,583 | 22.093976 | 80 | py |
skccm | skccm-master/skccm/tests/test_utilities.py | import os.path as op
import numpy as np
import numpy.testing as npt
import skccm.utilities as ut
def test_exp_weight():
#ensure it sums to one
X = np.array([ [0.1,0.2,.3,.4],
[.3,.3,.7,.7]])
W = ut.exp_weight(distances)
np.testing.assert_array_almost_equal(np.array([1.,1.]),W.sum(... | 329 | 18.411765 | 73 | py |
skccm | skccm-master/skccm/tests/__init__.py | 0 | 0 | 0 | py | |
skccm | skccm-master/skccm/tests/test_skccm.py | import os.path as op
import numpy as np
import numpy.testing as npt
import skccm as ccm
def test_regression_dist_calc():
X = np.array([
[ 0.3, 0.6],
[ 0.2, 1.4],
[ 1.2, 0.2]])
y = X.sum(axis=1,keepdims=True)
R = edm.Regression()
R.fit(X,y)
R.dist_calc(X)
d = np.arr... | 4,742 | 24.918033 | 78 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/SVDD/linear_EcoSVDD_numerics.py | #Owen Howell, July 15, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#Optimized linear EcoSVDD code
#In case of norm 1 kernel K( x, x) = 1 reduces to FISVDD algorithm: https://arxiv.org/abs/1709.00139
#In paper we focus on kernel functions K(x,x) = 1, however this code works for any kernel function K(x,y)
#This ... | 12,103 | 21.332103 | 114 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/SVDD/linear_EcoSVDD.py | #Owen Howell, July 15, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#Optimized linear EcoSVDD code
#In case of norm 1 kernel K( x, x) = 1 reduces to FISVDD algorithm: https://arxiv.org/abs/1709.00139
#In paper we focus on kernel functions K(x,x) = 1, however this code works for any kernel function K(x,y)
#This ... | 11,814 | 21.6341 | 127 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/MNIST/EcoSVM_MNIST.py | #Owen Howell, July 20, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#This code runs Eco_SVM on MNIST dataset
#Note: This code takes significant computational time (+1 days aprox) , for the plots made in paper each realization was done in parallel
#Note: The memory requirments are also large for full dataset. For... | 15,622 | 22.671212 | 195 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/Nonlinear_SVM/nonlinear_EcoSVM_numerics.py | #Owen Howell, July 20, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#Optimized nonlinear EcoSVM code
#Nothing is precomputed
#Easy online implementation
#Import standard python packages
import numpy as np
import matplotlib.pyplot as plt
import sys
#QP is done with CVXOPT packages
from cvxopt import matrix, s... | 14,890 | 22.711783 | 197 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/Nonlinear_SVM/nonlinear_EcoSVM.py | #Owen Howell, July 20, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#Optimized nonlinear EcoSVM code
#Nothing is precomputed
#Easy online implementation
#Import standard python packages
import numpy as np
import matplotlib.pyplot as plt
import sys
#QP is done with CVXOPT packages
from cvxopt import matrix, ... | 16,212 | 21.240055 | 171 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/Linear_SVM/linear_EcoSVM.py | #Owen Howell, July 15, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#Optimized linear EcoSVM code
#Nothing is precomputed
#This code runs EcoSVM algoritm and compares with batch SVM
#Import standard python packages
import numpy as np
import matplotlib.pyplot as plt
import sys
#QP is done with CVXOPT package... | 13,646 | 21.557025 | 140 | py |
EcoSVM | EcoSVM-master/SIcode/python_scripts/Linear_SVM/linear_EcoSVM_numerics.py | #Owen Howell, July 14, 2019
#olh20@bu.edu, https://owenhowell20.github.io
#linear EcoSVM code for numerical experements
#This code produces plots showing how EcoSVM test accuracy and number of support vectors depend on training epoch
#Import standard python packages
import numpy as np
import matplotlib.pyplot as p... | 13,742 | 23.026224 | 171 | py |
TapNet | TapNet-master/tieredImageNet_TapNet/scripts/train_TapNet_tieredImageNet.py | import os
import sys
sys.path.append('../')
import argparse
import numpy as np
import scipy.io as sio
import chainer.functions as F
from chainer import optimizers
from chainer import cuda
from chainer import serializers
from utils.generators import tieredImageNetGenerator
from utils.model_TapNet_ResNet12 import TapN... | 7,175 | 41.714286 | 176 | py |
TapNet | TapNet-master/tieredImageNet_TapNet/utils/generators.py | """
This code based on codes from https://github.com/tristandeleu/ntm-one-shot
"""
import numpy as np
import random
import pickle as pkl
class tieredImageNetGenerator(object):
"""tieredImageNetGenerator
Args:
image_file (str): 'data/train_images.npz' or 'data/test_images.npz' or 'data/val_images.npz' ... | 3,029 | 39.945946 | 114 | py |
TapNet | TapNet-master/tieredImageNet_TapNet/utils/rank_nullspace.py | import numpy as np
from numpy.linalg import svd
import cupy as cp
from cupy.linalg import svd as svd_gpu
from cupy import core
def rank(A, atol=1e-13, rtol=0):
A = np.atleast_2d(A)
s = svd(A, compute_uv=False)
tol = max(atol, rtol*s[0])
rank = int((s >= tol).sum())
return rank
def nullspace(A, to... | 781 | 22.69697 | 60 | py |
TapNet | TapNet-master/tieredImageNet_TapNet/utils/model_TapNet_ResNet12.py | import cupy as cp
import numpy as np
import chainer
import chainer.links as L
import chainer.functions as F
from chainer import cuda
from utils.rank_nullspace import nullspace_gpu
class TapNet(object):
def __init__(self, nb_class_train, nb_class_test, input_size, dimension,
n_shot, gpu=-1):
... | 12,091 | 34.253644 | 123 | py |
TapNet | TapNet-master/tieredImageNet_TapNet/data/__init__.py | 1 | 0 | 0 | py | |
TapNet | TapNet-master/miniImageNet_TapNet/scripts/train_TapNet_miniImageNet.py | import os
import sys
sys.path.append('../')
import argparse
import numpy as np
import scipy.io as sio
import chainer.functions as F
from chainer import optimizers
from chainer import cuda
from chainer import serializers
from utils.generators import miniImageNetGenerator
from utils.model_TapNet_ResNet12 import TapNet... | 7,014 | 40.755952 | 176 | py |
TapNet | TapNet-master/miniImageNet_TapNet/utils/generators.py | """
This code based on codes from https://github.com/tristandeleu/ntm-one-shot
"""
import numpy as np
import random
class miniImageNetGenerator(object):
"""miniImageNetGenerator
Args:
data_file (str): 'data/train.npz' or 'data/test.npz'
nb_classes (int): number of classes in an episode
... | 2,249 | 35.290323 | 96 | py |
TapNet | TapNet-master/miniImageNet_TapNet/utils/rank_nullspace.py | import numpy as np
from numpy.linalg import svd
import cupy as cp
from cupy.linalg import svd as svd_gpu
from cupy import core
def rank(A, atol=1e-13, rtol=0):
A = np.atleast_2d(A)
s = svd(A, compute_uv=False)
tol = max(atol, rtol*s[0])
rank = int((s >= tol).sum())
return rank
def nullspace(A, to... | 781 | 22.69697 | 60 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.