python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model # AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning # https://arxiv.org/abs/1612.01887 # AdaAttMO is a modified version with maxout lstm # Att2in is from Self-critical Sequence Training for Image Captioning #...
connect-caption-and-trace-main
captioning/models/AttModel_both_backup_2020_11_07.py
""" BertCapModel is using huggingface transformer bert model as seq2seq model. The result is not as goog as original transformer. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import...
connect-caption-and-trace-main
captioning/models/BertCapModel.py
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model # AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning # https://arxiv.org/abs/1612.01887 # AdaAttMO is a modified version with maxout lstm # Att2in is from Self-critical Sequence Training for Image Captioning #...
connect-caption-and-trace-main
captioning/models/AttModel_for_coco_caption_baseline.py
# This file contains Att2in2, AdaAtt, AdaAttMO, UpDown model # AdaAtt is from Knowing When to Look: Adaptive Attention via A Visual Sentinel for Image Captioning # https://arxiv.org/abs/1612.01887 # AdaAttMO is a modified version with maxout lstm # Att2in is from Self-critical Sequence Training for Image Captioning #...
connect-caption-and-trace-main
captioning/models/AttModel_for_coco_caption_task.py
import torch from . import losses from ..utils.rewards import init_scorer, get_self_critical_reward class LossWrapper(torch.nn.Module): def __init__(self, model, opt): super(LossWrapper, self).__init__() self.opt = opt self.model = model if opt.label_smoothing > 0: self....
connect-caption-and-trace-main
captioning/modules/loss_wrapper_caption_generation.py
import torch import torch.nn.functional as F from . import losses from ..utils.rewards import init_scorer, get_self_critical_reward class LossWrapper(torch.nn.Module): def __init__(self, model, opt): super(LossWrapper, self).__init__() self.opt = opt self.model = model if opt.label_...
connect-caption-and-trace-main
captioning/modules/loss_wrapper_show_control_tell.py
import torch import torch.nn.functional as F from . import losses from ..utils.rewards import init_scorer, get_self_critical_reward from ..utils.local_optimal_transport import local_OT class LossWrapper(torch.nn.Module): def __init__(self, model, opt): super(LossWrapper, self).__init__() self.opt ...
connect-caption-and-trace-main
captioning/modules/loss_wrapper_trace_generation.py
import torch import torch.nn.functional as F from . import losses from ..utils.rewards import init_scorer, get_self_critical_reward import numpy as np import random class LossWrapper(torch.nn.Module): def __init__(self, model, opt): super(LossWrapper, self).__init__() self.opt = opt self.mo...
connect-caption-and-trace-main
captioning/modules/loss_wrapper_joint.py
import torch import torch.nn.functional as F from . import losses from ..utils.rewards import init_scorer, get_self_critical_reward class LossWrapper(torch.nn.Module): def __init__(self, model, opt): super(LossWrapper, self).__init__() self.opt = opt self.model = model if opt.label_...
connect-caption-and-trace-main
captioning/modules/loss_wrapper_for_coco_caption.py
import torch import torch.nn as nn from ..utils.rewards import get_scores, get_self_cider_scores class RewardCriterion(nn.Module): def __init__(self): super(RewardCriterion, self).__init__() def forward(self, input, seq, reward): input = input.gather(2, seq.unsqueeze(2)).squeeze(2) ...
connect-caption-and-trace-main
captioning/modules/losses.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import h5py import lmdb import os import numpy as np import numpy.random as npr import random import torch import torch.utils.data as data import multiprocessing import six class HybridLoader: ...
connect-caption-and-trace-main
captioning/data/pth_loader.py
connect-caption-and-trace-main
captioning/data/__init__.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import h5py import os import numpy as np import random import torch import skimage import skimage.io import scipy.misc from torchvision import transforms as trn preprocess = trn.Compose([ #...
connect-caption-and-trace-main
captioning/data/dataloaderraw.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import h5py import lmdb import os import numpy as np import numpy.random as npr import random import torch import torch.utils.data as data import multiprocessing import six class HybridLoader: ...
connect-caption-and-trace-main
captioning/data/dataloader.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import h5py import lmdb import os import numpy as np import numpy.random as npr import random import torch import torch.utils.data as data import multiprocessing import six class HybridLoader: ...
connect-caption-and-trace-main
captioning/data/dataloader_show_control_tell.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import base64 import numpy as np import csv import sys import zlib import time import mmap import argparse parser = argparse.ArgumentParser() # output_dir parser.add_argument('--downloaded_feats', d...
connect-caption-and-trace-main
scripts/make_bu_data.py
""" Preprocess a raw json dataset into features files for use in data_loader.py Input: json file that has the form [{ file_path: 'path/img.jpg', captions: ['a caption', ...] }, ...] example element in this list would look like {'captions': [u'A man with a red helmet on a small moped on a dirt road. ', u'Man riding a m...
connect-caption-and-trace-main
scripts/prepro_feats.py
# coding: utf-8 """ Create a reference json file used for evaluation with `coco-caption` repo. Used when reference json is not provided, (e.g., flickr30k, or you have your own split of train/val/test) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function impo...
connect-caption-and-trace-main
scripts/prepro_reference_json.py
""" Precompute ngram counts of captions, to accelerate cider computation during training time. """ import os import json import argparse from six.moves import cPickle import captioning.utils.misc as utils from collections import defaultdict import sys sys.path.append("cider") from pyciderevalcap.ciderD.ciderD_scorer ...
connect-caption-and-trace-main
scripts/prepro_ngrams.py
import argparse import h5py import os import numpy as np import json from tqdm import tqdm def main(params): imgs = json.load(open(params['input_json'], 'r')) imgs = imgs['images'] N = len(imgs) if params['fc_input_dir'] is not None: print('processing fc') with h5py.File(params['fc_o...
connect-caption-and-trace-main
scripts/dump_to_h5df.py
""" Preprocess a raw json dataset into hdf5/json files for use in data_loader.py Input: json file that has the form [{ file_path: 'path/img.jpg', captions: ['a caption', ...] }, ...] example element in this list would look like {'captions': [u'A man with a red helmet on a small moped on a dirt road. ', u'Man riding a ...
connect-caption-and-trace-main
scripts/prepro_labels.py
import torch import scipy.optimize import numpy as np m = 10 pred = torch.rand([10, m, 4]) label = torch.rand([10, m, 4]) def local_OT(D): p = D.shape[1]; m = D.shape[2] # construct the cx, ax=b x = torch.rand([10,m*m]) A = torch.zeros([m+m,m*m]) b = torch.ones([m+m]) for i in range(p): ...
connect-caption-and-trace-main
scripts/my_local_optimal_transport.py
# copy from https://github.com/Lyken17/Efficient-PyTorch/tools from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path as osp import os, sys import os.path as osp from PIL import Image import six import string import lmdb import pickle imp...
connect-caption-and-trace-main
scripts/dump_to_lmdb.py
import numpy as np import os import h5py import numpy as np import jsonlines import re import json # The first directory should lead to your feature files extracted by detectrons, and the box_only and feats_only are the new folders for saving bounding boxes and features (which will be used during training). i = 0 for...
connect-caption-and-trace-main
scripts/prepare_feats_boxes_from_npz.py
""" Preprocess a raw json dataset into hdf5/json files for use in data_loader.lua Input: json file that has the form [{ file_path: 'path/img.jpg', captions: ['a caption', ...] }, ...] example element in this list would look like {'captions': [u'A man with a red helmet on a small moped on a dirt road. ', u'Man riding a...
connect-caption-and-trace-main
scripts/build_bpe_subword_nmt.py
""" Preprocess PubTator snapshot for use with Snorkel v6.2 1) Download snapshot 2) Split snapshot into blocks 3) Parse blocks and load into database """ import os import sys import glob import shutil import argparse from time import time def split_pubtator_corpus(file_path, split_size=500000): """ Split Pub...
snorkel-biocorpus-master
parse_pubtator.py
import re import sys from itertools import product from sqlalchemy.sql import select from collections import defaultdict from snorkel.udf import UDF, UDFRunner from snorkel.models import TemporarySpan, Sentence, Document, SequenceTag, Candidate class SequenceTagCandidateExtractor(UDFRunner): """UDFRunner for Sequ...
snorkel-biocorpus-master
custom_cand_generator.py
class Tagger(object): pass
snorkel-biocorpus-master
pubtator/tags.py
import re import sys import codecs import lxml.etree as et from collections import namedtuple from snorkel.models import Document, SequenceTag Tag = namedtuple('Tag', 'document_id abs_char_start abs_char_end concept_type concept_uid source') class MetadataProcessor(object): """ Load external information ...
snorkel-biocorpus-master
pubtator/metadata.py
from .parsers import * from .metadata import *
snorkel-biocorpus-master
pubtator/__init__.py
import re import codecs from snorkel.parser import DocPreprocessor from snorkel.models import Document, split_stable_id from snorkel.parser import Parser, ParserConnection, Spacy, Sentence class PubTatorParser(Parser): """ Parser wrapper for PubTator annotations. Annotations require some data munging to ma...
snorkel-biocorpus-master
pubtator/parsers.py
import codecs import spacy from collections import defaultdict from snorkel.models import construct_stable_id from spacy.tokens import Doc from snorkel.parser import DocPreprocessor from snorkel.models import Document, split_stable_id from snorkel.parser import Parser, ParserConnection, Spacy, Sentence class LineCorpu...
snorkel-biocorpus-master
pubtator/doc_parsers.py
"""An extensible library for opening URLs using a variety of protocols The simplest way to use this module is to call the urlopen function, which accepts a string containing a URL or a Request object (described below). It opens the URL and returns the results as file-like object; the returned object has some extra me...
snorkel-biocorpus-master
pubtator/api/urllib2.py
import urllib2 import time import sys import getopt inputfile = '' bioconcept = '' format = '' try: options, remainder = getopt.getopt(sys.argv[1:], 'i:b:f:', ['inputfile=','bioconcept=','format=']) except getopt.GetoptError, err: print "\npython RESTful.client.get.py -i [inputfile] -b [bioconcept] -f [format]\n" ...
snorkel-biocorpus-master
pubtator/api/RESTful.client.get.py
import urllib2 import time import sys import getopt inputfile = '' trigger = '' taxonomy = '' email = '' PubTator_username = '' url_Submit = '' try: options, remainder = getopt.getopt(sys.argv[1:], 'i:t:x:e:', ['inputfile=','trigger=','taxonomy=','email=']) except getopt.GetoptError, err: print "\npython RESTful.cl...
snorkel-biocorpus-master
pubtator/api/RESTful.client.post.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------ Learn Common Phrases ------------------------------------------------ Train PMI-based phrase models. Currently this only assumes bigrams, but it can be extended easily. """ import sys import logging import argparse from...
snorkel-biocorpus-master
embeddings/train_pmi_phrases.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ------------------------------------------------ Create Word Embeddings ------------------------------------------------ Use Gensim's Word2Vec implementation to create word (or short phrase) embeddings ''' import re import sys import string import logging import argp...
snorkel-biocorpus-master
embeddings/train_emb.py
""" Generate external database key/value pairs for select fields that we want to define joins or elastic search attributes over (e.g., publication year, journal, mesh keywords). The rest of the content we commit as a the raw XML tree. """ import glob import lxml.etree as et filelist = glob.glob("{}/*.xml".format()) ...
snorkel-biocorpus-master
etl/pubmed/extract/extract_metadata.py
''' Dumps PubMed standoff abstracts to a common text file format for bulk loading ''' import os import glob import codecs import argparse import lxml.etree as et from pubtator.parsers import PubTatorDocPreprocessor def parse_standoff_format(filename, outputdir, source_prefix="gold_cdr"): """ FORMAT: ...
snorkel-biocorpus-master
etl/pubmed/extract/extract_annotations.py
''' Dumps PubMed abstracts to a common text file format for bulk preprocessing FORMAT: ~~_PMID_XXXXXX_~~ TEXT .. ''' import os import glob import codecs import argparse import lxml.etree as et from pubtator.parsers import PubTatorDocPreprocessor def parse_xml_format(filename, outputdir): """ NLM XML Format ...
snorkel-biocorpus-master
etl/pubmed/extract/extract_text.py
""" Requires 1) Convert standoff format into 1 sentence per line. 2) Apply rule-based sentence boundary detection/tokenization fixes The main goal of this step is to ensure high-quality SBD which often breaks in the presence of complex chemical names """ import re import os import glob import codecs import argpars...
snorkel-biocorpus-master
etl/pubmed/extract/tokenization_fixes.py
""" """ import re import os import sys import glob import codecs import argparse article_rgx = re.compile("~~_PMID_([0-9]+)_~~") def load_line_corpus(filename, sentences=False, encoding="utf-8"): corpus = {} with codecs.open(filename, "rU", 'utf-8') as fp: doc = [] for line in fp: ...
snorkel-biocorpus-master
etl/pubmed/extract/export_line_corpus.py
""" Transform PubMed text generated by extract_pubmed.py into tokenized standoff format. This leverages 2 external software tools that fix tokenization errors when using CoreNLP and spaCy are used on biomedical text, primarily: 1) Errors tokenizing chemical names 2) Correctly identifying sentence boundaries in the ...
snorkel-biocorpus-master
etl/pubmed/extract/tokenize.py
""" Load PubTator snapshot for use with Snorkel v6.2 This loads tags into memory, so it works best when the input PubTator file is split into smaller blocks. """ import os import glob import codecs import argparse def dump2delimited(tags, outfile, write_mode, sep=u"\t", encoding="utf-8"): with codecs.open(outfil...
snorkel-biocorpus-master
OLD/extract_pubtator_tags.py
model-patching-master
augmentation/__init__.py
import tensorflow as tf import wandb import yaml import subprocess from augmentation.utilities.visualize import gallery from augmentation.utilities.wandb import * from augmentation.utilities.checkpoint import load_tf_optimizer_state def rewrite_config_for_resumption(config): config.prev_wandb_entity = config.wand...
model-patching-master
augmentation/methods/robust/utils.py
import argparse import os import yaml import subprocess import glob import functools from augmentation.augment.utils import create_multiple_train_eval_augmentation_pipelines from augmentation.augment.static import create_multiple_train_eval_static_augmentation_pipelines from augmentation.datasets.utils import * from au...
model-patching-master
augmentation/methods/robust/train.py
import tensorflow as tf import numpy as np from tensorflow_examples.models.pix2pix.pix2pix import upsample, downsample, InstanceNormalization def unet_generator(output_channels, input_shape=(256, 256, 3), norm_type='batchnorm', output_init=0.02, residual_output=False): """Modified u-net generat...
model-patching-master
augmentation/methods/cyclegan/models.py
import datetime import tensorflow as tf import random import wandb from tensorflow_examples.models.pix2pix import pix2pix from augmentation.dataflows.utils import create_paired_direct_dataflow, \ create_paired_parallel_dataflow_via_numpy from augmentation.methods.cyclegan.models import mnist_unet_generator, mnist...
model-patching-master
augmentation/methods/cyclegan/utils.py
import argparse import os import functools import time import subprocess from augmentation.utilities.config import * from augmentation.utilities.metrics import * from augmentation.datasets.utils import get_processed_dataset_info, apply_modifier_to_dataset_payload, load_dataset from augmentation.dataflows.utils import d...
model-patching-master
augmentation/methods/cyclegan/train.py
model-patching-master
augmentation/autoaugment/__init__.py
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
model-patching-master
augmentation/autoaugment/augmentation_transforms.py
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
model-patching-master
augmentation/autoaugment/policies.py
from augmentation.dataflows.utils import create_parallel_dataflow_via_numpy, create_direct_dataflow import augmentation.augment.static import tensorflow as tf import tensorflow_datasets as tfds import numpy as np import matplotlib.pyplot as plt from multiprocessing import cpu_count from types import SimpleNamespace imp...
model-patching-master
augmentation/datasets/utils.py
from types import SimpleNamespace import tensorflow as tf import augmentation.datasets.utils CELEBA_BASE_VARIANTS = ['5_o_Clock_Shadow', 'Arched_Eyebrows', 'Attractive', 'Bags_Under_Eyes', 'Bald', 'B...
model-patching-master
augmentation/datasets/custom/celeba_128.py
import tensorflow as tf import os import augmentation.datasets.utils # Basic feature construction, taken from the tutorial on TFRecords def _bytestring_feature(list_of_bytestrings): return tf.train.Feature(bytes_list=tf.train.BytesList(value=list_of_bytestrings)) def _int_feature(list_of_ints): return tf.tr...
model-patching-master
augmentation/datasets/custom/tfrecords.py
from types import SimpleNamespace import tensorflow as tf import augmentation.datasets.utils WATERBIRDS_CLASSES = ['landbird', 'waterbird'] WATERBIRDS_DOMAINS = ['land', 'water'] # Group Sizes # ------------------------------------ # [y, z] = [[0, 0], [0, 1], [1, 0], [1, 1]] # # Training Set (split = 0) # [3498, 18...
model-patching-master
augmentation/datasets/custom/waterbirds.py
from types import SimpleNamespace import augmentation.datasets.utils from augmentation.datasets.custom.mnist import MNIST_CORRUPTED_VARIANTS import tensorflow as tf # TODO multihead should be specified as an option to the dataset instead of a separate one def load_mnist_correlation_yz_multihead(dataset_name, dataset...
model-patching-master
augmentation/datasets/custom/mnist_correlation.py
from types import SimpleNamespace import augmentation.datasets.utils MNIST_CORRUPTED_VARIANTS = ['identity', 'shot_noise', 'impulse_noise', 'glass_blur', 'motion_blur', 'shear', ...
model-patching-master
augmentation/datasets/custom/mnist.py
import numpy as np import imgaug.augmenters as iaa from imgaug.augmenters import * from augmentation.methods.cyclegan.models import * from augmentation.autoaugment import augmentation_transforms from augmentation.autoaugment.augmentation_transforms import MEANS, STDS from augmentation.autoaugment.policies import good_p...
model-patching-master
augmentation/augment/utils.py
from augmentation.augment.utils import WandbModelPseudoLabelingPipeline, BinaryMNISTWandbModelPseudoLabelingPipeline, \ PretrainedMNISTCycleGANAugmentationPipeline, ResizeImage from augmentation.utilities.wandb import load_pretrained_keras_model_from_wandb, particular_checkpoint_step_extractor, \ load_wandb_run...
model-patching-master
augmentation/augment/static.py
import tensorflow.keras as keras from classification_models.tfkeras import Classifiers def simple_model(input_shape, n_classes): inputs = keras.layers.Input(shape=input_shape, name='digits') x = keras.layers.Flatten()(inputs) x = keras.layers.Dense(64, activation='relu', name='dense_1')(x) x = keras.l...
model-patching-master
augmentation/models/models.py
# The code in this file is adapted from # https://keras.io/examples/cifar10_resnet/ import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras.layers import AveragePooling2D, Input, Flatten from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, Activation from tensorflow.keras.model...
model-patching-master
augmentation/models/resnet.py
import tensorflow as tf import tensorflow.keras as keras import wandb import matplotlib.pyplot as plt import seaborn as sns import numpy as np from tensorflow.python.keras import backend as K from augmentation.methods.robust.utils import irm_penalty_explicit class ConfusionMatrix(keras.metrics.Metric): def __ini...
model-patching-master
augmentation/utilities/metrics.py
import os import yaml from types import SimpleNamespace def load_yaml_config(path: str, prefix_keys=False) -> SimpleNamespace: """ Load a yaml configuration file from the specified path, apply preprocessing operations to it and return the configuration in a SimpleNamespace. :param path: Path to the c...
model-patching-master
augmentation/utilities/config.py
import pickle import gzip def compile_keras_models(models, optimizers): # Compile the models: this is necessary in order to save model architecture, weights and optimizer to disk # It doesn't matter what loss we use here since we're not going to be calling model.fit: TODO check! for model, optimizer in zi...
model-patching-master
augmentation/utilities/checkpoint.py
import wandb import json import time import numpy as np from collections import namedtuple from augmentation.methods.cyclegan.models import mnist_unet_generator, unet_generator from augmentation.models.models import create_keras_classification_model WandbRun = namedtuple('WandbRun', 'path id name history files cfg url...
model-patching-master
augmentation/utilities/wandb.py
import numpy as np def gallery(array, ncols=None): # https://stackoverflow.com/questions/42040747/more-idiomatic-way-to-display-images-in-a-grid-with-numpy nindex, height, width, intensity = array.shape if ncols is None: ncols = int(np.floor(np.sqrt(nindex))) while nindex % ncols != 0: ncols +...
model-patching-master
augmentation/utilities/visualize.py
import tensorflow as tf import numpy as np import wandb from types import SimpleNamespace def set_global_seeds(seed): """ Set all the random seeds. """ tf.random.set_seed(seed) np.random.seed(seed) def basic_setup(seed, logical_gpu_memory_limits=(4096, 10240)): """ Function for setting u...
model-patching-master
augmentation/utilities/utils.py
import augmentation.datasets.utils from augmentation.augment.utils import WandbModelPseudoLabelingPipeline, BinaryMNISTWandbModelPseudoLabelingPipeline def configure_pseudolabeler(pseudolabel: bool, pseudolabeler_builder, pseudolabeler_builder_args): """Pass in a class that can build a pseudolabeler (implementing...
model-patching-master
augmentation/utilities/labelers.py
import tensorflow as tf import tensorflow.keras as keras def decay_weights(model, weight_decay_rate): """Calculates the loss for l2 weight decay and returns it.""" # @tf.function def _decay_weights(weights, weight_decay_rate): reg_loss = 0. for var in weights: reg_loss = reg_l...
model-patching-master
augmentation/utilities/losses.py
from typing import List import tensorflow as tf import tensorflow.keras as keras from augmentation.utilities.metrics import reset_metrics, update_metrics def evaluate_model(model: keras.Model, generator, metrics: List[keras.metrics.Metric], aggregate=None, ...
model-patching-master
augmentation/utilities/eval.py
import tensorflow as tf import tensorflow.keras as keras import numpy as np class LinearDecay(keras.optimizers.schedules.LearningRateSchedule): # https://github.com/LynnHo/CycleGAN-Tensorflow-2/blob/master/module.py # if `step` < `step_decay`: use fixed learning rate # else: linearly decay the learning ra...
model-patching-master
augmentation/utilities/optim.py
import tensorflow as tf import dataflow as D import time import numpy as np import datetime from multiprocessing import cpu_count from augmentation.augment.utils import compose_augmentations def benchmark(dataflow, num_epochs=2, sleep=0.): start_time = time.perf_counter() for epoch_num in range(num_epochs): ...
model-patching-master
augmentation/dataflows/utils.py
#!/usr/bin/env python3 # 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. """ This is the main script used for training Classy Vision jobs. This can be used for training on your local machine,...
cv_bias_amplification-main
my-project-release/my-project/classy_train.py
#!/usr/bin/env python3 # 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 pathlib import Path from classy_vision.generic.registry_utils import import_all_modules FILE_ROOT = Path(__file...
cv_bias_amplification-main
my-project-release/my-project/losses/__init__.py
#!/usr/bin/env python3 # 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.nn.functional as F from classy_vision.losses import ClassyLoss, register_loss @register_loss("one_hot_bi...
cv_bias_amplification-main
my-project-release/my-project/losses/one_hot_binary_ce_loss.py
#!/usr/bin/env python3 # 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 import copy import enum import json import logging import math import multiprocessing as mp import ti...
cv_bias_amplification-main
my-project-release/my-project/tasks/biasamp_classification_task.py
#!/usr/bin/env python3 # 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 traceback from pathlib import Path from classy_vision.generic.registry_utils import import_all_modules from cl...
cv_bias_amplification-main
my-project-release/my-project/tasks/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from torchvision.datasets import FashionMNIST import torch.utils.data import torch from torchvision import datasets, transforms import clas...
cv_bias_amplification-main
my-project-release/my-project/datasets/cifar100_random_sample.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from PIL import Image import numpy as np from typing import Any, Callable, Dict, List, Optional, Tuple, Union import json from classy_visio...
cv_bias_amplification-main
my-project-release/my-project/datasets/inversion_transforms.py
#!/usr/bin/env python3 # 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 Any, Callable, Dict, Optional, Union from classy_vision.dataset import ClassyDataset, register_dat...
cv_bias_amplification-main
my-project-release/my-project/datasets/cifar100.py
#!/usr/bin/env python3 # 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 pathlib import Path from classy_vision.generic.registry_utils import import_all_modules FILE_ROOT = Path(__file...
cv_bias_amplification-main
my-project-release/my-project/datasets/__init__.py
#!/usr/bin/env python3 # 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 Any, Callable, Dict, Optional, Union from classy_vision.dataset import ClassyDataset, register_dat...
cv_bias_amplification-main
my-project-release/my-project/datasets/fashionmnist.py
#!/usr/bin/env python3 # 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 Any, Callable, Dict, Optional, Union from classy_vision.dataset import ClassyDataset, register_dat...
cv_bias_amplification-main
my-project-release/my-project/datasets/cifar10_overlay.py
#!/usr/bin/env python3 # 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 pathlib import Path from classy_vision.generic.registry_utils import import_all_modules FILE_ROOT = Path(__file...
cv_bias_amplification-main
my-project-release/my-project/models/__init__.py
#!/usr/bin/env python3 # 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 Tensor import torch.nn as nn from typing import Type, Any, Callable, Union, List, Option...
cv_bias_amplification-main
my-project-release/my-project/models/custom_resnet.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/fashionmnist/scripts/training_measurements.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Run from within the /scripts folder. import json import numpy as np import pandas as pd import classy_vision.generic.util as util import...
cv_bias_amplification-main
my-project-release/my-project/configs/fashionmnist/scripts/generate_experiment_configs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_width/scripts/training_measurements.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import numpy as np import classy_vision.generic.util as util import random import pandas as pd import os CONFIG_PATH = os.pat...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_width/scripts/generate_experiment_configs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100/scripts/training_measurements_checkpoints.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import numpy as np import classy_vision.generic.util as util import random import pandas as pd import os CONFIG_PATH = os.pat...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100/scripts/generate_experiment_configs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar10_overlay/scripts/training_measurements.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import numpy as np import classy_vision.generic.util as util import random import pandas as pd import os CONFIG_PATH = os.path...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar10_overlay/scripts/generate_experiment_configs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_trainingsize/scripts/training_measurements.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import numpy as np import classy_vision.generic.util as util import random import pandas as pd import os CONFIG_PATH = os.pat...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_trainingsize/scripts/generate_experiment_configs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_regularization/scripts/training_measurements.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import numpy as np import classy_vision.generic.util as util import random import pandas as pd import os CONFIG_PATH = os.pat...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_regularization/scripts/generate_experiment_configs.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from copy import error import torch import torch.utils.data import ast import itertools import json import numpy as np import pandas as pd...
cv_bias_amplification-main
my-project-release/my-project/configs/cifar100_swapped/scripts/training_measurements_checkpoints.py