repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/train_utils.py | import argparse
import os
import logging
import numpy as np
import random
import sys
import torch
from datetime import datetime
from torch.serialization import default_restore_location
def add_logging_arguments(parser):
parser.add_argument("--seed", default=0, type=int, help="random number generator seed")
p... | 7,573 | 52.716312 | 138 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/main_function_helpers.py | import torch
import argparse
import os
import yaml
import pathlib
import pickle
import logging
import sys
import time
from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
import torchvision
import glob
from torch.serialization import default_restore_location
from torch.utils.data import Dat... | 23,245 | 45.772636 | 182 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/util_calculate_psnr_ssim.py | import cv2
import numpy as np
import torch
# from https://github.com/JingyunLiang/SwinIR/blob/328dda0f4768772e6d8c5aa3d5aa8e24f1ad903b/utils/util_calculate_psnr_ssim.py#L80
def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False):
"""Calculate PSNR (Peak Signal-to-Noise Ratio).
Re... | 9,023 | 37.564103 | 129 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/test_metrics.py | import torch
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
#import cv2
from utils.noise_model import get_noise
from utils.metrics import ssim,psnr
from utils.util_calculate_psnr_ssim import calculate_psnr,calculate_ssim
from skimage import color
import PIL.Image as Image
import torchvision.tr... | 4,464 | 29.582192 | 119 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/noise_model.py | import torch
def get_noise(data, noise_seed, fix_noise, noise_std = float(25)/255.0):
if fix_noise:
device = torch.device('cuda')
gen = torch.Generator(device=device)
batch_size = data.size(dim=0)
tensor_dim = list(data.size())[1:]
for i in range(0,batch_size)... | 880 | 31.62963 | 87 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/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,321 | 20.322581 | 75 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/Image_denoising_figure2/Noise2Noise/utils/data_helpers/load_datasets_helpers.py | import os
import os.path
import numpy as np
import h5py
import torch
import torchvision.transforms as transforms
import PIL.Image as Image
from utils.utils_image import *
class ImagenetSubdataset(torch.utils.data.Dataset):
def __init__(self, size, path_to_ImageNet_train, mode='train', patch_size='128', val_crop=Tr... | 1,949 | 32.62069 | 131 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/train_network_for_histogram.py | # %%
import torch
import h5py
import numpy as np
import os
import yaml
import logging
import glob
import random
import pickle
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import matplotlib.pyplot as plt
from torch.nn import MSELoss
import copy
from argparse import ArgumentParser
from torc... | 21,063 | 36.681574 | 211 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/run_CS_natural_images.py | # %%
import torch
import h5py
import numpy as np
import os
import yaml
import logging
import glob
import json
import random
import pickle
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import matplotlib.pyplot as plt
from torch.nn import MSELoss
from argparse import ArgumentParser
from torc... | 29,149 | 44.404984 | 278 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/CS_natural_images_functions/progress_bar.py | from collections import OrderedDict
from numbers import Number
from tqdm import tqdm
import torch
import logging
import os
import numpy as np
def init_logging(experiment_path):
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
handlers = [logging.StreamHandler()]
mode = ... | 3,573 | 30.910714 | 127 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/CS_natural_images_functions/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
class SSIMLoss(nn.Module):
"""
SSIM loss module.
"""
de... | 1,849 | 31.45614 | 98 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/CS_natural_images_functions/load_save_model_helpers.py | import glob
import torch
import os
from torch.serialization import default_restore_location
import logging
def setup_experiment_or_load_checkpoint(experiment_path, resume_from='best', model=None, optimizer=None, scheduler=None):
'''
Args:
- resume_from: Either 'best' or 'some_number' where some_number ... | 4,690 | 45.445545 | 154 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/CS_natural_images_functions/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_natural_images_figure4/CS_natural_images_functions/fftc.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 List, Optional
import torch
import torch.fft # type: ignore
def fft2c(data: torch.Tensor) -> torch.Tensor:
"""
... | 4,108 | 23.753012 | 80 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/CS_natural_images_functions/data_transforms.py | import numpy as np
import torch
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import torchvision.transforms as transforms
import PIL.Image as Image
from CS_natural_images_functions.log_progress_helpers import save_figure
from CS_natural_images_functions.fftc import fft2c, ifft2c
class C... | 8,047 | 36.432558 | 141 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_natural_images_figure4/CS_natural_images_functions/log_progress_helpers.py | import numpy as np
import matplotlib.pyplot as plt
from typing import Dict, Optional, Sequence, Tuple, Union, List
import os
import torchvision
import io
import torch
from CS_natural_images_functions.losses import SSIMLoss
def complex_abs(data: torch.Tensor) -> torch.Tensor:
"""
Compute the absolute value of ... | 8,395 | 35.663755 | 162 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/main.py |
#################
# Import python packages
import torch
import logging
import time
from torch.utils.tensorboard import SummaryWriter
import sys
import os
from torch.serialization import default_restore_location
from collections import defaultdict
import numpy as np
import torchvision
import pickle
import matplotlib.py... | 40,715 | 45.961938 | 214 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/coil_combine.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 functions.math import complex_abs_sq
def rss(data: torch.Tensor, dim: int = 0) -> torch.Tensor:
"""
Compute the ... | 1,015 | 22.627907 | 66 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/math.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 numpy as np
import torch
def complex_mul(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Complex multiplication.
... | 2,728 | 25.754902 | 77 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/log_save_image_utils.py | import matplotlib.pyplot as plt
import torchvision
import io
import torch
import numpy as np
def plot_to_image(figure):
"""Converts the matplotlib plot specified by 'figure' to a PNG image and
returns it. The supplied figure is closed and inaccessible after this call."""
# Save the plot to a PNG in memory.... | 1,533 | 33.088889 | 91 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/train_utils.py |
import torch
import numpy as np
import random
import os
import glob
import logging
from torch.serialization import default_restore_location
from tensorboard.backend.event_processing import event_accumulator
import time
import matplotlib.pyplot as plt
def setup_experiment(hp_exp):
'''
- Handle seeding
- Cr... | 7,597 | 44.771084 | 160 | py |
sample_complexity_ss_recon | sample_complexity_ss_recon-main/CS_accelerated_MRI_figure5/functions/fftc.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 List, Optional
import torch
from packaging import version
if version.parse(torch.__version__) >= version.parse("1.7.0"):... | 5,535 | 25.236967 | 80 | 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/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 |
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/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/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/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/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/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/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/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/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 |
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/toxicity/model_manager.py |
#
# adapted from: https://github.com/unitaryai/detoxify/blob/master/detoxify/detoxify.py
#
# using the pre-trained toxicity models provided via Detoxify checkpoints, but...
# 1) let's try different / lighter torch requirement approaches (to enable installation on heroku) - see requirements.txt file
# 2) let's also try... | 6,115 | 39.773333 | 155 | py |
FBNETGEN | FBNETGEN-main/main.py | from pathlib import Path
import argparse
import yaml
import torch
from model import FBNETGEN, GNNPredictor, SeqenceModel, BrainNetCNN
from train import BasicTrain, BiLevelTrain, SeqTrain, GNNTrain, BrainCNNTrain
from datetime import datetime
from dataloader import init_dataloader
def main(args):
with open(args.... | 3,687 | 35.514851 | 109 | py |
FBNETGEN | FBNETGEN-main/dataloader.py |
import numpy as np
import torch
import torch.utils.data as utils
from sklearn import preprocessing
import pandas as pd
from scipy.io import loadmat
import pathlib
class StandardScaler:
"""
Standard the input
"""
def __init__(self, mean, std):
self.mean = mean
self.std = std
def t... | 6,468 | 30.556098 | 104 | py |
FBNETGEN | FBNETGEN-main/train.py | from typing import overload
import torch
from numpy.lib import save
from util import Logger, accuracy, TotalMeter
import numpy as np
from pathlib import Path
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score
from sklearn.metrics import precision_recall_fscore_support
from util.prepossess import ... | 16,952 | 34.690526 | 98 | py |
FBNETGEN | FBNETGEN-main/util/prepossess.py | import torch
import numpy as np
import random
def mixup_data(x, nodes, y, alpha=1.0, device='cuda'):
'''Returns mixed inputs, pairs of targets, and lambda'''
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
batch_size = x.size()[0]
index = torch.randperm(batch_size).... | 2,388 | 27.783133 | 90 | py |
FBNETGEN | FBNETGEN-main/util/loss.py | import torch
def inner_loss(label, matrixs):
loss = 0
if torch.sum(label == 0) > 1:
loss += torch.mean(torch.var(matrixs[label == 0], dim=0))
if torch.sum(label == 1) > 1:
loss += torch.mean(torch.var(matrixs[label == 1], dim=0))
return loss
def intra_loss(label, matrixs):
a,... | 1,451 | 24.928571 | 70 | py |
FBNETGEN | FBNETGEN-main/util/meter.py | from typing import List
import torch
def accuracy(output: torch.Tensor, target: torch.Tensor, top_k=(1,)) -> List[float]:
max_k = max(top_k)
batch_size = target.size(0)
_, predict = output.topk(max_k, 1, True, True)
predict = predict.t()
correct = predict.eq(target.view(1, -1).expand_as(predict))... | 1,699 | 22.943662 | 84 | py |
FBNETGEN | FBNETGEN-main/util/FCNet/infer.py | import torch
import argparse
import yaml
from model import SeqenceModel, FCNet
from dataloader import infer_dataloader
from pathlib import Path
import numpy as np
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import roc_... | 2,775 | 22.726496 | 119 | py |
FBNETGEN | FBNETGEN-main/model/GSL.py | import torch
import torch.nn as nn
from torch.nn import functional as F
from model.cell import DCGRUCell
import numpy as np
from .model import GNNPredictor, ConvKRegion, Embed2GraphByLinear, GruKRegion, Embed2GraphByProduct
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def count_parameters(mod... | 16,048 | 35.894253 | 119 | py |
FBNETGEN | FBNETGEN-main/model/model.py | from turtle import forward
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Conv1d, MaxPool1d, Linear, GRU
import math
def sample_gumbel(shape, eps=1e-20):
U = torch.rand(shape).cuda()
return -torch.autograd.Variable(torch.log(-torch.log(U + eps) + ep... | 13,552 | 29.050998 | 97 | py |
FBNETGEN | FBNETGEN-main/model/cell.py | import numpy as np
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class LayerParams:
def __init__(self, rnn_network: torch.nn.Module, layer_type: str):
self._rnn_network = rnn_network
self._params_dict = {}
self._biases_dict = {}
self._type = lay... | 6,299 | 38.873418 | 105 | py |
dynet | dynet-master/examples/variational-autoencoder/basic-image-recon/vae.py | from __future__ import print_function
from utils import load_mnist, make_grid, pre_pillow_float_img_process, save_image
import numpy as np
import argparse
import dynet as dy
import os
if not os.path.exists('results'):
os.makedirs('results')
parser = argparse.ArgumentParser(description='VAE MNIST Example')
parser... | 6,690 | 31.639024 | 118 | py |
dynet | dynet-master/examples/mnist/basic-mnist-benchmarks/mnist_pytorch.py | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import time
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNI... | 4,645 | 38.372881 | 95 | py |
dynet | dynet-master/doc/source/conf.py | # -*- coding: utf-8 -*-
#
# DyNet documentation build configuration file, created by
# sphinx-quickstart on Thu Oct 13 16:13:12 2016.
#
# 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
# autogenerated file.
#
# All... | 9,095 | 30.583333 | 83 | py |
pose_refinement | pose_refinement-master/src/training/loaders.py | import numpy as np
from torch.utils.data import DataLoader, SequentialSampler
from itertools import chain
import torch
from databases.datasets import pose_grid_from_index, Mpi3dTrainDataset, PersonStackedMucoTempDataset, ConcatPoseDataset
class ConcatSampler(torch.utils.data.Sampler):
""" Concatenates two sampl... | 6,259 | 41.297297 | 136 | py |
pose_refinement | pose_refinement-master/src/training/callbacks.py | import math
import numpy as np
import torch
from training.loaders import UnchunkedGenerator
from training.torch_tools import eval_results
from util.pose import remove_root, mrpe, optimal_scaling, r_mpjpe
class BaseCallback(object):
def on_itergroup_end(self, iter_cnt, epoch_loss):
pass
def on_epoch... | 13,217 | 38.57485 | 117 | py |
pose_refinement | pose_refinement-master/src/training/torch_tools.py | import numpy as np
from torch.utils.data import DataLoader, TensorDataset
from itertools import zip_longest, chain
import torch
from util.misc import assert_shape
from inspect import signature
import time
from torch import optim
from util.pose import mrpe
def exp_decay(params):
def f(epoch):
return params... | 13,551 | 35.926431 | 136 | py |
pose_refinement | pose_refinement-master/src/training/preprocess.py | import numpy as np
import torch
from databases.datasets import PoseDataset
from databases.joint_sets import Common14Joints, CocoExJoints, MuPoTSJoints
from util.misc import assert_shape, load
from util.pose import remove_root, remove_root_keepscore, combine_pose_and_trans
def preprocess_2d(data, fx, cx, fy, cy, join... | 16,694 | 33.853862 | 139 | py |
pose_refinement | pose_refinement-master/src/util/pose.py | import numpy as np
from databases.joint_sets import CocoExJoints
from util.misc import assert_shape
def harmonic_mean(a, b, eps=1e-6):
return 2 / (1 / (a + eps) + 1 / (b + eps))
def _combine(data, target, a, b):
"""
Modifies data by combining (taking average) joints at index a and b at position target.... | 7,952 | 30.939759 | 113 | py |
pose_refinement | pose_refinement-master/src/scripts/maskrcnn_bboxes.py | """ Generates Mask-RCNN bounding boxes. """
import argparse
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import cv2
# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.config import get_cfg
import detectron2.... | 3,049 | 29.19802 | 101 | py |
pose_refinement | pose_refinement-master/src/scripts/hrnet_predict.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
sys.path.append('../hrnet/lib')
from scripts import hrnet_dataset
# ------------------------------------------------------------------------------
# pose.pytorch
# Copyright (c) 2018-present Micros... | 7,588 | 33.03139 | 95 | py |
pose_refinement | pose_refinement-master/src/scripts/hrnet_dataset.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Marton Veges
# ------------------------------------------------------------------------------
from __future__ impor... | 10,625 | 32.415094 | 128 | py |
pose_refinement | pose_refinement-master/src/scripts/eval.py | #!/usr/bin/python3
"""
Evaluates a (not end2end) model on MuPo-TS
"""
import argparse
import os
import numpy as np
import torch
from util.misc import load
from databases import mupots_3d
from databases.datasets import PersonStackedMuPoTsDataset
from databases.joint_sets import MuPoTSJoints, CocoExJoints
from model.po... | 4,512 | 34.81746 | 127 | py |
pose_refinement | pose_refinement-master/src/scripts/train.py | import argparse
import os
from databases.datasets import Mpi3dTestDataset, Mpi3dTrainDataset, PersonStackedMucoTempDataset, ConcatPoseDataset
from model.videopose import TemporalModel, TemporalModelOptimized1f
from training.callbacks import preds_from_logger, ModelCopyTemporalEvaluator
from training.loaders import Chu... | 7,059 | 38.222222 | 122 | py |
pose_refinement | pose_refinement-master/src/databases/datasets.py | import os
import h5py
import numpy as np
from torch.utils.data import Dataset
from databases import mupots_3d, mpii_3dhp, muco_temp
from databases.joint_sets import CocoExJoints, OpenPoseJoints, MuPoTSJoints
class PoseDataset(Dataset):
""" Subclasses should have the attributes poses2d/3d, pred_cdepths, pose[2|3... | 27,399 | 42.149606 | 132 | py |
pose_refinement | pose_refinement-master/src/model/pose_refinement.py | import numpy as np
import torch
from scipy import ndimage
from databases.joint_sets import MuPoTSJoints
from training.callbacks import BaseMPJPECalculator
from training.torch_tools import get_optimizer
from util.misc import assert_shape
from util.pose import remove_root, insert_zero_joint
def pose_error(pred, init):... | 7,511 | 34.267606 | 127 | py |
pose_refinement | pose_refinement-master/src/model/videopose.py | # Based on https://github.com/facebookresearch/VideoPose3D
#
# Copyright (c) 2018-present, Facebook, Inc.
# 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 torch.nn as nn
class TemporalModelBase(nn.Module):
""... | 9,265 | 40.927602 | 116 | py |
UltraNest | UltraNest-master/docs/conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ultranest documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47: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
# a... | 5,899 | 27.780488 | 77 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.