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 |
|---|---|---|---|---|---|---|
cmm_ts | cmm_ts-main/models/attention/InputAttention.py | import tensorflow as tf
import keras.backend as K
from keras.layers import *
class InputAttention(Layer):
def __init__(self, config, name = 'Attention'):
super(InputAttention, self).__init__(name = name)
self.config = config
def build(self, inputs):
# input_shape = batch x n_past x n... | 1,990 | 31.639344 | 102 | py |
cmm_ts | cmm_ts-main/models/attention/SelfAttention.py | import tensorflow as tf
import numpy as np
from keras.layers import *
from models.Constraints import *
import models.Words as W
import keras.backend as K
class SelfAttention(Layer):
def __init__(self, config, causal_vec : np.array, name = 'Attention'):
super(SelfAttention, self).__init__(name = name)
... | 1,508 | 38.710526 | 93 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="covidcast",
version="0.2.1", # also update in docs/conf.py
author="Alex Reinhart",
author_email="[email protected]",
description="Access COVID-19 data through the Delphi COVIDcast API... | 1,055 | 27.540541 | 72 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/tests/test_geography.py | import pytest
from covidcast import geography
@pytest.mark.parametrize("test_key, test_kwargs, expected", [
(
"not a fips",
{},
[None]
),
(
"42003",
{},
["Allegheny County"],
),
(
"4200",
{"ties_method... | 9,873 | 25.330667 | 99 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/tests/test_plotting.py | import os
from datetime import date
from unittest.mock import patch
import matplotlib
import platform
import geopandas as gpd
# for some reason gpd.testing gives "no attribute" so we'll import it explicitly
import geopandas.testing as gpd_testing
import numpy as np
import pandas as pd
import pytest
from covidcast impo... | 11,890 | 42.716912 | 143 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/tests/test_covidcast.py | import warnings
from datetime import date, datetime
from unittest.mock import patch
# Force tests to use a specific backend, so they reproduce across platforms
import matplotlib
matplotlib.use("AGG")
import pandas as pd
import numpy as np
import pytest
from epiweeks import Week
from covidcast import covidcast
from c... | 16,595 | 46.965318 | 118 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 2,310 | 34.015152 | 89 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/covidcast/plotting.py | """This contains the plotting and geo data management methods for the COVIDcast signals."""
import io
import warnings
from datetime import date, timedelta
from typing import Tuple, Any
import geopandas as gpd
import imageio
import numpy as np
import pandas as pd
import pkg_resources
from matplotlib import pyplot as p... | 26,547 | 52.309237 | 100 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/covidcast/errors.py | """Custom warnings and exceptions for covidcast functions."""
class NoDataWarning(Warning):
"""Warning raised when no data is returned on a given day by covidcast.signal()."""
| 182 | 29.5 | 87 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/covidcast/covidcast.py | """This is the client side library for accessing the COVIDcast API."""
import warnings
from datetime import timedelta, date
from functools import reduce
from typing import Union, Iterable, Tuple, List
import pandas as pd
import numpy as np
from delphi_epidata import Epidata
from epiweeks import Week
from .errors impo... | 24,833 | 44.566972 | 100 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/covidcast/__init__.py | """Fetch data from Delphi's COVIDcast API.
The COVIDcast API provides daily updated data on the COVID-19 pandemic in the
United States, including cases, deaths, medical records, nationwide symptom
surveys, and other data collated by the Delphi research group at Carnegie Mellon
University.
Functions:
* signal - Fetch... | 739 | 36 | 80 | py |
covidcast | covidcast-main/Python-packages/covidcast-py/covidcast/geography.py | """Functions for converting and mapping between geographic types."""
import re
import warnings
from typing import Union, Iterable
import pandas as pd
import pkg_resources
COUNTY_CENSUS = pd.read_csv(
pkg_resources.resource_filename(__name__, "geo_mappings/county_census.csv"), dtype=str)
MSA_CENSUS = pd.read_csv(
... | 17,755 | 54.836478 | 100 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-2.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "state")
covidcast.plot(data)
plt.show() | 238 | 38.833333 | 126 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-7.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day=date(2020, 8, 4), end_day=date(2020, 8, 4), geo_type="county")
geo_data = covidcast.get_geo_df(data)
CA = geo_data.loc[geo_data.state_fips == "06",:]
CA = CA.to_crs("EPSG:3395")... | 399 | 39 | 125 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-1.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "county")
covidcast.plot(data)
plt.show() | 239 | 39 | 127 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-5.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "msa")
covidcast.plot(data, plot_type="bubble")
plt.show() | 256 | 41.833333 | 124 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-3.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "msa")
covidcast.plot(data)
plt.show() | 236 | 38.5 | 124 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-4.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "hrr")
covidcast.plot(data)
plt.show() | 236 | 38.5 | 124 | py |
covidcast | covidcast-main/docs/covidcast-py/plot_directive/plot_examples-6.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day=date(2020,8,3), end_day=date(2020,8,4), geo_type="county")
covidcast.plot(data, cmap="viridis", edgecolor="0.8")
plt.show() | 266 | 43.5 | 121 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/ff9d0adfb7c8ffca0588503bd7c99492/plot_examples-6.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day=date(2020,8,3), end_day=date(2020,8,4), geo_type="county")
covidcast.plot(data, cmap="viridis", edgecolor="0.8")
plt.show() | 266 | 43.5 | 121 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/e0a8df2a9fc8b7b132f415bd8ef2bdc4/plot_examples-7.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day=date(2020, 8, 4), end_day=date(2020, 8, 4), geo_type="county")
geo_data = covidcast.get_geo_df(data)
CA = geo_data.loc[geo_data.state_fips == "06",:]
CA = CA.to_crs("EPSG:3395")... | 399 | 39 | 125 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/45737588e68d40bc70776db507250bec/plot_examples-2.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "state")
covidcast.plot(data)
plt.show() | 238 | 38.833333 | 126 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/571325b5380a37ed852fc9bdad934c81/plot_examples-3.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "msa")
covidcast.plot(data)
plt.show() | 236 | 38.5 | 124 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/f1cd4c7dca77dd16a6bb13e5255f47b8/plot_examples-4.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "hrr")
covidcast.plot(data)
plt.show() | 236 | 38.5 | 124 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/c366b60b64ba94fc749687d0d5a05bf0/plot_examples-1.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "county")
covidcast.plot(data)
plt.show() | 239 | 39 | 127 | py |
covidcast | covidcast-main/docs/covidcast-py/html/_downloads/376487b264df9d30227aca49c0e60421/plot_examples-5.py | import covidcast
from datetime import date
from matplotlib import pyplot as plt
data = covidcast.signal("fb-survey", "smoothed_cli", start_day = date(2020,8,4), end_day = date(2020,8,4), geo_type = "msa")
covidcast.plot(data, plot_type="bubble")
plt.show() | 256 | 41.833333 | 124 | py |
UL-CALC | UL-CALC-master/upper_limit.py | '''
Program to create artificial halo into visibility and estimate upper limit to halo flux
NOTE: Currently this program needs visibilities with a single spectral window
--------------------------------------------------------
Main Program
STAGES:
1) Estimate RMS : BANE is used to estimate the rms in a defined regio... | 3,300 | 39.753086 | 106 | py |
UL-CALC | UL-CALC-master/modules.py | execfile('params.py')
execfile('mylogging.py')
def prompt_with_timeout(t):
import sys
from select import select
print('Press Enter to continue...')
rlist, _, _ = select([sys.stdin], [], [], t)
if rlist:
s = sys.stdin.readline()
else:
print("No input received. Moving on...")
d... | 10,795 | 37.834532 | 173 | py |
UL-CALC | UL-CALC-master/create_contours.py | import sys, os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse,Rectangle
from astropy.wcs import WCS
from astropy.visualization import ZScaleInterval,PercentileInterval,MinMaxInterval
from astropy.io import fits
from astropy.nddata.utils import Cutout2D
from astropy import uni... | 2,501 | 33.75 | 92 | py |
UL-CALC | UL-CALC-master/mylogging.py | import logging
import datetime
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logger = logging.getLogger()
now = datetime.datetime.now()
t = now.strftime("%Y%m%d-%H%M%S")
logname = 'ulc-{}-{}.log'.format(cluster.replace(' ',''), t)
logging.basicConfig(
filename=srcdir + '/' + logna... | 816 | 29.259259 | 80 | py |
UL-CALC | UL-CALC-master/params.py | # INPUT PARAMETERS (Descriptions at the end)
bane_pth= '/path/to/BANE'
srcdir = '/path/to/source/directory'
visname = '<source>.MS'
imgname = '<source>.IMAGE'
vispath = os.path.join(srcdir, visname)
imgpath = os.path.join(srcdir, imgname)
cluster = '<source-name>'
if cluster != '':
z = float(Ned.query_object(clust... | 2,663 | 28.6 | 113 | py |
TreEnhance | TreEnhance-master/ptcolor.py | """Pytorch routines for color conversions and management.
All color arguments are given as 4-dimensional tensors representing
batch of images (Bx3xHxW). RGB values are supposed to be in the
range 0-1 (but values outside the range are tolerated).
Some examples:
>>> rgb = torch.tensor([0.8, 0.4, 0.2]).view(1, 3, 1, 1... | 11,528 | 28.561538 | 113 | py |
TreEnhance | TreEnhance-master/data_Prep.py | import torch
import torch.utils
import torch.utils.data
import os
from torchvision import transforms
from random import random, sample
from PIL import Image
class Dataset_LOL(torch.utils.data.Dataset):
def __init__(self, raw_dir, exp_dir, subset_img=None, size=None, training=True):
self.raw_dir = raw_dir
... | 1,956 | 32.169492 | 89 | py |
TreEnhance | TreEnhance-master/training.py | #!/usr/bin/env python3
import torch
import torch.utils
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
import collections
import numpy as np
import random
from data_Prep import LoadDataset, Dataset_LOL
import Actions as Actions
import warnings
import Network
import os
from matplotlib import py... | 11,048 | 36.327703 | 118 | py |
TreEnhance | TreEnhance-master/Actions.py | import torch
import torch.utils
import torch.utils.data
from ColorAlgorithms import Gray_World, MaxRGB, saturation, hue
from torchvision import transforms
from PIL import ImageFilter
def select(img, act):
if act == 0:
return gamma_corr(img, 0.6, 0)
elif act == 1:
return gamma_corr(img, 0.6, 1)... | 3,418 | 27.491667 | 119 | py |
TreEnhance | TreEnhance-master/mcts.py | """Implementation of Monte Carlo Tree Search algorithm.
This implementation allows "parallel" multi-root trees. This does not
enable parallel computation, but reduces significantly the python
overhead thanks to numpy optimized operations.
The search can be configured by providing custom transition and
evaluation fun... | 13,523 | 37.862069 | 99 | py |
TreEnhance | TreEnhance-master/Network.py | import torch
from torchvision.models import resnet18
import torch.nn as nn
class ModifiedResnet(nn.Module):
def __init__(self, n_actions, Dropout=None):
super(ModifiedResnet, self).__init__()
self.model = resnet18(pretrained=False)
num_ftrs = self.model.fc.in_features
self.model.fc... | 879 | 34.2 | 119 | py |
TreEnhance | TreEnhance-master/metrics.py | import torch
def PSNR(img, gt):
mseL = torch.nn.MSELoss()
mse = mseL(img, gt)
if mse != 0:
print(20 * torch.log10(1 / torch.sqrt(mse)))
return 20 * torch.log10(1 / torch.sqrt(mse))
return 20 * torch.log10(1 / torch.sqrt(torch.tensor(1e-9)))
| 275 | 24.090909 | 63 | py |
TreEnhance | TreEnhance-master/evaluation.py | #!/usr/bin/env python3
import warnings
import torch
import torch.utils
import torch.utils.data
import numpy as np
from data_Prep import Dataset_LOL
import Actions as Actions
import Network
import tqdm
import mcts
import argparse
from ptcolor import deltaE94, rgb2lab
warnings.filterwarnings("ignore")
NUM_ACTIONS = 37
M... | 5,424 | 30.358382 | 94 | py |
TreEnhance | TreEnhance-master/ColorAlgorithms.py | import torch
from torchvision.transforms.functional import adjust_saturation, adjust_hue
def Gray_World(img):
m = img.mean(-2, True).mean(-1, True)
img = img / torch.clamp(m, min=1e-3)
ma = img.max(-1, True).values.max(-2, True).values.max(-3, True).values
return img / torch.clamp(ma, min=1e-3)
def ... | 584 | 24.434783 | 77 | py |
uSDN | uSDN-master/utils.py | import numpy as np
import scipy.io as sio
import collections
import scipy.misc
def loadData(mname):
return sio.loadmat(mname)
def readData(filename,num=10):
input = loadData(filename)
data = collections.namedtuple('data', ['hyperLR', 'multiHR', 'hyperHR',
'dimLR... | 2,846 | 48.086207 | 113 | py |
uSDN | uSDN-master/uSDN.py | from tensorflow.python.client import device_lib
from utils import *
from pbAuto_uSDN import*
import time
import os
import argparse
parser = argparse.ArgumentParser(description='uSDN for HSI-SR')
parser.add_argument('--cuda', default='0', help='Choose GPU.')
parser.add_argument('--filenum', type=str, default='balloons_... | 2,351 | 29.545455 | 109 | py |
uSDN | uSDN-master/pbAuto_uSDN.py | import tensorflow as tf
import numpy as np
import math
# import matplotlib.pyplot as plt
import scipy.io as sio
import random
import scipy.misc
import os
from tensorflow.python.training import saver
import tensorflow.contrib.layers as ly
from os.path import join as pjoin
from numpy import *
import numpy.matlib
import s... | 24,758 | 45.539474 | 180 | py |
deep-viz-keras | deep-viz-keras-master/saliency.py | # Copyright 2017 Google Inc. 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 applicable law or ag... | 2,836 | 35.371795 | 93 | py |
deep-viz-keras | deep-viz-keras-master/integrated_gradients.py | # Copyright 2017 Google Inc. 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 applicable law or ag... | 1,506 | 34.880952 | 84 | py |
deep-viz-keras | deep-viz-keras-master/guided_backprop.py | # Copyright 2017 Google Inc. 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 applicable law or ag... | 3,669 | 42.176471 | 106 | py |
deep-viz-keras | deep-viz-keras-master/utils.py | def show_image(image, grayscale = True, ax=None, title=''):
if ax is None:
plt.figure()
plt.axis('off')
if len(image.shape) == 2 or grayscale == True:
if len(image.shape) == 3:
image = np.sum(np.abs(image), axis=2)
vmax = np.percentile(image, 99)
... | 689 | 25.538462 | 65 | py |
deep-viz-keras | deep-viz-keras-master/visual_backprop.py | from saliency import SaliencyMask
import numpy as np
import keras.backend as K
from keras.layers import Input, Conv2DTranspose
from keras.models import Model
from keras.initializers import Ones, Zeros
class VisualBackprop(SaliencyMask):
"""A SaliencyMask class that computes saliency masks with VisualBackprop (http... | 2,406 | 40.5 | 112 | py |
lrec2020-coref | lrec2020-coref-master/scripts/create_crossval_train_predict.py | import sys
def gen(path_to_scorer, train_out_file, pred_out_file):
train_out=open(train_out_file, "w", encoding="utf-8")
pred_out=open(pred_out_file, "w", encoding="utf-8")
for i in range(10):
train_out.write ("python3 scripts/bert_coref.py -m train -w models/crossval/%s.model -t data/litbank_tenfold_splits/%s/t... | 774 | 47.4375 | 277 | py |
lrec2020-coref | lrec2020-coref-master/scripts/bert_coref.py | import re
import os
from collections import Counter
import sys
import argparse
import pytorch_pretrained_bert
from pytorch_pretrained_bert.modeling import BertPreTrainedModel, BertModel, BertConfig
from pytorch_pretrained_bert import BertTokenizer
from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_... | 24,602 | 24.233846 | 255 | py |
lrec2020-coref | lrec2020-coref-master/scripts/calc_coref_metrics.py | import subprocess, re, sys
def get_coref_score(metric, path_to_scorer, gold=None, preds=None):
output=subprocess.check_output(["perl", path_to_scorer, metric, preds, gold]).decode("utf-8")
output=output.split("\n")[-3]
matcher=re.search("Coreference: Recall: \(.*?\) (.*?)% Precision: \(.*?\) (.*?)% F1: (.*?)%", ou... | 1,191 | 30.368421 | 102 | py |
lrec2020-coref | lrec2020-coref-master/scripts/create_crossval_train.py | import sys
def gen(path_to_scorer, train_out_file, pred_out_file):
train_out=open(train_out_file, "w", encoding="utf-8")
pred_out=open(pred_out_file, "w", encoding="utf-8")
for i in range(10):
train_out.write ("python3 scripts/bert_coref.py -m train -w models/crossval/%s.model -t data/litbank_tenfold_splits/%s/t... | 774 | 47.4375 | 277 | py |
lrec2020-coref | lrec2020-coref-master/scripts/create_crossval.py | """
Create 10-fold cross-validation data from LitBank data.
"""
import sys, os, re
def create_data(ids, infolder, outfile):
out=open(outfile, "w", encoding="utf-8")
for idd in ids:
infile="%s/%s.conll" % (infolder, idd)
with open(infile) as file:
for line in file:
out.write("%s\n" % line.rstrip())
... | 1,431 | 24.122807 | 113 | py |
NGS | NGS-master/main_SNPDistancesWholeGenomes.py | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 17:46:00 2018
Changchuan Yin
Dept. of Mathematics, Statistics and Computer Science.
University of Illinois at Chicago
Email: [email protected]
Citation:
Yin., C., & Yau., S.S.-T (2018). Whole genome single nucleotide polymorphism genotyping of Staphylococcus aureus.
Comm... | 3,494 | 50.397059 | 216 | py |
NGS | NGS-master/gene_snp.py | # -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 17:46:00 2018
Changchuan Yin
Dept. of Mathematics, Statistics and Computer Science.
University of Illinois at Chicago
Email: [email protected]
Citation:
Yin., C., & Yau., S.S.-T (2018). Whole genome single nucleotide polymorphism genotyping of Stap... | 8,858 | 26.512422 | 189 | py |
NGS | NGS-master/main_SNPDistancesHighLowSNPs.py | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 17:46:00 2018
Changchuan Yin
Dept. of Mathematics, Statistics and Computer Science.
University of Illinois at Chicago
Email: [email protected]
Citation:
Yin., C., & Yau., S.S.-T (2018). Whole genome single nucleotide polymorphism genotyping of Staphylococcus aureus.
Comm... | 3,458 | 33.939394 | 151 | py |
NGS | NGS-master/main_SNPHistograms.py | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 17:46:00 2018
Changchuan Yin
Dept. of Mathematics, Statistics and Computer Science.
University of Illinois at Chicago
Email: [email protected]
Citation:
Yin., C., & Yau., S.S.-T (2018). Whole genome single nucleotide polymorphism genotyping of Staphylococcus aureus.
Comm... | 3,677 | 31.548673 | 189 | py |
CGMM | CGMM-master/score.py | from typing import List
import torch
from pydgn.training.callback.metric import Metric
class CGMMCompleteLikelihoodScore(Metric):
@property
def name(self) -> str:
return 'Complete Log Likelihood'
def __init__(self, use_as_loss=False, reduction='mean', use_nodes_batch_size=True):
super()... | 2,750 | 36.175676 | 114 | py |
CGMM | CGMM-master/cgmm_embedding_task.py | import os
import shutil
import torch
from cgmm_incremental_task import CGMMTask
# This works with graph classification only
from pydgn.static import LOSS, SCORE
class EmbeddingCGMMTask(CGMMTask):
def run_valid(self, dataset_getter, logger):
"""
This function returns the training and validation... | 7,955 | 53.122449 | 162 | py |
CGMM | CGMM-master/emission.py | import math
import scipy
import scipy.cluster
import scipy.cluster.vq
import torch
# Interface for all emission distributions
from torch.nn import ModuleList
class EmissionDistribution(torch.nn.Module):
def __init__(self):
super().__init__()
def init_accumulators(self):
raise NotImplementedE... | 22,661 | 40.734807 | 120 | py |
CGMM | CGMM-master/readout.py | import torch
from pydgn.model.interface import ReadoutInterface
class CGMMGraphReadout(ReadoutInterface):
def __init__(self, dim_node_features, dim_edge_features, dim_target, config):
super().__init__(dim_node_features, dim_edge_features, dim_target, config)
embeddings_node_features = dim_node_f... | 641 | 32.789474 | 82 | py |
CGMM | CGMM-master/cgmm.py | import torch
from pydgn.model.interface import ModelInterface
from util import compute_bigram, compute_unigram
from torch_geometric.nn import global_mean_pool, global_add_pool
from torch_scatter import scatter_add, scatter_max
class CGMM(ModelInterface):
def __init__(self, dim_node_features, dim_edge_features, ... | 22,943 | 43.638132 | 120 | py |
CGMM | CGMM-master/loss.py | from pydgn.training.callback.metric import Metric
class CGMMLoss(Metric):
@property
def name(self) -> str:
return 'CGMM Loss'
def __init__(self, use_as_loss=True, reduction='mean', use_nodes_batch_size=True):
super().__init__(use_as_loss=use_as_loss, reduction=reduction, use_nodes_batch_s... | 1,555 | 32.826087 | 113 | py |
CGMM | CGMM-master/probabilistic_readout.py | from typing import Tuple, Optional, List
import torch
from pydgn.experiment.util import s2c
class ProbabilisticReadout(torch.nn.Module):
def __init__(self, dim_node_features, dim_edge_features, dim_target, config):
super().__init__()
self.K = dim_node_features
self.Y = dim_target
... | 3,817 | 33.396396 | 82 | py |
CGMM | CGMM-master/cgmm_incremental_task.py | import os
import shutil
import torch
from pydgn.experiment.experiment import Experiment
from pydgn.experiment.util import s2c
from pydgn.static import LOSS, SCORE
from torch.utils.data.sampler import SequentialSampler
from torch_geometric.data import Data
class CGMMTask(Experiment):
def __init__(self, model_con... | 25,222 | 54.557269 | 240 | py |
CGMM | CGMM-master/util.py | from typing import Optional, Tuple, List
import torch
import torch_geometric
def extend_lists(data_list: Optional[Tuple[Optional[List[torch.Tensor]]]],
new_data_list: Tuple[Optional[List[torch.Tensor]]]) -> Tuple[Optional[List[torch.Tensor]]]:
r"""
Extends the semantic of Python :func:`exten... | 8,585 | 41.50495 | 160 | py |
CGMM | CGMM-master/__init__.py | 0 | 0 | 0 | py | |
CGMM | CGMM-master/incremental_engine.py | import torch
from pydgn.training.engine import TrainingEngine
from util import extend_lists, to_tensor_lists
class IncrementalTrainingEngine(TrainingEngine):
def __init__(self, engine_callback, model, loss, **kwargs):
super().__init__(engine_callback, model, loss, **kwargs)
def _to_list(self, data_li... | 838 | 40.95 | 104 | py |
CGMM | CGMM-master/cgmm_classifier_task.py | import os
import torch
from cgmm_incremental_task import CGMMTask
from pydgn.experiment.util import s2c
from pydgn.static import LOSS, SCORE
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader
# This works with graph classification only
class ClassifierCGMMTask(CGMMTask):
def run... | 9,149 | 55.481481 | 146 | py |
CGMM | CGMM-master/provider.py | import random
import numpy as np
from pydgn.data.dataset import ZipDataset
from pydgn.data.provider import DataProvider
from pydgn.data.sampler import RandomSampler
from torch.utils.data import Subset
def seed_worker(exp_seed, worker_id):
np.random.seed(exp_seed + worker_id)
random.seed(exp_seed + worker_id)... | 2,201 | 37.631579 | 118 | py |
CGMM | CGMM-master/optimizer.py | from pydgn.training.callback.optimizer import Optimizer
from pydgn.training.event.handler import EventHandler
class CGMMOptimizer(Optimizer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_eval_epoch_start(self, state):
"""
Use the "return_node_embeddings" field of th... | 1,014 | 29.757576 | 113 | py |
BVQI | BVQI-master/temporal_naturalness.py | import torch
import argparse
import pickle as pkl
import numpy as np
import math
import torch
import torch.nn.functional as F
import yaml
from scipy.stats import pearsonr, spearmanr
from scipy.stats import kendalltau as kendallr
from tqdm import tqdm
from sklearn import decomposition
import time
from buona_vista imp... | 4,901 | 30.625806 | 96 | py |
BVQI | BVQI-master/semantic_affinity.py | ## Contributed by Teo Haoning Wu, Daniel Annan Wang
import argparse
import pickle as pkl
import open_clip
import numpy as np
import torch
import yaml
from scipy.stats import pearsonr, spearmanr
from scipy.stats import kendalltau as kendallr
from tqdm import tqdm
from buona_vista import datasets
def rescale(x):
... | 3,856 | 30.614754 | 96 | py |
BVQI | BVQI-master/spatial_naturalness.py | # Contributed by Teo Haoning Wu, Erli Zhang Karl
import argparse
import glob
import math
import os
import pickle as pkl
from collections import OrderedDict
import decord
import numpy as np
import torch
import torchvision as tv
import yaml
from pyiqa import create_metric
from pyiqa.default_model_configs import DEFAULT... | 3,380 | 28.657895 | 88 | py |
BVQI | BVQI-master/prompt_tuning.py | import os, glob
import argparse
import pickle as pkl
import random
from copy import deepcopy
import open_clip
import numpy as np
import torch
import torch.nn as nn
import yaml
from scipy.stats import pearsonr, spearmanr
from scipy.stats import kendalltau as kendallr
from tqdm import tqdm
from buona_vista import dat... | 17,790 | 39.251131 | 158 | py |
BVQI | BVQI-master/load_features.py | import os
import argparse
import pickle as pkl
import random
import open_clip
import numpy as np
import torch
import torch.nn as nn
import yaml
from scipy.stats import pearsonr, spearmanr
from scipy.stats import kendalltau as kendallr
from tqdm import tqdm
from buona_vista import datasets
import wandb
def rescale... | 2,446 | 28.841463 | 100 | py |
BVQI | BVQI-master/pyiqa/api_helpers.py | import fnmatch
import re
from .default_model_configs import DEFAULT_CONFIGS
from .models.inference_model import InferenceModel
from .utils import get_root_logger
def create_metric(metric_name, as_loss=False, device=None, **kwargs):
assert (
metric_name in DEFAULT_CONFIGS.keys()
), f"Metric {metric_na... | 2,217 | 35.360656 | 112 | py |
BVQI | BVQI-master/pyiqa/test.py | import logging
from os import path as osp
import torch
from pyiqa.data import build_dataloader, build_dataset
from pyiqa.models import build_model
from pyiqa.utils import get_env_info, get_root_logger, get_time_str, make_exp_dirs
from pyiqa.utils.options import dict2str, parse_options
def test_pipeline(root_path):
... | 1,864 | 30.083333 | 87 | py |
BVQI | BVQI-master/pyiqa/default_model_configs.py | import fnmatch
import re
from collections import OrderedDict
IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
DEFAULT_CONFIGS = OrderedDict(
{
"ahiq": {
"metric_opts": {
"type": "AHIQ",
},
"metric_mode": "FR",
... | 6,554 | 25.431452 | 72 | py |
BVQI | BVQI-master/pyiqa/version.py | # GENERATED VERSION FILE
# TIME: Wed Dec 7 13:57:45 2022
__version__ = "0.1.5"
__gitsha__ = "3619109"
version_info = (0, 1, 5)
| 128 | 20.5 | 32 | py |
BVQI | BVQI-master/pyiqa/train_nsplits.py | import datetime
import logging
import os
import time
from os import path as osp
import numpy as np
import torch
from pyiqa.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher
from pyiqa.models import build_model
from pyiqa.train import create_train_val_dataloader, init_tb_loggers, train_pipeline
from pyiqa.... | 2,387 | 34.641791 | 84 | py |
BVQI | BVQI-master/pyiqa/__init__.py | # flake8: noqa
from .api_helpers import *
from .archs import *
from .data import *
from .default_model_configs import *
from .losses import *
from .matlab_utils import *
from .metrics import *
from .models import *
from .test import *
from .train import *
from .utils import *
from .version import __gitsha__, __version_... | 322 | 22.071429 | 44 | py |
BVQI | BVQI-master/pyiqa/train.py | import datetime
import logging
import math
import os
import time
from os import path as osp
import torch
from pyiqa.data import build_dataloader, build_dataset
from pyiqa.data.data_sampler import EnlargedSampler
from pyiqa.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher
from pyiqa.models import build_mo... | 11,816 | 36.39557 | 103 | py |
BVQI | BVQI-master/pyiqa/matlab_utils/functions.py | import math
import numpy as np
import torch
import torch.nn.functional as F
from pyiqa.archs.arch_util import ExactPadding2d, symm_pad, to_2tuple
def fspecial(size=None, sigma=None, channels=1, filter_type="gaussian"):
r"""Function same as 'fspecial' in MATLAB, only support gaussian now.
Args:
size ... | 10,439 | 33.569536 | 124 | py |
BVQI | BVQI-master/pyiqa/matlab_utils/math_util.py | r"""Mathematical utilities
Created by: https://github.com/tomrunia/PyTorchSteerablePyramid/blob/master/steerable/math_utils.py
Modified by: Jiadi Mo (https://github.com/JiadiMo)
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import torch
def abs(x):
return torch.sqrt(x... | 2,611 | 26.787234 | 99 | py |
BVQI | BVQI-master/pyiqa/matlab_utils/scfpyr_util.py | r"""Complex-valued steerable pyramid
Created by: https://github.com/tomrunia/PyTorchSteerablePyramid
Modified by: Jiadi Mo (https://github.com/JiadiMo)
Refer to:
- Offical Matlab code from https://github.com/LabForComputationalVision/matlabPyrTools/blob/master/buildSCFpyr.m;
- Original Python code from https... | 8,552 | 36.678414 | 121 | py |
BVQI | BVQI-master/pyiqa/matlab_utils/__init__.py | """This folder contains pytorch implementations of matlab functions.
And should produce the same results as matlab.
Note: to enable GPU acceleration, all functions take batched tensors as inputs,
and return batched results.
"""
from .functions import *
from .resize import imresize
from .scfpyr_util import SCFpyr_PyTo... | 529 | 19.384615 | 79 | py |
BVQI | BVQI-master/pyiqa/matlab_utils/resize.py | """
A standalone PyTorch implementation for fast and efficient bicubic resampling.
The resulting values are the same to MATLAB function imresize('bicubic').
## Author: Sanghyun Son
## Email: [email protected] (primary), [email protected] (secondary)
## Version: 1.2.0
## Last update: July 9th, 2020 ... | 12,696 | 27.404922 | 83 | py |
BVQI | BVQI-master/pyiqa/matlab_utils/.ipynb_checkpoints/functions-checkpoint.py | import math
import numpy as np
import torch
import torch.nn.functional as F
from pyiqa.archs.arch_util import ExactPadding2d, symm_pad, to_2tuple
def fspecial(size=None, sigma=None, channels=1, filter_type="gaussian"):
r"""Function same as 'fspecial' in MATLAB, only support gaussian now.
Args:
size ... | 10,439 | 33.569536 | 124 | py |
BVQI | BVQI-master/pyiqa/models/lr_scheduler.py | import math
from collections import Counter
from torch.optim.lr_scheduler import _LRScheduler
class MultiStepRestartLR(_LRScheduler):
"""MultiStep with restarts learning rate scheme.
Args:
optimizer (torch.nn.optimizer): Torch optimizer.
milestones (list): Iterations that will decrease learn... | 4,268 | 32.880952 | 85 | py |
BVQI | BVQI-master/pyiqa/models/base_model.py | import os
import time
from collections import OrderedDict
from copy import deepcopy
import torch
from torch.nn.parallel import DataParallel, DistributedDataParallel
from pyiqa.models import lr_scheduler as lr_scheduler
from pyiqa.utils import get_root_logger
from pyiqa.utils.dist_util import master_only
class BaseM... | 16,657 | 36.859091 | 104 | py |
BVQI | BVQI-master/pyiqa/models/hypernet_model.py | from collections import OrderedDict
import torch
from pyiqa.metrics import calculate_metric
from pyiqa.utils.registry import MODEL_REGISTRY
from .general_iqa_model import GeneralIQAModel
@MODEL_REGISTRY.register()
class HyperNetModel(GeneralIQAModel):
"""General module to train an IQA network."""
def test... | 1,260 | 28.325581 | 86 | py |
BVQI | BVQI-master/pyiqa/models/wadiqam_model.py | from collections import OrderedDict
from pyiqa.metrics import calculate_metric
from pyiqa.utils.registry import MODEL_REGISTRY
from .general_iqa_model import GeneralIQAModel
@MODEL_REGISTRY.register()
class WaDIQaMModel(GeneralIQAModel):
"""General module to train an IQA network."""
def setup_optimizers(se... | 1,014 | 29.757576 | 84 | py |
BVQI | BVQI-master/pyiqa/models/dbcnn_model.py | from collections import OrderedDict
from os import path as osp
import torch
from tqdm import tqdm
from pyiqa.archs import build_network
from pyiqa.losses import build_loss
from pyiqa.metrics import calculate_metric
from pyiqa.models import lr_scheduler as lr_scheduler
from pyiqa.utils import get_root_logger, imwrite,... | 1,797 | 31.690909 | 79 | py |
BVQI | BVQI-master/pyiqa/models/sr_model.py | from collections import OrderedDict
from os import path as osp
import torch
from tqdm import tqdm
from pyiqa.archs import build_network
from pyiqa.losses import build_loss
from pyiqa.metrics import calculate_metric
from pyiqa.utils import get_root_logger, imwrite, tensor2img
from pyiqa.utils.registry import MODEL_REG... | 9,927 | 35.77037 | 112 | py |
BVQI | BVQI-master/pyiqa/models/pieapp_model.py | from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from pyiqa.metrics.correlation_coefficient import calculate_rmse
from pyiqa.utils.registry import MODEL_REGISTRY
from .general_iqa_model import GeneralIQAModel
@MODEL_REGI... | 2,271 | 32.910448 | 130 | py |
BVQI | BVQI-master/pyiqa/models/general_iqa_model.py | from collections import OrderedDict
from os import path as osp
import torch
from tqdm import tqdm
from pyiqa.archs import build_network
from pyiqa.losses import build_loss
from pyiqa.metrics import calculate_metric
from pyiqa.utils import get_root_logger, imwrite, tensor2img
from pyiqa.utils.registry import MODEL_REG... | 8,455 | 36.087719 | 112 | py |
BVQI | BVQI-master/pyiqa/models/bapps_model.py | import os.path as osp
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from pyiqa.metrics import calculate_metric
from pyiqa.utils.registry import MODEL_REGISTRY
from .general_iqa_model import GeneralIQAModel
@MODEL_REGI... | 5,987 | 36.898734 | 125 | py |
BVQI | BVQI-master/pyiqa/models/__init__.py | import importlib
from copy import deepcopy
from os import path as osp
from pyiqa.utils import get_root_logger, scandir
from pyiqa.utils.registry import MODEL_REGISTRY
__all__ = ["build_model"]
# automatically scan and import model modules for registry
# scan all the files under the 'models' folder and collect files ... | 1,031 | 26.157895 | 76 | py |
BVQI | BVQI-master/pyiqa/models/inference_model.py | from collections import OrderedDict
import torch
import torchvision as tv
from pyiqa.default_model_configs import DEFAULT_CONFIGS
from pyiqa.utils.img_util import imread2tensor
from pyiqa.utils.registry import ARCH_REGISTRY
class InferenceModel(torch.nn.Module):
"""Common interface for quality inference of imag... | 2,613 | 36.884058 | 95 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.