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
drizzle
drizzle-master/drizzle/tests/test_drizzle.py
import math import os import pytest import numpy as np from astropy import wcs from astropy.io import fits from drizzle import drizzle, cdrizzle TEST_DIR = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = os.path.join(TEST_DIR, 'data') ok = False def bound_image(image): """ Compute region where ima...
20,424
30.520062
83
py
drizzle
drizzle-master/drizzle/tests/test_pixmap.py
import os.path import numpy as np from numpy.testing import assert_equal, assert_almost_equal from astropy import wcs from astropy.io import fits from drizzle import calc_pixmap TEST_DIR = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = os.path.join(TEST_DIR, 'data') def test_map_rectangular(): """ ...
2,061
25.435897
67
py
drizzle
drizzle-master/drizzle/tests/__init__.py
0
0
0
py
Ranger-Deep-Learning-Optimizer
Ranger-Deep-Learning-Optimizer-master/setup.py
#!/usr/bin/env python import os from setuptools import find_packages, setup def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='ranger', version='0.1.dev0', packages=find_packages( exclude=['tests', '*.tests', '*.tests.*', 't...
696
24.814815
67
py
Ranger-Deep-Learning-Optimizer
Ranger-Deep-Learning-Optimizer-master/ranger/rangerqh.py
# RangerQH - @lessw2020 github # Combines Quasi Hyperbolic momentum with Hinton Lookahead. # https://arxiv.org/abs/1810.06801v4 (QH paper) # #Lookahead paper --> MZhang,G Hinton https://arxiv.org/abs/1907.08610 # Some portions = Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed un...
6,752
35.901639
107
py
Ranger-Deep-Learning-Optimizer
Ranger-Deep-Learning-Optimizer-master/ranger/ranger913A.py
# Ranger deep learning optimizer - RAdam + Lookahead + calibrated adaptive LR combined. # https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer # Ranger has now been used to capture 12 records on the FastAI leaderboard. #This version = 9.13.19A #Credits: #RAdam --> https://github.com/LiyuanLucasLiu/RAdam #L...
8,362
39.400966
133
py
Ranger-Deep-Learning-Optimizer
Ranger-Deep-Learning-Optimizer-master/ranger/ranger.py
# Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer. # https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer # and/or # https://github.com/lessw2020/Best-Deep-Learning-Optimizers # Ranger has now been used to capture 12 records on the FastAI leaderboard. ...
7,915
41.789189
169
py
Ranger-Deep-Learning-Optimizer
Ranger-Deep-Learning-Optimizer-master/ranger/ranger2020.py
# Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer. # https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer # and/or # https://github.com/lessw2020/Best-Deep-Learning-Optimizers # Ranger has been used to capture 12 records on the FastAI leaderboard. # Th...
9,051
42.311005
176
py
Ranger-Deep-Learning-Optimizer
Ranger-Deep-Learning-Optimizer-master/ranger/__init__.py
from .ranger import Ranger from .ranger913A import RangerVA from .rangerqh import RangerQH
91
22
32
py
RADio
RADio-main/data_preprocessing.py
import datetime import dart.Util import dart.preprocess.downloads import dart.preprocess.nlp import dart.preprocess.enrich_articles import dart.preprocess.identify_stories import dart.preprocess.recommendations def main(): config = dart.Util.read_full_config_file() # downloads external data sources ...
1,191
29.564103
86
py
RADio
RADio-main/metrics_calculation.py
import datetime import dart.Util import dart.metrics.start_calculations def main(): # step 0: load config file config = dart.Util.read_full_config_file() articles, recommendations, behavior_file = dart.Util.read_files() print(str(datetime.datetime.now()) + "\tMetrics") dart.metrics.start_calcul...
445
22.473684
113
py
RADio
RADio-main/setup.py
# TO DO
7
7
7
py
RADio
RADio-main/top_analysis.py
import dart.Util import pandas as pd from random import sample import itertools from dart.external.rbo import rbo pd.set_option('display.float_format', '{:.5f}'.format) config = dart.Util.read_full_config_file() articles = dart.Util.read_pickle(config['articles']) recommendations = dart.Util.read_pickle(config['reco...
4,305
34.295082
101
py
RADio
RADio-main/dart/Util.py
import json import csv import numpy as np import random import string import pandas as pd import os from datetime import datetime import pickle from pathlib import Path ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.dirname(ROOT_DIR) def read_config_file(): with open(os.path.join(BASE_...
3,424
28.025424
176
py
RADio
RADio-main/dart/__init__.py
0
0
0
py
RADio
RADio-main/dart/external/kl_divergence.py
import numpy as np from scipy.stats import entropy from numpy.linalg import norm import math def opt_merge_max_mappings(dict1, dict2): """ Merges two dictionaries based on the largest value in a given mapping. Parameters ---------- dict1 : Dict[Any, Comparable] dict2 : Dict[Any, Comparable] Re...
2,641
29.72093
111
py
RADio
RADio-main/dart/external/__init__.py
0
0
0
py
RADio
RADio-main/dart/external/discount.py
import math def harmonic_number(n): """Returns an approximate value of n-th harmonic number. http://en.wikipedia.org/wiki/Harmonic_number """ # Euler-Mascheroni constant gamma = 0.57721566490153286060651209008240243104215933593992 return gamma + math.log(n) + 0.5 / n - 1. / (12 * n ** 2) + 1. ...
337
29.727273
83
py
RADio
RADio-main/dart/external/rbo.py
"""Rank-biased overlap, a ragged sorted list similarity measure. See http://doi.acm.org/10.1145/1852102.1852106 for details. All functions directly corresponding to concepts from the paper are named so that they can be clearly cross-identified. The definition of overlap has been modified to account for ...
10,648
36.628975
87
py
RADio
RADio-main/dart/metrics/activation.py
import numpy as np from sklearn.preprocessing import KBinsDiscretizer from dart.external.kl_divergence import compute_kl_divergence from dart.external.discount import harmonic_number import warnings class Activation: """ Class that calculates the average Affect score based on absolute sentiment polarity value...
2,550
44.553571
105
py
RADio
RADio-main/dart/metrics/start_calculations.py
import dart.metrics.activation import dart.metrics.calibration import dart.metrics.fragmentation import dart.metrics.representation import dart.metrics.alternative_voices import dart.metrics.visualize import dart.Util import pandas as pd import numpy as np import time from random import sample from datetime import dat...
10,941
54.826531
122
py
RADio
RADio-main/dart/metrics/calibration.py
from dart.external.discount import harmonic_number from dart.external.kl_divergence import compute_kl_divergence from sklearn.preprocessing import KBinsDiscretizer import warnings import numpy as np import dart.handler.other.textstat class Calibration: """ Class that calibrates recommender Calibration. Th...
4,623
46.183673
141
py
RADio
RADio-main/dart/metrics/fragmentation.py
import numpy as np from dart.external.discount import harmonic_number from dart.external.kl_divergence import compute_kl_divergence class Fragmentation: """ Class that calculates to what extent users have seen the same news stories. A "story" is considered a set of articles that are about the same 'event'...
2,475
38.301587
119
py
RADio
RADio-main/dart/metrics/alternative_voices.py
from collections import Counter from dart.external.discount import harmonic_number from dart.external.kl_divergence import compute_kl_divergence import numpy as np class AlternativeVoices: """ Class that calculates the number of mentions of minority vs majority people. In the current implementation, what ...
7,977
48.552795
136
py
RADio
RADio-main/dart/metrics/representation.py
import numpy as np from dart.external.discount import harmonic_number from dart.external.kl_divergence import compute_kl_divergence from collections import defaultdict class Representation: """ Calculates Representation of entities linked to different political parties using KL Divergence. Currently the i...
5,481
44.683333
143
py
RADio
RADio-main/dart/metrics/visualize.py
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from pathlib import Path class Visualize: @staticmethod def print_mean(df): print(df.groupby('type')['mean'].mean()) print(df.groupby('type')['std'].mean()) @staticmethod def plot(df, title): plt.figure...
3,736
40.065934
115
py
RADio
RADio-main/dart/preprocess/identify_stories.py
from datetime import datetime, timedelta import pandas as pd import networkx as nx import community.community_louvain as community_louvain from collections import defaultdict from statistics import mode, StatisticsError from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cos...
8,819
43.1
188
py
RADio
RADio-main/dart/preprocess/nlp.py
import datetime # if that doesn't work, do pip install -U numpy # https://discuss.pytorch.org/t/valueerror-and-importerror-occurred-when-import-torch/5818 import nl_core_news_sm import pandas as pd import en_core_web_sm from textblob import TextBlob import textstat import json import os import dart.Util config = da...
2,500
28.081395
90
py
RADio
RADio-main/dart/preprocess/enrich_articles.py
import pandas as pd import dart.handler.NLP.enrich_entities import dart.handler.NLP.cluster_entities import dart.handler.other.wikidata import dart.Util class Enricher: def __init__(self, config): self.config = config self.metrics = config['metrics'] self.language = config['language'] ...
1,704
32.431373
113
py
RADio
RADio-main/dart/preprocess/downloads.py
import requests from recommenders.models.newsrec.newsrec_utils import get_mind_data_set from recommenders.models.deeprec.deeprec_utils import download_deeprec_resources import os import pandas as pd import numpy as np from urllib import request, error from bs4 import BeautifulSoup import datetime import time def dow...
3,605
32.082569
161
py
RADio
RADio-main/dart/preprocess/recommendations.py
import pandas as pd import pickle import os from pathlib import Path import json import datetime import random import csv import dart.Util import dart.preprocess.downloads ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.dirname(ROOT_DIR) config = dart.Util.read_config_file() mind_type = c...
2,743
35.586667
116
py
RADio
RADio-main/dart/handler/other/wikidata.py
import requests import json import pandas as pd class WikidataHandler: """ Class that constructs Wikidata queries, executes them and reads responses """ def __init__(self, language, country): self.url = 'https://query.wikidata.org/sparql' if language == 'dutch': self.language_tag ...
8,733
40.590476
151
py
RADio
RADio-main/dart/handler/other/textstat.py
import textstat class TextStatHandler: def __init__(self, language): switcher = { "dutch": textstat.set_lang("nl"), "english": textstat.set_lang("en"), "german": textstat.set_lang("de") } switcher.get(language, "Invalid language") @staticmethod ...
494
21.5
50
py
RADio
RADio-main/dart/handler/NLP/cluster_entities.py
import networkx as nx import community.community_louvain as community_louvain import pandas as pd import itertools from difflib import SequenceMatcher from collections import defaultdict class Clustering: def __init__(self, threshold, a, b, metric): self.threshold = threshold self.a = a s...
4,401
39.018182
125
py
RADio
RADio-main/dart/handler/NLP/enrich_entities.py
import dart.Util import dart.handler.other.wikidata import string import pandas as pd from collections import defaultdict import os class EntityEnricher: def __init__(self, metrics, config): self.metrics = metrics self.language = config['language'] self.country = config['country'] ...
6,789
41.974684
118
py
RADio
RADio-main/dart/handler/NLP/cosine_similarity.py
import math import itertools import numpy as np import collections, functools, operator from stop_words import get_stop_words from statistics import StatisticsError from sklearn.feature_extraction.text import TfidfVectorizer # basically copied from https://www.datasciencecentral.com/profiles/blogs/ # document-simila...
3,950
38.118812
122
py
RADio
RADio-main/dart/handler/NLP/sentiment.py
from textblob import TextBlob from textblob_nl import PatternTagger as PatternTagger_nl, PatternAnalyzer as PatternAnalyzer_nl class Sentiment: """ Class that calculates the average Affect score based on absolute sentiment polarity values. This approach is an initial approximation of the concept, and shou...
1,143
37.133333
111
py
RADio
RADio-main/viz/pickleToCSV.py
import pandas as pd import numpy as np import pickle from pathlib import Path import os ## JS d = pd.read_pickle("../../data/output.pickle") columns = list(d.columns)[2:9] for i, column in enumerate(columns): _, d[column], _ = d[column].str # root JS d.iloc[:,2:8] = d.iloc[:,2:8].apply(np.sqrt) # d.iloc[:...
1,837
22.265823
72
py
RADio
RADio-main/viz/mind.py
from recommenders.datasets import mind from recommenders.datasets.download_utils import unzip_file # hypers item_sim_measure = "item_feature_vector" #"item_cooccurrence_count" p = "../../data/" trainName = "MINDlarge_train.zip" devName = "MINDlarge_dev.zip" mind.download_mind(size="large", dest_path=p) # mind.extr...
819
26.333333
101
py
RADio
RADio-main/script/popularity-MIND.py
# Databricks notebook source import datetime import time import numpy as np import pyspark.sql.functions as F from pyspark.sql.types import * from pyspark.sql import Row from pyspark.sql.window import Window import math from pyspark.ml.recommendation import ALS from pyspark.sql import SparkSession spark = SparkSessio...
10,267
40.403226
154
py
the-gan-zoo
the-gan-zoo-master/update.py
# -*- coding: utf-8 -*- """ Update Readme.md and cumulative_gans.jpg """ from __future__ import print_function from __future__ import division import numpy as np import matplotlib.pyplot as plt from bs4 import BeautifulSoup import requests import csv def load_data(): """ Load GANs data from the gans.csv file """...
2,569
31.531646
78
py
ygm
ygm-master/.cmake-format.py
# ----------------------------- # Options effecting formatting. # # Requires cmake-format (pip install cmake_format). See # https://cmake-format.readthedocs.io/en/latest/configuration.html for more # examples. # ----------------------------- with section("format"): # How wide to allow formatted cmake files lin...
1,288
32.051282
81
py
bond
bond-main/coverage/search_OA_CR.py
import time import re import unicodedata import requests import Levenshtein """ Cleaning title and identifying author name """ def cleaning_title(title, typ): if typ == "oa": n = 6 else: n = 4 stoplist = [line.strip() for line in open("stopwords-it.txt")] stoplist = set(stoplist) ...
7,030
33.131068
116
py
bond
bond-main/coverage/coverage.py
import logging import os import json import csv from search_OA_CR import * def calculate_coverage(logger, cand_dict): cov = dict() cov["total_CV"] = len(cand_dict["pubbs"]) cov["mag"] = 0 cov["oa"] = 0 cov["cr"] = 0 cov["combined"] = 0 for pub in cand_dict["pubbs"]: if "PId" in pu...
5,413
38.808824
116
py
bond
bond-main/data_collection/id_search.py
import time import os import re import json import unicodedata import requests import Levenshtein """ Cleaning title and identifying author name """ def cleaning_title(title, typ): if typ == "oa": n = 6 else: n = 4 stoplist = [line.strip() for line in open("stopwords-it.txt")] stoplist...
13,167
38.190476
116
py
bond
bond-main/data_collection/cit_retrieval.py
import time import os import json import re import unicodedata import requests """Retrieving Cited MAG""" def search_cited(loggr, idt): hdr_mag = {'Ocp-Apim-Subscription-Key': 'ac0d6ea6f26845e8b41c0df9f4e45120'} query = f"expr=Id={idt}&attributes=Id,DOI,AA.AuN,AA.AuId,Ti,Y,J.JN" url_mag = f"https://api.l...
12,080
34.221574
116
py
bond
bond-main/data_collection/add_info.py
import csv def adding_cov(metrics_dd): print("adding coverage section") for asn_year, terms in metrics_dd["cand"].items(): for term, roles in terms.items(): for role, fields in roles.items(): for field, candidates in fields.items(): for cand_id, info i...
3,983
45.325581
139
py
bond
bond-main/data_collection/bib_retrieval.py
"""Retrieving Articles from Author Identifiers: AuthorIDs > Article IDs""" import time import os import json import requests def matching_pubbs(list_pubbs, new): value = 0 n = len(list_pubbs) idx = 0 while idx < n: if "PId" in list_pubbs[idx].keys(): if new["PId"] == list_pubbs[id...
8,320
42.11399
119
py
bond
bond-main/data_collection/bond_execution.py
import logging from meta_extraction import * from add_info import * from id_search import * from bib_retrieval import * from cit_retrieval import * from graph_analysis import * def BoND(cand_jsons_path, comm_csv_path, outcomes_path, final_path): logging.basicConfig(filename='data_collection.log', level=logging.E...
3,576
48.680556
116
py
bond
bond-main/data_collection/meta_extraction.py
import os import json import csv import re import unicodedata def cleaning_doi(doi_raw): doi_clean = doi_raw.strip("DOI: ").strip("HTTPS://DX.DOI.ORG/").strip("#").replace(" ", "") return doi_clean def cleaning_title(title_raw): title_clean = u"".join([c for c in unicodedata.normalize("NFKD", title_ra...
8,266
45.184358
131
py
bond
bond-main/data_collection/graph_analysis.py
""" Create graph, measure features and collect results """ import os import json import networkx as nx import numpy as np ''' Create graph''' def create_graph_pid(graph, list_pubbs, group, author, key, end_date): for pub in list_pubbs: if pub[key] < end_date: if "PId" in pub.keys() or "doi" ...
8,581
34.609959
121
py
bond
bond-main/visualization/visualization.py
import os import json import numpy as np import networkx as nx import matplotlib.pyplot as plt from xml.dom import minidom from wand.api import library import wand.color import wand.image def create_graph_pid(graph, list_pubbs, group, author): for pub in list_pubbs: if "PId" in pub.keys() or "doi" in pub....
8,404
46.485876
114
py
bond
bond-main/ml_experiment/script/plotDecisionTree.py
import time import sys import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import svm, tree from sklearn.model_selection import cross_validate from sklearn.metrics import * from sklearn.utils import resample from itertools import combinations inputFile = "../../complete_metrics.csv"...
3,415
32.821782
101
py
bond
bond-main/ml_experiment/script/ml_combinations.py
import time import sys import pandas as pd import numpy as np from sklearn import svm, tree from sklearn.model_selection import cross_validate from sklearn.metrics import * from sklearn.utils import resample from itertools import combinations import ray sections = ["AP", "FP"] fields = ["10-G1", "13-D4"] coverages ...
6,548
34.4
163
py
acoustic-images-distillation
acoustic-images-distillation-master/setup.py
from setuptools import setup setup( name='codebase', version='0.0.1', packages=['codebase'], install_requires=['librosa', 'numpy', 'tensorflow-gpu==1.4.0', 'torchfile'], url='https://gitlab.iit.it/aperez/acoustic-images-distillation', license='', author='Andres Perez', author_email='and...
423
29.285714
81
py
acoustic-images-distillation
acoustic-images-distillation-master/main_s2.py
import tensorflow as tf from datetime import datetime from codebase.loggers import Logger from codebase.models.audition import HearModel from codebase.models.audition import SoundNet5Model from codebase.models.audition import DualCamHybridModel from codebase.trainers import TwoStreamsTrainer from codebase.data import ...
5,898
48.158333
110
py
acoustic-images-distillation
acoustic-images-distillation-master/main_s1.py
import tensorflow as tf from datetime import datetime from codebase.loggers import Logger from codebase.models.vision import ResNet50Model from codebase.models.vision import ResNet50TemporalModel from codebase.models.audition import HearModel from codebase.models.audition import DualCamModel from codebase.models.audit...
6,668
49.522727
120
py
acoustic-images-distillation
acoustic-images-distillation-master/utils/convert_data.py
import argparse import cv2 import glob import numpy as np import os import re import tensorflow as tf from collections import namedtuple from datetime import datetime from scipy import io as spio from utils import str2dir Image = namedtuple('Image', 'rows cols depth data') Audio = namedtuple('Audio', 'mics samples da...
8,417
45
173
py
acoustic-images-distillation
acoustic-images-distillation-master/utils/compute_stats.py
from __future__ import division from datetime import datetime import argparse import tensorflow as tf import numpy as np import os import sys from codebase.data import ActionsDataLoader as DataLoader parser = argparse.ArgumentParser() parser.add_argument('root_dir', help='Directory holding generated lists and comput...
4,791
40.310345
111
py
acoustic-images-distillation
acoustic-images-distillation-master/utils/__init__.py
import argparse import os import tensorflow as tf def str2dir(dir_name): if not os.path.isdir(dir_name): raise argparse.ArgumentTypeError('{} is not a directory!'.format(dir_name)) elif os.access(dir_name, os.W_OK) is False: raise argparse.ArgumentTypeError('{} is not a writeable directory!'.f...
859
34.833333
116
py
acoustic-images-distillation
acoustic-images-distillation-master/utils/generate_lists.py
import argparse import glob import numpy as np import os import re from utils import str2dir TRAIN_SET_SIZE = 0.8 VALID_SET_SIZE = 0.1 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('root_dir', help='Dataset root directory', type=str2dir) parser.add_argument('--location...
3,928
39.927083
143
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/__init__.py
0
0
0
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/dualcamnet.py
import tensorflow as tf import tensorflow.contrib.slim as slim def dualcamnet_v2(inputs, keep_prob=0.5, is_training=True, num_classes=None, num_frames=12, num_channels=12, spatial_squeeze=False, scope='DualCamN...
2,579
48.615385
110
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/multimodal.py
from collections import OrderedDict from tensorflow.contrib.slim.nets import resnet_v1 import dualcamnet import shared import tensorflow as tf import tensorflow.contrib.slim as slim class AVModel(object): def __init__(self, num_classes=None): self.scope = 'AVNet' self.num_classes = num_classes...
5,061
40.491803
114
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/resnet_temporal.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from codebase.models import resnet_utils resnet_arg_scope = resnet_utils.resnet_arg_scope slim = tf.contrib.slim @slim.add_arg_scope def bottleneck_normal(inputs, ...
6,387
40.212903
91
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/soundnet.py
import tensorflow as tf import tensorflow.contrib.slim as slim import torchfile def soundnet_arg_scope(is_training=True, weight_decay=0.0001): """Defines the SoundNet arg scope. Args: is_training: Boolean flag indicating whether we are in training or not. weight_decay: The ...
15,910
51.167213
113
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/shared.py
import tensorflow as tf import tensorflow.contrib.slim as slim def shared_net(inputs, num_classes=None, is_training=True, keep_prob=0.5, spatial_squeeze=True, scope='shared_net'): """ Builds a three-layer fully-connected modality agnostic network. """ with tf.variable_scope(scope, [inputs]) as sc: ...
1,434
48.482759
116
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/audition.py
import dualcamnet import hearnet import shared import soundnet import tensorflow as tf import tensorflow.contrib.slim as slim from collections import OrderedDict flags = tf.app.flags FLAGS = flags.FLAGS class DualCamModel(object): def __init__(self, mode='train', input_shape=None, num_classes=14, num_frames=12...
12,249
40.385135
118
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/__init__.py
0
0
0
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/vision.py
from tensorflow.contrib.slim.nets import resnet_v1 import tensorflow as tf import tensorflow.contrib.slim as slim import resnet_temporal as resnet_v2 class ResNet50Model(object): def __init__(self, input_shape=None, num_classes=14): self.scope = 'resnet_v1_50' self.num_classes = num_classes ...
4,934
37.554688
120
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/hearnet.py
import tensorflow as tf import tensorflow.contrib.slim as slim def build_arg_scope(weight_decay=0.0005): with slim.arg_scope([slim.layers.conv2d, slim.layers.fully_connected], activation_fn=slim.nn_ops.relu, weights_regularizer=slim.regularizers.l2_regularizer(weigh...
3,364
41.594937
91
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/models/resnet_utils.py
# Copyright 2016 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 applicable ...
14,617
43.567073
166
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/loggers/logger.py
import tempfile import tensorflow as tf class Logger(object): def __init__(self, log_dir, exp_name): self.__log_dir = tempfile.mkdtemp() if log_dir is None or not tf.gfile.Exists(log_dir) else log_dir self.__log_dir = '{}/{}'.format(log_dir, exp_name) self.summary_op = None self....
1,351
34.578947
107
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/loggers/__init__.py
from logger import Logger
25
25
25
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/data/actions_data.py
from __future__ import division from tensorflow.contrib.slim.nets import vgg from preprocessing import vgg_preprocessing import librosa import tensorflow as tf import numpy as np import math flags = tf.app.flags FLAGS = flags.FLAGS # The real number of tracks is 128 corresponding to the number of microphones but eve...
17,906
46.248021
134
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/data/__init__.py
from actions_data import ActionsDataLoader
43
21
42
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/trainers/one_stream.py
from datetime import datetime from utils import build_accuracy import tempfile import tensorflow as tf import tensorflow.contrib.slim as slim flags = tf.app.flags FLAGS = flags.FLAGS class OneStreamTrainer(object): def __init__(self, model, logger=None, display_freq=1, learning_rate=0.0001, nu...
15,796
44.656069
131
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/trainers/two_streams.py
from datetime import datetime from utils import build_accuracy import tensorflow as tf flags = tf.app.flags slim = tf.contrib.slim FLAGS = flags.FLAGS class TwoStreamsTrainer(object): def __init__(self, teacher_model, student_model, logger=None, lambda_value=0.5, temperature_value=1.0, ...
15,751
46.161677
135
py
acoustic-images-distillation
acoustic-images-distillation-master/codebase/trainers/__init__.py
from one_stream import OneStreamTrainer from two_streams import TwoStreamsTrainer
82
26.666667
41
py
synorim-merged
synorim-merged/jittor/evaluate.py
import jittor import bdb, traceback, pdb import importlib import argparse from pathlib import Path from utils import exp from tqdm import tqdm def test_epoch(): net_model.eval() net_model.hparams.is_training = False pbar = tqdm(test_loader, desc='Test') meter = exp.AverageMeter() for batch_idx, d...
1,235
25.297872
77
py
synorim-merged
synorim-merged/jittor/dataset.py
import json import jittor from pathlib import Path import numpy as np class DatasetSpec: PC = 200 FULL_FLOW = 300 FULL_MASK = 400 class FlowDataset(jittor.dataset.Dataset): def __init__(self, batch_size, shuffle, num_workers, base_folder: str, spec: list, sub_frames: list, split: st...
2,470
35.338235
89
py
synorim-merged
synorim-merged/jittor/train.py
import argparse import bdb import importlib import pdb import shutil import traceback from pathlib import Path from omegaconf import OmegaConf from tqdm import tqdm import jittor from utils import exp jittor.flags.use_cuda = True def train_epoch(): global global_step net_model.train() net_model.hparam...
2,990
28.91
94
py
synorim-merged
synorim-merged/jittor/metric.py
import jittor class PairwiseFlowMetric: def __init__(self, batch_mean: bool = False, compute_epe3d: bool = True, compute_acc3d_outlier: bool = False): self.batch_mean = batch_mean self.compute_epe3d = compute_epe3d self.compute_acc3d_outlier = compute_acc3d_outlier def evaluate(self, ...
2,182
40.980769
114
py
synorim-merged
synorim-merged/jittor/models/base_model.py
import functools import importlib from pathlib import Path import jittor from jittor import nn from jittor.optim import LambdaLR from utils.exp import AverageMeter, parse_config_yaml def lambda_lr_wrapper(it, lr_config, batch_size): return max( lr_config['decay_mult'] ** (int(it * batch_size / lr_config...
1,680
34.020833
109
py
synorim-merged
synorim-merged/jittor/models/desc_net.py
import jittor from dataset import DatasetSpec as DS, FlowDataset # Following won't work in jittor. # from backbones.pointconv import PointConv as Backbone from backbones.pointnet2 import PN2BackboneLarge as Backbone from models.base_model import BaseModel import numpy as np from utils.misc import cdist class Model(...
2,844
37.972603
91
py
synorim-merged
synorim-merged/jittor/models/full_sync.py
from collections import defaultdict import jittor from dataset import DatasetSpec as DS, FlowDataset from metric import PairwiseFlowMetric from models.base_model import BaseModel import numpy as np class Model(BaseModel): """ This model runs the full test of our model, taking multiple point clouds as input...
7,787
43.25
113
py
synorim-merged
synorim-merged/jittor/models/basis_net.py
import jittor import random from dataset import DatasetSpec as DS, FlowDataset from backbones.pointnet2 import PN2BackboneLarge as Backbone from backbones.pointnet2 import PN2BackboneSmall as BackboneSmall from models.base_model import BaseModel import numpy as np from utils.misc import cdist, cdist_single from colle...
11,005
42.848606
114
py
synorim-merged
synorim-merged/jittor/utils/exp.py
import pickle from collections import OrderedDict import sys from pathlib import Path from omegaconf import OmegaConf def parse_config_yaml(yaml_path: Path, args: OmegaConf = None, override: bool = True) -> OmegaConf: """ Load yaml file, and optionally merge it with existing ones. This supports a light-w...
4,390
33.03876
110
py
synorim-merged
synorim-merged/jittor/utils/misc.py
import jittor def cdist(src, dst): """ Calculate Euclid distance between each two points. src^T * dst = xn * xm + yn * ym + zn * zm; sum(src^2, dim=-1) = xn*xn + yn*yn + zn*zn; sum(dst^2, dim=-1) = xm*xm + ym*ym + zm*zm; dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2 = sum(src**2,dim=...
1,000
29.333333
60
py
synorim-merged
synorim-merged/jittor/backbones/pointnet2.py
""" The code here is from https://github.com/Jittor/PointCloudLib.git """ from typing import List, Optional, Tuple import math import numpy as np import jittor as jt from jittor import nn from jittor.contrib import concat jt.flags.use_cuda = 1 def index_points(points, idx): """ Input: points: inpu...
34,807
33.947791
156
py
synorim-merged
synorim-merged/jittor/backbones/pointconv.py
""" The code here is from https://github.com/Jittor/PointCloudLib.git """ import numpy as np import jittor as jt from jittor import nn from jittor.contrib import concat def topk(input, k, dim=None, largest=True, sorted=True): if dim is None: dim = -1 if dim < 0: dim += input.ndim transpo...
16,355
34.25
120
py
synorim-merged
synorim-merged/pytorch/evaluate.py
import torch import bdb, traceback, pdb import importlib import argparse from pathlib import Path from utils import exp import numpy as np from tqdm import tqdm from dataset.base import DatasetSpec def visualize(test_result, data): try: import open3d as o3d except ImportError: print("Please im...
4,097
37.299065
120
py
synorim-merged
synorim-merged/pytorch/train.py
import argparse import bdb import importlib import pdb import shutil import traceback from pathlib import Path import torch from omegaconf import OmegaConf from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from utils import exp def train_epoch(): global global_step net_model.train() ...
3,917
31.114754
112
py
synorim-merged
synorim-merged/pytorch/metric.py
import torch class PairwiseFlowMetric: def __init__(self, batch_mean: bool = False, compute_epe3d: bool = True, compute_acc3d_outlier: bool = False, scene_level: bool = False): """ :param batch_mean: Whether to return an array with size (B, ) or a single scalar (mean) :par...
3,005
45.246154
113
py
synorim-merged
synorim-merged/pytorch/dataset/base.py
import collections import multiprocessing import torch from numpy.random import RandomState from torch.utils.data import Dataset import zlib, json from enum import Enum class DatasetSpec(Enum): FILENAME = 100 PC = 200 # Flow and masks are dictionary with key (view_i, view_j). FULL_FLOW = 300 FULL...
3,050
32.527473
109
py
synorim-merged
synorim-merged/pytorch/dataset/flow_dataset.py
import json from pathlib import Path import numpy as np from dataset.base import RandomSafeDataset, DatasetSpec import MinkowskiEngine as ME from pyquaternion.quaternion import Quaternion class DataAugmentor: """ Will apply data augmentation to pairwise point clouds, by applying random transformations ...
8,649
41.610837
114
py
synorim-merged
synorim-merged/pytorch/models/base_model.py
import functools import importlib import tempfile from pathlib import Path from typing import Mapping, Any, Optional, Callable, Union import numpy as np import torch from torch import nn from omegaconf import OmegaConf from torch.optim.lr_scheduler import LambdaLR from utils.exp import AverageMeter, parse_config_yaml ...
3,644
37.776596
109
py
synorim-merged
synorim-merged/pytorch/models/basis_net_self.py
from collections import defaultdict import torch from torch.utils.data import DataLoader from dataset.base import DatasetSpec as DS, list_collate from dataset.flow_dataset import FlowDataset from models.basis_net import Model as BaseModel from models.desc_net_self import Model as DescModel class Model(BaseModel): ...
3,726
50.763889
108
py
synorim-merged
synorim-merged/pytorch/models/desc_net.py
import torch import MinkowskiEngine as ME from torch.nn import Parameter from torch.utils.data import DataLoader from dataset.base import DatasetSpec as DS, list_collate from dataset.flow_dataset import FlowDataset, DataAugmentor from metric import PairwiseFlowMetric from models.spconv import ResUNet from models.base...
6,939
51.180451
113
py
synorim-merged
synorim-merged/pytorch/models/full_sync.py
from collections import defaultdict import torch.linalg from torch.utils.data import DataLoader from dataset.base import DatasetSpec as DS, list_collate from dataset.flow_dataset import FlowDataset from metric import PairwiseFlowMetric from models.base_model import BaseModel import numpy as np from utils.point impor...
10,385
41.740741
119
py