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 |
|---|---|---|---|---|---|---|
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/training/progress_bar.py | from collections import OrderedDict
from numbers import Number
from tqdm import tqdm
from .meters import AverageMeter, RunningAverageMeter, TimeMeter
class ProgressBar:
''''
Takes iterable like train_loader and functions exctly like this iterator if quiet is True. Otherwise it additionally provides a progress... | 1,860 | 41.295455 | 145 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/training/losses.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 torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import L1Loss, MSELoss
class SSIMLoss(nn.Module):
"""
... | 1,886 | 31.534483 | 98 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/training/training_functions.py |
import torch
from torch.nn import L1Loss, MSELoss
# Implementation of SSIMLoss
from functions.training.losses import SSIMLoss
# Apply a center crop on the larger image to the size of the smaller.
#from functions.data.transforms import center_crop_to_smallest
# In order to get access to attributes stored in save_ch... | 3,890 | 37.147059 | 100 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/training/meters.py | import time
import torch
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
if isinstance(val, torch.Tensor):
val = val.item()
... | 1,318 | 19.936508 | 75 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/training/debug_helper.py | import torch
import numpy as np
from typing import Dict, Optional, Sequence, Tuple, Union, List
import os
import matplotlib.pyplot as plt
def save_figure(
x: np.array,
figname: str,
hp_exp: Dict,
save: Optional[bool]=True,):
""""
x must have dimension height,width
"""
if save:
s... | 2,560 | 34.082192 | 75 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/models/unet.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 torch
from torch import nn
from torch.nn import functional as F
class Unet(nn.Module):
"""
PyTorch implementation of a U-Net... | 6,021 | 31.907104 | 113 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/data/mri_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 logging
import os
import pickle
import xml.etree.ElementTree as etree
from pathlib import Path
from typing import Callable, Dict, List... | 8,347 | 36.773756 | 130 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/data/subsample.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 contextlib
from typing import Optional, Sequence, Tuple, Union
import numpy as np
import torch
@contextlib.contextmanager
def temp_... | 9,552 | 43.849765 | 149 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/data/transforms.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.
"""
from typing import Dict, Optional, Sequence, Tuple, Union
import numpy as np
import torch
from packaging import version
from functions.coil_... | 15,090 | 37.595908 | 260 | py |
tinysegmenter | tinysegmenter-master/setup.py | from distutils.core import setup, Command
import os
import sys
sys.path.append('./tinysegmenter')
sys.path.append('./tests')
def read_file(filename):
filepath = os.path.join(
os.path.dirname(os.path.dirname(__file__)), filename)
if os.path.exists(filepath):
return open(filepath).read()
... | 1,437 | 27.76 | 71 | py |
tinysegmenter | tinysegmenter-master/runtests.py | #! /usr/bin/env python
sources = """
eNrMvW2b40aSICaffbaPd3t7ez6v7+zzPRDbfQTVLHRXazQvtNgzLak1295RS1a3ZnqfUi2FIsAq
qEiADYBVRWk1z33yn/MX/wP/FcdbviLBYrWkXWt3ugggXyIjIyMjIiMj/ss/++HNO/Hrf/XOO+/M
N7s2b9pkndaXb/6r1/PxO+8Mh8PoPC/zulhE63xxkZZFs46WVR1hoaI8j9Iyi5p8lS9afIIWLqoy
Wm5LeK7KJomghUGx3lR1Cx8Hg0GWLyPuZ16m67zZpIs8Hk8HEfx... | 231,272 | 74.976675 | 77 | py |
tinysegmenter | tinysegmenter-master/tests/test_tinysegmenter.py | # coding: utf-8
#
# Usage: py.test -v test_tinysegmenter.py
#
# `pip install -r requirements.txt` is required.
from __future__ import unicode_literals
import io
import subprocess
import tinysegmenter
import pytest
def test_ctypes():
ctype = tinysegmenter._ctype
assert ctype('一') == 'M'
assert ctype('〆') ... | 1,220 | 25.543478 | 129 | py |
tinysegmenter | tinysegmenter-master/tinysegmenter/tinysegmenter.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# TinySegmenter 0.1 -- Super compact Japanese tokenizer in Javascript
# (c) 2008 Taku Kudo <taku@chasen.org>
# TinySegmenter is freely distributable under the terms of a new BSD licence.
# For details, see http://lilyx.net/pages/tinysegmenter_licence.txt
# "TinySegmenter... | 18,779 | 63.315068 | 2,039 | py |
tinysegmenter | tinysegmenter-master/tinysegmenter/__init__.py | from .tinysegmenter import tokenize, _ctype
| 44 | 21.5 | 43 | py |
introd | introd-main/cfvqa/engine.py | import os
import math
import time
import torch
import datetime
import threading
import numpy as np
from bootstrap.lib import utils
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
class Engine(object):
"""Contains training and evaluation procedures
"""
def __init__(self):
... | 17,179 | 38.313501 | 121 | py |
introd | introd-main/cfvqa/run.py | import os
import click
import traceback
import torch
import torch.backends.cudnn as cudnn
from bootstrap.lib import utils
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
from cfvqa import engines
from bootstrap import datasets
from bootstrap import models
from bootstrap import optimi... | 4,750 | 36.117188 | 113 | py |
introd | introd-main/cfvqa/cfvqa/__version__.py | __version__ = '0.0.0'
| 22 | 10.5 | 21 | py |
introd | introd-main/cfvqa/cfvqa/run.py | import os
import click
import traceback
import torch
import torch.backends.cudnn as cudnn
from bootstrap.lib import utils
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
from cfvqa import engines
from bootstrap import datasets
from bootstrap import models
from bootstrap import optimi... | 4,750 | 36.117188 | 113 | py |
introd | introd-main/cfvqa/cfvqa/__init__.py | 0 | 0 | 0 | py | |
introd | introd-main/cfvqa/cfvqa/models/networks/rubi.py | import torch
import torch.nn as nn
from block.models.networks.mlp import MLP
from .utils import grad_mul_const # mask_softmax, grad_reverse, grad_reverse_mask,
class RUBiNet(nn.Module):
"""
Wraps another model
The original model must return a dictionnary containing the 'logits' key (predictions before so... | 1,733 | 33 | 105 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/smrl_net.py | from copy import deepcopy
import itertools
import os
import numpy as np
import scipy
import torch
import torch.nn as nn
import torch.nn.functional as F
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
import block
from block.models.networks.vqa_net import factory_text_enc
from block.mod... | 6,297 | 32.679144 | 129 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/cfvqaintrod.py | import torch
import torch.nn as nn
from block.models.networks.mlp import MLP
from .utils import grad_mul_const # mask_softmax, grad_reverse, grad_reverse_mask,
eps = 1e-12
class CFVQAIntroD(nn.Module):
"""
Wraps another model
The original model must return a dictionnary containing the 'logits' key (predi... | 5,384 | 33.741935 | 123 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/utils.py | import torch
def mask_softmax(x, lengths):#, dim=1)
mask = torch.zeros_like(x).to(device=x.device, non_blocking=True)
t_lengths = lengths[:,:,None].expand_as(mask)
arange_id = torch.arange(mask.size(1)).to(device=x.device, non_blocking=True)
arange_id = arange_id[None,:,None].expand_as(mask)
mask[... | 2,326 | 27.036145 | 98 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/cfvqa.py | import torch
import torch.nn as nn
from block.models.networks.mlp import MLP
from .utils import grad_mul_const # mask_softmax, grad_reverse, grad_reverse_mask,
eps = 1e-12
class CFVQA(nn.Module):
"""
Wraps another model
The original model must return a dictionnary containing the 'logits' key (predictions... | 5,174 | 35.702128 | 161 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/factory.py | import sys
import copy
import torch
import torch.nn as nn
import os
import json
from bootstrap.lib.options import Options
from bootstrap.models.networks.data_parallel import DataParallel
from block.models.networks.vqa_net import VQANet as AttentionNet
from bootstrap.lib.logger import Logger
from .rubi import RUBiNet
f... | 4,667 | 29.913907 | 64 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/updn_net.py | from copy import deepcopy
import itertools
import os
import numpy as np
import scipy
import torch
import torch.nn as nn
import torch.nn.functional as F
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
import block
from block.models.networks.vqa_net import factory_text_enc
from block.mod... | 7,498 | 32.627803 | 129 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/rubiintrod.py | import torch
import torch.nn as nn
from block.models.networks.mlp import MLP
from .utils import grad_mul_const # mask_softmax, grad_reverse, grad_reverse_mask,
class RUBiIntroD(nn.Module):
"""
Wraps another model
The original model must return a dictionnary containing the 'logits' key (predictions before... | 2,042 | 31.951613 | 105 | py |
introd | introd-main/cfvqa/cfvqa/models/networks/__init__.py | 0 | 0 | 0 | py | |
introd | introd-main/cfvqa/cfvqa/models/networks/san_net.py | from copy import deepcopy
import itertools
import os
import numpy as np
import scipy
import torch
import torch.nn as nn
import torch.nn.functional as F
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
import block
from block.models.networks.vqa_net import factory_text_enc
from block.mod... | 10,169 | 34.190311 | 129 | py |
introd | introd-main/cfvqa/cfvqa/models/criterions/rubiintrod_criterion.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
class RUBiIntroDCriterion(nn.Module):
def __init__(self):
super().__init__()
self.cls_loss = nn.CrossEntropyLoss(reduction='none')
def for... | 1,165 | 28.897436 | 72 | py |
introd | introd-main/cfvqa/cfvqa/models/criterions/cfvqaintrod_criterion.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
class CFVQAIntroDCriterion(nn.Module):
def __init__(self):
super().__init__()
self.cls_loss = nn.CrossEntropyLoss(reduction='none')
def fo... | 1,135 | 28.894737 | 72 | py |
introd | introd-main/cfvqa/cfvqa/models/criterions/factory.py | from bootstrap.lib.options import Options
from block.models.criterions.vqa_cross_entropy import VQACrossEntropyLoss
from .rubi_criterion import RUBiCriterion
from .cfvqa_criterion import CFVQACriterion
from .cfvqaintrod_criterion import CFVQAIntroDCriterion
from .rubiintrod_criterion import RUBiIntroDCriterion
def fac... | 1,453 | 35.35 | 73 | py |
introd | introd-main/cfvqa/cfvqa/models/criterions/__init__.py | 0 | 0 | 0 | py | |
introd | introd-main/cfvqa/cfvqa/models/criterions/rubi_criterion.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
class RUBiCriterion(nn.Module):
def __init__(self, question_loss_weight=1.0):
super().__init__()
Logger()(f'RUBiCriterion, with question_loss_weight... | 1,058 | 32.09375 | 88 | py |
introd | introd-main/cfvqa/cfvqa/models/criterions/cfvqa_criterion.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
class CFVQACriterion(nn.Module):
def __init__(self, question_loss_weight=1.0, vision_loss_weight=1.0, is_va=True):
super().__init__()
self.is_va = is... | 1,918 | 33.267857 | 89 | py |
introd | introd-main/cfvqa/cfvqa/models/metrics/vqa_rubi_metrics.py | import torch
import torch.nn as nn
import os
import json
from scipy import stats
import numpy as np
from collections import defaultdict
from bootstrap.models.metrics.accuracy import accuracy
from block.models.metrics.vqa_accuracies import VQAAccuracies
from bootstrap.lib.logger import Logger
from bootstrap.lib.options... | 10,030 | 43.384956 | 143 | py |
introd | introd-main/cfvqa/cfvqa/models/metrics/vqa_cfvqasimple_metrics.py | import torch
import torch.nn as nn
import os
import json
from scipy import stats
import numpy as np
from collections import defaultdict
from bootstrap.models.metrics.accuracy import accuracy
from block.models.metrics.vqa_accuracies import VQAAccuracies
from bootstrap.lib.logger import Logger
from bootstrap.lib.options... | 10,348 | 43.995652 | 143 | py |
introd | introd-main/cfvqa/cfvqa/models/metrics/vqa_rubiintrod_metrics.py | import torch
import torch.nn as nn
import os
import json
from scipy import stats
import numpy as np
from collections import defaultdict
from bootstrap.models.metrics.accuracy import accuracy
from block.models.metrics.vqa_accuracies import VQAAccuracies
from bootstrap.lib.logger import Logger
from bootstrap.lib.options... | 10,000 | 43.252212 | 143 | py |
introd | introd-main/cfvqa/cfvqa/models/metrics/vqa_cfvqa_metrics.py | import torch
import torch.nn as nn
import os
import json
from scipy import stats
import numpy as np
from collections import defaultdict
from bootstrap.models.metrics.accuracy import accuracy
from block.models.metrics.vqa_accuracies import VQAAccuracies
from bootstrap.lib.logger import Logger
from bootstrap.lib.options... | 10,384 | 44.152174 | 143 | py |
introd | introd-main/cfvqa/cfvqa/models/metrics/factory.py | from bootstrap.lib.options import Options
from block.models.metrics.vqa_accuracies import VQAAccuracies
from .vqa_rubi_metrics import VQARUBiMetrics
from .vqa_cfvqa_metrics import VQACFVQAMetrics
from .vqa_cfvqasimple_metrics import VQACFVQASimpleMetrics
from .vqa_cfvqaintrod_metrics import VQACFVQAIntroDMetrics
from .... | 3,402 | 36.395604 | 106 | py |
introd | introd-main/cfvqa/cfvqa/models/metrics/__init__.py | 0 | 0 | 0 | py | |
introd | introd-main/cfvqa/cfvqa/models/metrics/vqa_cfvqaintrod_metrics.py | import torch
import torch.nn as nn
import os
import json
from scipy import stats
import numpy as np
from collections import defaultdict
from bootstrap.models.metrics.accuracy import accuracy
from block.models.metrics.vqa_accuracies import VQAAccuracies
from bootstrap.lib.logger import Logger
from bootstrap.lib.options... | 10,313 | 43.843478 | 143 | py |
introd | introd-main/cfvqa/cfvqa/datasets/vqacp.py | import os
import csv
import copy
import json
import torch
import numpy as np
from tqdm import tqdm
from os import path as osp
from bootstrap.lib.logger import Logger
from block.datasets.vqa_utils import AbstractVQA
from copy import deepcopy
import random
import h5py
class VQACP(AbstractVQA):
def __init__(self,
... | 7,952 | 41.079365 | 111 | py |
introd | introd-main/cfvqa/cfvqa/datasets/vqacp2.py | import os
import csv
import copy
import json
import torch
import numpy as np
from tqdm import tqdm
from os import path as osp
from bootstrap.lib.logger import Logger
from block.datasets.vqa_utils import AbstractVQA
from copy import deepcopy
import random
import h5py
class VQACP2(AbstractVQA):
def __init__(self,
... | 7,954 | 41.089947 | 111 | py |
introd | introd-main/cfvqa/cfvqa/datasets/factory.py | from bootstrap.lib.options import Options
from block.datasets.tdiuc import TDIUC
from block.datasets.vrd import VRD
from block.datasets.vg import VG
from block.datasets.vqa_utils import ListVQADatasets
from .vqa2 import VQA2
from .vqacp2 import VQACP2
from .vqacp import VQACP
def factory(engine=None):
opt = Option... | 5,245 | 32.202532 | 63 | py |
introd | introd-main/cfvqa/cfvqa/datasets/__init__.py | 0 | 0 | 0 | py | |
introd | introd-main/cfvqa/cfvqa/datasets/vqa2.py | import os
import csv
import copy
import json
import torch
import numpy as np
from os import path as osp
from bootstrap.lib.logger import Logger
from bootstrap.lib.options import Options
from block.datasets.vqa_utils import AbstractVQA
from copy import deepcopy
import random
import tqdm
import h5py
class VQA2(AbstractV... | 8,260 | 44.640884 | 122 | py |
introd | introd-main/cfvqa/cfvqa/engines/engine.py | import os
import math
import time
import torch
import datetime
import threading
import numpy as np
from bootstrap.lib import utils
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
class Engine(object):
"""Contains training and evaluation procedures
"""
def __init__(self):
... | 17,193 | 38.345538 | 121 | py |
introd | introd-main/cfvqa/cfvqa/engines/logger.py | from bootstrap.lib.logger import Logger
from .engine import Engine
class LoggerEngine(Engine):
""" LoggerEngine is similar to Engine. The only difference is a more powerful is_best method.
It is able to look into the logger dictionary that contains the list of all the logged variables
indexed by n... | 2,067 | 35.280702 | 121 | py |
introd | introd-main/cfvqa/cfvqa/engines/factory.py | import importlib
from bootstrap.lib.options import Options
from bootstrap.lib.logger import Logger
from .engine import Engine
from .logger import LoggerEngine
def factory():
Logger()('Creating engine...')
if Options()['engine'].get('import', False):
# import usually is "yourmodule.engine.factory"
... | 639 | 23.615385 | 71 | py |
introd | introd-main/cfvqa/cfvqa/engines/__init__.py | from .factory import factory | 28 | 28 | 28 | py |
introd | introd-main/cfvqa/cfvqa/optimizers/factory.py | import torch.nn as nn
from bootstrap.lib.options import Options
from bootstrap.optimizers.factory import factory_optimizer
from block.optimizers.lr_scheduler import ReduceLROnPlateau
from block.optimizers.lr_scheduler import BanOptimizer
def factory(model, engine):
opt = Options()['optimizer']
optimizer = Ban... | 1,127 | 35.387097 | 95 | py |
introd | introd-main/cfvqa/cfvqa/optimizers/__init__.py | 0 | 0 | 0 | py | |
introd | introd-main/css/fc.py | from __future__ import print_function
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
class FCNet(nn.Module):
"""Simple class for non-linear fully connect network
"""
def __init__(self, dims):
super(FCNet, self).__init__()
layers = []
for i in range(len(di... | 853 | 24.117647 | 76 | py |
introd | introd-main/css/main.py | import argparse
import json
import cPickle as pickle
from collections import defaultdict, Counter
from os.path import dirname, join
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import numpy as np
from dataset import Dictionary, VQAFeatureDataset
import base_model
from train imp... | 6,824 | 34.732984 | 119 | py |
introd | introd-main/css/vqa_debias_loss_functions.py | from collections import OrderedDict, defaultdict, Counter
from torch import nn
from torch.nn import functional as F
import numpy as np
import torch
import inspect
def convert_sigmoid_logits_to_binary_logprobs(logits):
"""computes log(sigmoid(logits)), log(1-sigmoid(logits))"""
log_prob = -F.softplus(-logits)... | 9,581 | 35.022556 | 116 | py |
introd | introd-main/css/base_model.py | import torch
import torch.nn as nn
from attention import Attention, NewAttention
from language_model import WordEmbedding, QuestionEmbedding
from classifier import SimpleClassifier
from fc import FCNet
import numpy as np
def mask_softmax(x,mask):
mask=mask.unsqueeze(2).float()
x2=torch.exp(x-torch.max(x))
... | 2,765 | 32.325301 | 102 | py |
introd | introd-main/css/base_model_introd.py | import torch
import torch.nn as nn
from attention import Attention, NewAttention
from language_model import WordEmbedding, QuestionEmbedding
from classifier import SimpleClassifier
from fc import FCNet
import numpy as np
def mask_softmax(x,mask):
mask=mask.unsqueeze(2).float()
x2=torch.exp(x-torch.max(x))
... | 2,820 | 32.583333 | 102 | py |
introd | introd-main/css/train_introd.py | import json
import os
import pickle
import time
from os.path import join
import torch
import torch.nn as nn
import utils
from torch.autograd import Variable
import numpy as np
from tqdm import tqdm
import random
import copy
from torch.nn import functional as F
def compute_score_with_logits(logits, labels):
logit... | 5,773 | 32.569767 | 115 | py |
introd | introd-main/css/main_introd.py | import argparse
import json
import cPickle as pickle
from collections import defaultdict, Counter
from os.path import dirname, join
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import numpy as np
from dataset import Dictionary, VQAFeatureDataset
import base_model_introd as base... | 6,902 | 35.718085 | 119 | py |
introd | introd-main/css/utils.py | from __future__ import print_function
import errno
import os
import numpy as np
# from PIL import Image
import torch
import torch.nn as nn
EPS = 1e-7
def assert_eq(real, expected):
# assert real == expected, '%s (true) vs %s (expected)' % (real, expected)
assert real == real, '%s (true) vs %s (expected)' %... | 2,535 | 23.862745 | 79 | py |
introd | introd-main/css/classifier.py | import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
class SimpleClassifier(nn.Module):
def __init__(self, in_dim, hid_dim, out_dim, dropout):
super(SimpleClassifier, self).__init__()
layers = [
weight_norm(nn.Linear(in_dim, hid_dim), dim=None),
nn.ReLU(... | 565 | 28.789474 | 62 | py |
introd | introd-main/css/dataset.py | from __future__ import print_function
from __future__ import unicode_literals
import os
import json
import cPickle
from collections import Counter
import numpy as np
import utils
import h5py
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
from random import choice
class Dictionary(object):
... | 12,287 | 38.009524 | 106 | py |
introd | introd-main/css/eval.py | import argparse
import json
import cPickle
from collections import defaultdict, Counter
from os.path import dirname, join
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import numpy as np
import os
# from new_dataset import Dictionary, VQAFeatureDataset
from dataset import Dictionary, VQAF... | 7,543 | 34.088372 | 113 | py |
introd | introd-main/css/attention.py | import torch
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
from fc import FCNet
class Attention(nn.Module):
def __init__(self, v_dim, q_dim, num_hid):
super(Attention, self).__init__()
self.nonlinear = FCNet([v_dim + q_dim, num_hid])
self.linear = weight_norm(nn.... | 1,686 | 28.086207 | 66 | py |
introd | introd-main/css/train.py | import json
import os
import pickle
import time
from os.path import join
import torch
import torch.nn as nn
import utils
from torch.autograd import Variable
import numpy as np
from tqdm import tqdm
import random
import copy
def compute_score_with_logits(logits, labels):
logits = torch.argmax(logits, 1)
one_h... | 15,958 | 36.817536 | 115 | py |
introd | introd-main/css/language_model.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
class WordEmbedding(nn.Module):
"""Word Embedding
The ntoken-th dim is used for padding_idx, which agrees *implicitly*
with the definition in Dictionary.
"""
def __init__(self, ntoken, emb_dim, dropout):
... | 2,639 | 31.195122 | 84 | py |
introd | introd-main/css/tools/compute_softscore.py | from __future__ import print_function
import argparse
import os
import sys
import json
import numpy as np
import re
import cPickle
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dataset import Dictionary
import utils
contractions = {
"aint": "ain't", "arent": "aren't", "cant":... | 10,741 | 33.210191 | 76 | py |
introd | introd-main/css/tools/compute_softscore_val.py | from __future__ import print_function
import argparse
import os
import sys
import json
import numpy as np
import re
import cPickle
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dataset import Dictionary
import utils
contractions = {
"aint": "ain't", "arent": "aren't", "cant":... | 9,026 | 32.309963 | 76 | py |
introd | introd-main/css/tools/create_dictionary_v1.py | from __future__ import print_function
import os
import sys
import json
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dataset import Dictionary
def create_dictionary(dataroot):
dictionary = Dictionary()
questions = []
files = [
'OpenEnded_mscoc... | 1,745 | 30.178571 | 76 | py |
introd | introd-main/css/tools/create_dictionary.py | from __future__ import print_function
import os
import sys
import json
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dataset import Dictionary
def create_dictionary(dataroot):
dictionary = Dictionary()
questions = []
files = [
'v2_Op... | 1,799 | 29.508475 | 76 | py |
lda-c | lda-c-master/topics.py | #! /usr/bin/python
# usage: python topics.py <beta file> <vocab file> <num words>
#
# <beta file> is output from the lda-c code
# <vocab file> is a list of words, one per line
# <num words> is the number of words to print from each topic
import sys
def print_topics(beta_file, vocab_file, nwords = 25):
# get the... | 1,160 | 26.642857 | 77 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/conftest.py | import os
import pytest
from networkx import DiGraph
from api import create_app
CI_ENV = (os.getenv("CI") == "true")
#
# RT GRAPHS
#
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "test", "data")
TMP_DATA_DIR = os.path.join(TEST_DATA_DIR, "tmp")
@pytest.fixture(scope="module")
def mock_user_friends():
... | 4,029 | 32.865546 | 147 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/api/__init__.py |
import os
from dotenv import load_dotenv
from flask import Flask
from flask_cors import CORS
from api.routes.v0_routes import api_routes as api_v0_routes
from api.routes.v1_routes import api_routes as api_v1_routes
from app.bq_service import BigQueryService
load_dotenv()
SECRET_KEY = os.getenv("SECRET_KEY", defaul... | 820 | 24.65625 | 81 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/api/prep/daily_bot_scores.py |
import os
import json
from pandas import read_csv
import numpy as np
from app import DATA_DIR
#def binned_score(num):
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return floa... | 3,822 | 45.621951 | 258 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/api/routes/v0_routes.py |
from flask import Blueprint, current_app, jsonify, request
api_routes = Blueprint("v0_routes", __name__)
@api_routes.route("/api/v0/user_details/<screen_name>")
def user_details(screen_name=None):
#print(f"USER DETAILS: '{screen_name}'")
if "@" in screen_name or ";" in screen_name: # just be super safe about... | 3,560 | 47.780822 | 143 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/api/routes/v1_routes.py |
from flask import Blueprint, current_app, jsonify, request
api_routes = Blueprint("v1_routes", __name__)
@api_routes.route("/api/v1/user_tweets/<screen_name>")
def user_tweets(screen_name=None):
#print(f"USER TWEETS: '{screen_name}'")
if "@" in screen_name or ";" in screen_name: # just be super safe about pr... | 1,150 | 45.04 | 143 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_api_v0.py | import json
import pytest
from conftest import CI_ENV
@pytest.mark.skipif(CI_ENV, reason="avoid issuing HTTP requests on CI")
def test_user_details(api_client):
expected_keys = ['screen_name_count', 'screen_names', 'tweet_count', 'user_created_at', 'user_descriptions', 'user_id', 'user_names']
response = ap... | 6,818 | 47.021127 | 137 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_toxicity_checkpoint_scorer.py |
from app.toxicity.checkpoint_scorer import ToxicityScorer
from app.toxicity.model_manager import ModelManager
from conftest import toxicity_texts
def test_toxicity_scorer(original_model_manager):
# the different models have different class names
# so we need different table structures to store the resulting s... | 1,089 | 42.6 | 175 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_toxicity_scorer.py |
from app.toxicity.scorer import ToxicityScorer
def test_toxicity_scorer():
# the different models have different class names
# so we need different table structures to store the resulting scores
original = ToxicityScorer(model_name="original") # todo: use fixture
assert original.model.class_names == ... | 732 | 25.178571 | 73 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_model_training.py |
class DataFrame:
pass
class LogisticRegression:
pass
class MultinomialNB:
pass
def camel_to_snake(my_str):
return "".join([f"_{char.lower()}" if char.isupper() else char for char in str(my_str)]).lstrip("_")
def test_case_conversion():
assert camel_to_snake(DataFrame.__name__) == "data_frame"
... | 470 | 25.166667 | 104 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_lda_topics.py |
#topics = [
# {'impeach': 0.058, 'trump': 0.052, 'gop': 0.042, 'clinton': 0.039, 'commit': 0.037, 'condu': 0.037, 'proper': 0.037, 'defense': 0.037, 'jury': 0.037, 'grand': 0.037},
# {'trump': 0.063, 'impeach': 0.058, 'gop': 0.048, 'defense': 0.033, 'clinton': 0.033, 'commit': 0.033, 'grand': 0.032, 'condu'... | 3,663 | 125.344828 | 201 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_psycopg_grapher.py |
def test_set_uniqueness():
nodes = set()
nodes.add(1)
nodes.update([1,2,3])
assert nodes == {1, 2, 3}
| 120 | 14.125 | 29 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_friend_collection_in_batches.py |
from app.friend_collection.batch_per_thread import split_into_batches
def test_split_into_batches():
batches = split_into_batches([0,1,2,3,4,5,6,7,8,9,10], 3)
assert list(batches) == [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10]
]
| 275 | 20.230769 | 69 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_k_days.py |
from datetime import datetime
from app.retweet_graphs_v2.k_days.generator import DateRangeGenerator
def test_date_ranges():
gen = DateRangeGenerator(start_date="2020-01-01", k_days=3, n_periods=5)
assert [{"start_at": dr.start_at, "end_at": dr.end_at} for dr in gen.date_ranges] == [
{'start_at': dat... | 778 | 47.6875 | 95 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_tweet_recollection.py |
from app.tweet_recollection.collector import Collector
def test_recollection():
collector = Collector()
#assert collector.limit == 100000
#assert collector.batch_size == 100
assert collector.batch_size <= 100
assert collector.batch_size <= collector.limit
methods = list(dir(collector))
... | 511 | 25.947368 | 54 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_tokenizers.py |
import re
from app.bot_communities.tokenizers import Tokenizer, SpacyTokenizer, ALPHANUMERIC_PATTERN, TWITTER_ALPHANUMERIC_PATTERN
def test_string_cleaning_keeps_tags_and_handles():
status_text = "#HELLO @you http://hello.you ya know?"
assert re.sub(ALPHANUMERIC_PATTERN, "", status_text) == 'HELLO you http... | 1,663 | 43.972973 | 120 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_csv_grapher.py | import os
import pandas
from networkx import DiGraph, Graph
# columns: screen_name, friend_1, friend_2, friend_3, friend_4, etc...
#CSV_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "..", "data", "example_network.csv")
MOCK_CSV_FILEPATH = os.path.join(os.path.dirname(__file__), "data", "mock_network.csv")
... | 3,331 | 35.217391 | 148 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_botcode.py |
from networkx import DiGraph
from app.botcode.network_classifier_helper import (ALPHA, LAMBDA_1, LAMBDA_2, EPSILON,
compute_link_energy, compile_energy_graph, parse_bidirectional_links)
from app.botcode.investigation import classify_bot_probabilities
from conftest import compile_mock_rt_graph
def test_default_hy... | 17,960 | 60.091837 | 211 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_bq_grapher.py | import os
from networkx import read_gpickle
from app.friend_graphs.bq_grapher import BigQueryGrapher
from app.bq_service import BigQueryService
def test_network_grapher(mock_graph, expected_nodes, expected_edges):
graph_filepath = os.path.join(os.path.dirname(__file__), "data", "mock_graph.gpickle")
if os.pa... | 994 | 40.458333 | 150 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_pg_service.py |
# test bot screen name mathing strategy, that it case-insensitively finds a given screen name in an array of screen names:
#sql = """
# SELECT
# 'ACLU' as screen_name
#
# ,'ACLU' ilike any('{user1, aclu}'::text[]) as t1 -- TRUE
# ,'ACLU' ilike any('{user1, ACLU}'::text[]) as t2 -- TRUE
# ,'ACLU' ilike ... | 640 | 34.611111 | 122 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_toxicity_model_manager.py | from detoxify import Detoxify
import numpy as np
from transformers import BertForSequenceClassification, BertTokenizer
from pandas import DataFrame
from conftest import toxicity_texts
def test_packaged_model():
model = Detoxify("original")
results = model.predict(toxicity_texts)
assert results == {
... | 2,689 | 53.897959 | 231 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_api_v1.py | import json
import pytest
from conftest import CI_ENV
@pytest.mark.skipif(CI_ENV, reason="avoid issuing HTTP requests on CI")
def test_user_tweets(api_client):
expected_keys = ['created_at', 'score_bert', 'score_lr', 'score_nb', 'status_id', 'status_text']
response = api_client.get('/api/v1/user_tweets/ber... | 1,543 | 38.589744 | 131 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_number_decorators.py |
from app.decorators.number_decorators import fmt_n, fmt_pct
def test_large_number_decoration():
assert fmt_n(1_234_567.89012345) == '1,234,568'
def test_percent_decoration():
assert fmt_pct(0.97777777) == '97.78%'
| 226 | 21.7 | 59 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_datetime_decorators.py |
from datetime import datetime
from app.decorators.datetime_decorators import logstamp, dt_to_date, dt_to_s, s_to_dt
from app.decorators.datetime_decorators import to_ts as dt_to_ts
from app.decorators.datetime_decorators import fmt_date as ts_to_date
from app.decorators.datetime_decorators import to_dt as ts_to_dt
... | 1,360 | 30.651163 | 113 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/test/test_bq_service.py |
import pytest
from datetime import datetime
from conftest import CI_ENV
from app.bq_service import BigQueryService, split_into_batches, generate_timestamp
def test_generate_timestamp():
assert isinstance(generate_timestamp(), str)
assert isinstance(generate_timestamp(datetime.now()), str)
assert generate... | 1,090 | 32.060606 | 110 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/app/gcs_file_renaming.py | import os
from dotenv import load_dotenv
from app import seek_confirmation
from app.gcs_service import GoogleCloudStorageService
load_dotenv()
EXISTING_DIRPATH = os.getenv("EXISTING_DIRPATH", default="storage/data/archived_graphs")
EXISTING_PATTERN = os.getenv("EXISTING_PATTERN") or EXISTING_DIRPATH # can customize ... | 1,442 | 38 | 220 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/app/bq_service.py | from datetime import datetime, timedelta, timezone
import os
from functools import lru_cache
from pprint import pprint
from dotenv import load_dotenv
from google.cloud import bigquery
from google.cloud.bigquery import QueryJobConfig, ScalarQueryParameter
from pandas import DataFrame
from app import APP_ENV, seek_conf... | 72,536 | 38.040366 | 161 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/app/gcs_service.py |
import os
from pprint import pprint
from google.cloud import storage
from dotenv import load_dotenv
from conftest import TEST_DATA_DIR, TMP_DATA_DIR
load_dotenv()
GOOGLE_APPLICATION_CREDENTIALS = os.getenv("GOOGLE_APPLICATION_CREDENTIALS", default="google-credentials.json")
GCS_BUCKET_NAME=os.getenv("GCS_BUCKET_N... | 3,735 | 35.271845 | 111 | py |
tweet-analysis-2020 | tweet-analysis-2020-main/app/email_service.py | # app/email_service.py
import os
from dotenv import load_dotenv
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from app import SERVER_NAME, SERVER_DASHBOARD_URL
load_dotenv()
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
MY_EMAIL = os.getenv("MY_EMAIL_ADDRESS")
def send_email(subj... | 1,382 | 30.431818 | 96 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.