repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
DjalelBBZ/ramp-board | ramp-database/ramp_database/utils.py | <reponame>DjalelBBZ/ramp-board<filename>ramp-database/ramp_database/utils.py
"""
The :mod:`ramp_database.utils` module provides tools to setup and connect to the
RAMP database.
"""
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/model/score.py | from sqlalchemy import Float
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import Integer
from sqlalchemy import Boolean
from ramp_utils.utils import encode_string
from .base import Model
__all__ = ['ScoreType']
# XXX: Should probably be addressed at some point?
# Deprecated: score ty... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/model/__init__.py | """
The :mod:`ramp_database.model` defines the database structure which is used for the
RAMP events.
"""
from .base import * # noqa
from .user import * # noqa
from .fold import * # noqa
from .team import * # noqa
from .score import * # noqa
from .event import * # noqa
from .problem import * # noqa
from .workflo... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/tests/test_utils.py | <filename>ramp-database/ramp_database/tests/test_utils.py
import shutil
import pytest
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from ramp_database.testing import create_test_db
from ramp_database.model import Model
... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/model/tests/test_fold.py | import datetime
import shutil
import pytest
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from ramp_database.model import CVFold
from ramp_database.model import Model
from ramp_database.model import SubmissionOnCVFold
f... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_string_encoding.py | import sys
from ramp_utils import encode_string
PYTHON3 = sys.version_info[0] == 3
def test_encode_string():
if PYTHON3:
string = encode_string('a string')
assert isinstance(string, bytes)
string = encode_string(b'a string')
assert isinstance(string, bytes)
else:
stri... |
DjalelBBZ/ramp-board | ramp-engine/ramp_engine/tests/test_cli.py | import shutil
from click.testing import CliRunner
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from ramp_database.model import Model
from ramp_database.utils import setup_db
from ramp_database.testing import create_toy_... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/deploy.py | import os
import shutil
from ramp_database.testing import setup_files_extension_type
from ramp_database.testing import setup_ramp_kits_ramp_data
from ramp_database.tools.event import add_event
from ramp_database.tools.event import add_problem
from ramp_database.tools.event import get_problem
from ramp_database.utils i... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/frontend.py | import six
from .config_parser import read_config
def generate_flask_config(config):
"""Generate the configuration to deal with Flask.
Parameters
----------
config : dict or str
Either the loaded configuration or the configuration YAML file.
Returns
-------
flask_config : dict
... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_utils.py | <reponame>DjalelBBZ/ramp-board
import os
import six
from ramp_utils.utils import check_password
from ramp_utils.utils import encode_string
from ramp_utils.utils import hash_password
from ramp_utils.utils import import_module_from_source
def test_import_module_from_source():
module_path = os.path.dirname(__file_... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/utils.py | <gh_stars>0
import importlib
import sys
import bcrypt
import six
def import_module_from_source(source, name):
"""Load a module from a Python source file.
Parameters
----------
source : str
Path to the Python source file which will be loaded as a module.
name : str
Name to give to... |
DjalelBBZ/ramp-board | ramp-frontend/ramp_frontend/__init__.py | <filename>ramp-frontend/ramp_frontend/__init__.py
import os
from flask import Flask
from flask_login import LoginManager
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from ramp_database.model import Model
from ._version import __version__
all = [
'__version__'
]
HERE = os.path.dirname(__f... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/string_encoding.py | # TODO: remove this file once we are moving to Python 3 only
import sys
PYTHON3 = sys.version_info[0] == 3
def encode_string(text):
"""Encode text into an array of bytes in both Python 2 and 3 with UTF-8.
Parameters
----------
text : str or bytes
The text to be encoded
Returns
-----... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/__init__.py | <filename>ramp-database/ramp_database/__init__.py
from ._version import __version__
all = [
'__version__'
] |
DjalelBBZ/ramp-board | ramp-database/ramp_database/model/tests/test_submission.py | import os
import re
import shutil
import numpy as np
from numpy.testing import assert_allclose
import pytest
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from rampwf.prediction_types.base import BasePrediction
from ram... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/__init__.py | from .config_parser import read_config
from .frontend import generate_flask_config
from .ramp import generate_ramp_config
from .string_encoding import encode_string
from .utils import import_module_from_source
from .worker import generate_worker_config
from ._version import __version__
__all__ = [
'generate_flask... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/cli.py | <filename>ramp-utils/ramp_utils/cli.py
import click
from ramp_utils import deploy
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
def main():
pass
@main.command()
@click.option("--config", default='config.yml', show_default=True,
help='... |
DjalelBBZ/ramp-board | ramp-engine/ramp_engine/__init__.py | <filename>ramp-engine/ramp_engine/__init__.py
from .dispatcher import Dispatcher
from .local import CondaEnvWorker
from ._version import __version__
available_workers = {'conda': CondaEnvWorker}
__all__ = [
'CondaEnvWorker',
'Dispatcher',
'available_workers',
'__version__'
]
|
DjalelBBZ/ramp-board | ramp-database/ramp_database/tools/database.py | import logging
from ..model import Extension
from ..model import SubmissionFileType
from ..model import SubmissionFileTypeExtension
from ._query import select_extension_by_name
from ._query import select_submission_file_type_by_name
from ._query import select_submission_type_extension_by_name
logger = logging.getLog... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/model/team.py | <reponame>DjalelBBZ/ramp-board
import datetime
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import Integer
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from ramp_utils.utils import encode_str... |
DjalelBBZ/ramp-board | ramp-frontend/ramp_frontend/security.py | <filename>ramp-frontend/ramp_frontend/security.py
from itsdangerous import URLSafeTimedSerializer
from ramp_frontend import app
ts = URLSafeTimedSerializer(app.config["SECRET_KEY"])
|
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/worker.py | import os
import six
from .config_parser import read_config
def generate_worker_config(config):
"""Generate the configuration for RAMP worker from a configuration
file.
Parameters
----------
config : dict or str
Either the loaded configuration or the configuration YAML file.
Return... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/tests/test_testing.py | <filename>ramp-database/ramp_database/tests/test_testing.py
import os
import shutil
import pytest
from git.exc import GitCommandError
from ramp_utils import read_config
from ramp_utils import generate_ramp_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_templ... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_cli.py | import shutil
from click.testing import CliRunner
from ramp_database.utils import setup_db
from ramp_database.model import Model
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from ramp_utils.cli import main
def teardo... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_frontend.py | import pytest
from ramp_utils.testing import database_config_template
from ramp_utils import read_config
from ramp_utils import generate_flask_config
@pytest.mark.parametrize(
"config",
[database_config_template(),
read_config(database_config_template())]
)
def test_generate_flask_config(config):
f... |
DjalelBBZ/ramp-board | ramp-frontend/ramp_frontend/cli.py | <reponame>DjalelBBZ/ramp-board
import click
from ramp_utils import generate_flask_config
from ramp_utils import read_config
from . import create_app
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
def main():
pass
@main.command()
@click.option("--co... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/tools/event.py | import logging
import os
from sqlalchemy.orm.exc import NoResultFound
from ramp_utils.utils import import_module_from_source
from ._query import select_event_admin_by_instance
from ._query import select_event_by_name
from ._query import select_extension_by_name
from ._query import select_problem_by_name
from ._query... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_password.py | <filename>ramp-utils/ramp_utils/tests/test_password.py
from ramp_utils.password import hash_password
from ramp_utils.password import check_password
def test_check_password():
password = "<PASSWORD>"
hashed_password = hash_password(password)
assert check_password(password, hashed_password)
assert not c... |
DjalelBBZ/ramp-board | ramp-engine/ramp_engine/local.py | <gh_stars>0
import json
import logging
import os
import shutil
import subprocess
from .base import BaseWorker
logger = logging.getLogger('RAMP-WORKER')
class CondaEnvWorker(BaseWorker):
"""Local worker which uses conda environment to dispatch submission.
Parameters
----------
config : dict
... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/password.py | <filename>ramp-utils/ramp_utils/password.py
import bcrypt
from .string_encoding import encode_string
def hash_password(password):
"""Hash a password.
Parameters
----------
password : str or bytes
Human readable password.
Returns
-------
hashed_password : bytes
The hashed... |
DjalelBBZ/ramp-board | ramp-frontend/ramp_frontend/testing.py | <reponame>DjalelBBZ/ramp-board<filename>ramp-frontend/ramp_frontend/testing.py<gh_stars>0
"""The :mod:`ramp_frontend.testing` module contains all functions used to easily
test the frontend."""
from contextlib import contextmanager
def login(client, username, password):
"""Simulate a log-in from a user.
Afte... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/testing.py | """
The :mod:`ramp_database.testing` module create facility functions to test the
tools and model of ``ramp-database``.
"""
import logging
import os
import shutil
import subprocess
from git import Repo
from ramp_utils import generate_ramp_config
from .utils import setup_db
from .utils import session_scope
from .mo... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/ramp.py | import os
import six
from .config_parser import read_config
def generate_ramp_config(config):
"""Generate the configuration to deploy RAMP.
Parameters
----------
config : dict or str
Either the loaded configuration or the configuration YAML file.
Returns
-------
ramp_config : d... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_worker.py | import os
import pytest
from ramp_utils.testing import ramp_config_template
from ramp_utils import read_config
from ramp_utils import generate_worker_config
@pytest.mark.parametrize(
"config", [ramp_config_template(), read_config(ramp_config_template())]
)
def test_generate_worker_config(config):
worker_co... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/exceptions.py | """
The :mod:`ramp_database.exceptions` module include all custom warnings and errors
used in ``ramp-database``.
"""
__all__ = [
'DuplicateSubmissionError',
'MergeTeamError',
'MissingExtensionError',
'MissingSubmissionFileError',
'NameClashError',
'TooEarlySubmissionError',
'UnknownStateErr... |
DjalelBBZ/ramp-board | ramp-engine/ramp_engine/aws/ramp_aws_train.py | <filename>ramp-engine/ramp_engine/aws/ramp_aws_train.py
from __future__ import print_function, absolute_import, unicode_literals
import sys
import logging
import argparse
from argparse import RawTextHelpFormatter
from ramp_engine.aws.api import launch_ec2_instance_and_train
from ramp_engine.aws.api import train_on_ex... |
sbhattach/SNMP-TRAP-Receiver | trap_inform.py | """
SNMP TRAP and Infor Reciver for SNMP V1,V2c,V3
"""
import argparse
try:
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp, udp6
from pysnmp.entity.rfc3413 import ntfrcv
from pysnmp.proto.api import v2c
from pysnmp.smi import builder, view, compiler, rfc1902... |
nagomiso/knnFeat | sklearn_api.py | <filename>sklearn_api.py
# coding: utf-8
from functools import partial
from itertools import product
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
from sklearn.model_selection import StratifiedKFold
from sklearn.utils import check_X_y
class KNeighborsFeatures(... |
nagomiso/knnFeat | knn_feat.py | import numpy as np
from sklearn.model_selection import KFold
def _distance(a, b):
return np.linalg.norm(b - a)
def _get_feat(data, X_train, y_train, class_index, k_index):
inclass_X = X_train[y_train == class_index]
distances = np.array([_distance(a, data) for a in inclass_X])
sorted_distances_index ... |
nagomiso/knnFeat | test/test_knnFeat.py | import unittest
import numpy as np
import sys, os
sys.path.append(os.getcwd())
from knnFeat import knnExtract
class TestKnnFeat(unittest.TestCase):
def test_knnFeat(self):
X = np.reshape(np.array([0, 1, 3, 4, 5, 6, 1, 1, 0, 3]), (5, 2))
y = np.array([0, 0, 0, 1, 1])
expected = knnExtract(... |
nagomiso/knnFeat | test/test_distance.py | import unittest
import numpy as np
import sys, os
sys.path.append(os.getcwd())
from knnFeat import _distance
class TestDistance(unittest.TestCase):
def test_distance(self):
a = np.array([0, 0])
b = np.array([3, 4])
expected = _distance(a, b)
actual = 5
self.assertEqual(expe... |
nagomiso/knnFeat | test/test_get_feat.py | <reponame>nagomiso/knnFeat
import unittest
import numpy as np
import sys, os
sys.path.append(os.getcwd())
from knnFeat import _get_feat
class TestGetFeat(unittest.TestCase):
# Case 1: class_index == 0 and k_index == 0
def test_get_feat_c0k0(self):
data = np.array([0, 0])
X_train = np.reshape(n... |
ryphon/rke2 | contrib/custom-image-kubelet/genconfig.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
import logging
import os
import re
import stat
import sys
import tarfile
from base64 import b64decode
from collections import defaultdict
from os.path import basename, normpath
from shutil import copyfileobj
import boto3
import click
import requests
from yaml i... |
jmay0504/nitime | nitime/tests/test_lazy.py | <gh_stars>1-10
import sys
import os
import numpy.testing as npt
import numpy.testing.decorators as dec
import pytest
import nitime.lazyimports as l
# The next test requires nitime.lazyimports.disable_lazy_imports to have been
# set to false, otherwise the lazy import machinery is disabled and all imports
# happen at... |
jmay0504/nitime | nitime/algorithms/spectral.py | <filename>nitime/algorithms/spectral.py
"""
Spectral transforms are used in order to estimate the frequency-domain
representation of time-series. Several methods can be used and this module
contains implementations of several algorithms for the calculation of spectral
transforms.
"""
import numpy as np
from nitime.l... |
jmay0504/nitime | nitime/analysis/coherence.py | import warnings
import numpy as np
from nitime.lazy import scipy_stats_distributions as dist
from nitime.lazy import scipy_fftpack as fftpack
from nitime import descriptors as desc
from nitime import utils as tsu
from nitime import algorithms as tsa
# To support older versions of numpy that don't have tril_indices:
... |
hamzaleroi/dnn_migration | screw_detection/data_join.py | #!/usr/bin/env python
import h5py
import cv2
import numpy as np
import os
from glob import glob
import matplotlib.pyplot as plt
from tqdm.notebook import tqdm
import shutil
import argparse
def create_dir(_path):
if not os.path.exists(_path):
os.mkdir(_path)
def merge_dir(_dir):
class_names=os.listdir(... |
hamzaleroi/dnn_migration | screw_detection/infer.py | #!/usr/bin/env python
import numpy as np
import argparse
import matplotlib.pyplot as plt
import cv2
import os
from glob import glob
import tensorflow as tf
import warnings
import os
from tqdm import tqdm
def create_model(iden,NB_CLASS,NB_CHANNEL,WEIGHT_PATH):
if iden=='densenet201':
base_model_wrapper=tf.kera... |
hamzaleroi/dnn_migration | screw_classification/data.py | <filename>screw_classification/data.py
#!/usr/bin/env python
# coding: utf-8
from tqdm import tqdm_notebook
import shutil
import tensorflow as tf
from tqdm.notebook import tqdm
from albumentations import Resize
import albumentations as albu
from albumentations import (Blur, Compose, HorizontalFlip, HueSaturationValue,
... |
hamzaleroi/dnn_migration | screw_classification/infer.py | <reponame>hamzaleroi/dnn_migration
#!/usr/bin/env python
import tensorflow as tf
import os
import argparse
import warnings
import efficientnet.tfkeras as efn
from glob import glob
import numpy as np
from tqdm.notebook import tqdm
import cv2
class COLORS:
red = (0,0,255)
blue = (255,0,0)
green = (0,255,0... |
hamzaleroi/dnn_migration | screw_detection/train.py |
from tqdm.notebook import tqdm
from glob import glob
import os
import argparse
import tensorflow as tf
import numpy as np
from scripts.resnet import ResNeXt101
def data_input_fn(mode,BUFFER_SIZE,BATCH_SIZE,IMG_DIM,data_img_dim=64,DATA_PATH='ScrewDTF'):
def _parser(example):
feature ={ 'image' ... |
hamzaleroi/dnn_migration | screw_classification/data_store.py | #!/usr/bin/env python
import h5py
import cv2
import numpy as np
import os
from glob import glob
import matplotlib.pyplot as plt
from tqdm.notebook import tqdm
import argparse
def create_dir(_path):
if not os.path.exists(_path):
os.mkdir(_path)
def saveh5(path,data):
hf = h5py.File(path,'w')
hf.... |
hamzaleroi/dnn_migration | screw_classification/train.py | #!/usr/bin/env python
import numpy as np
import os
import argparse
from glob import glob
import pandas as pd
import seaborn as sn
from tqdm.notebook import tqdm
from sklearn.metrics import confusion_matrix, roc_curve, precision_recall_curve, classification_report
import efficientnet.tfkeras as efn
import matplotlib.pyp... |
hamzaleroi/dnn_migration | screw_classification/eval.py | <reponame>hamzaleroi/dnn_migration
#!/usr/bin/env python
# coding: utf-8
import efficientnet.tfkeras as efn
import warnings
import tensorflow as tf
import json
from tqdm.notebook import tqdm
import cv2
import numpy as np
import os
import argparse
class COLORS:
red = (0, 0, 255)
blue = (255, 0, 0)
green = (... |
hamzaleroi/dnn_migration | screw_detection/eval.py | <filename>screw_detection/eval.py
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
import os
import h5py
import tensorflow as tf
from tqdm.notebook import tqdm
from scripts.resnet import ResNeXt101
import warnings
from glob import glob
import cv2
import imageio
import ar... |
hamzaleroi/dnn_migration | screw_classification/data_join.py | #!/usr/bin/env python
import h5py
import cv2
import argparse
import numpy as np
import os
from glob import glob
import matplotlib.pyplot as plt
from tqdm.notebook import tqdm
import shutil
def create_dir(_path):
if not os.path.exists(_path):
os.mkdir(_path)
def merge_dir(_dir):
global count
... |
hamzaleroi/dnn_migration | screw_detection/data.py | <reponame>hamzaleroi/dnn_migration
import os
import h5py
import argparse
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import cv2
import numpy as np
import cv2
from PIL import Image as imgop
import random
from sklearn.utils import shuffle
from tqdm import tqdm_notebook
from glob import glo... |
Jetoky/discord_bot | bot_test.py | from _pytest.mark.structures import MARK_GEN
import Mafia_and_BR
import pytest
import unittest.mock
import os
@pytest.mark.asyncio
async def test_join_b():
ctx = unittest.mock.Mock()
ctx.author.id = 3
ctx.send = unittest.mock.AsyncMock()
Mafia_and_BR.users_bunker.clear()
await Mafia_and_BR.join_bun... |
Jetoky/discord_bot | file_creator.py | <reponame>Jetoky/discord_bot
from pathlib import Path
path = f"{Path.cwd()}"
def create():
""" Функция возвращает данные для создания файла, в котором хранится вся необходимая информация для игры "Бункер"
В данной функции создается и изменяется файл BabyFile.txt
"""
import random
s = ("инжене... |
paarthneekhara/cleverhans | examples/adversarial_asr/create_defense_data.py | from os import listdir
from os.path import isfile, join
import sys
import argparse
import random
def _get_file_names(audio_dir):
file_names = []
for f in listdir(audio_dir):
if f.endswith(".wav"):
file_names.append(f)
return file_names
def main():
parser = argparse.ArgumentParser(description=No... |
paarthneekhara/cleverhans | examples/adversarial_asr/transcribe_lingvo.py | import tensorflow as tf
from lingvo import model_imports
from lingvo import model_registry
import numpy as np
import scipy.io.wavfile as wav
import generate_masking_threshold as generate_mask
from tool import create_features, create_inputs
import time
from lingvo.core import cluster_factory
from absl import app
import ... |
paarthneekhara/cleverhans | examples/adversarial_asr/lingvo/core/base_layer.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 applica... |
paarthneekhara/cleverhans | examples/adversarial_asr/lingvo/core/ops/py_x_ops.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 applica... |
drmidnightytb/Consulta-DNS | main.py | import time
import socket
from requests import get
import smtplib
import socket
import os
print('')
restart = 'S'
while restart == 'S':
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
print('#####################')
time.sleep(0.5)
print('Consulta de IP por DNS')
t... |
june-08042/sciwing | sciwing/modules/embedders/trainable_word_embedder.py | <filename>sciwing/modules/embedders/trainable_word_embedder.py
from sciwing.modules.embedders.base_embedders import BaseEmbedder
from sciwing.data.datasets_manager import DatasetsManager
from sciwing.vocab.embedding_loader import EmbeddingLoader
import torch
import torch.nn as nn
from typing import List
from sciwing.da... |
june-08042/sciwing | sciwing/datasets/__init__.py | <reponame>june-08042/sciwing
from sciwing.datasets.classification.text_classification_dataset import (
TextClassificationDataset,
)
from sciwing.datasets.classification.text_classification_dataset import (
TextClassificationDatasetManager,
)
from sciwing.datasets.seq_labeling.conll_dataset import CoNLLDatasetMa... |
mapbox/rio-color | rio_color/__init__.py | """rio-color"""
__version__ = "1.0.4"
|
piyush2896/Image-Resizer-Python | image-resizer.py | import argparse
import sys
import cv2
import os
parser = argparse.ArgumentParser()
parser.add_argument("--src", metavar="source",
help="Source folder of the Image files")
parser.add_argument("--dest", metavar="destinantion",
help="Destination folder of the Image files (Default: ... |
Phantom4d/dtrump-pickup-bot | main.py | <filename>main.py
import StringIO
import json
import logging
import random
import urllib
import urllib2
# for sending images
from PIL import Image
import multipart
# standard app engine imports
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2
TOKEN = '<KEY>'
BASE_URL = '... |
db434/nn-restrict | structured/fully_connected.py | from collections import OrderedDict
import torch.nn as nn
from . import wrapped
import modifiers.modules as quantisable
class Conv2d(nn.Module):
"""Simple wrapper for the default convolution class. Introduced so all
convolution variants have a similar interface.
Adds batch normalisation to be fair, ... |
db434/nn-restrict | tests/test_butterfly.py | import random
import torch
from structured.butterfly import *
def _group_counts_to_group_sizes(params, group_counts):
"""Convert numbers of groups to sizes of groups."""
_, out_channels, _ = params
group_sizes = [out_channels // count for count in group_counts]
return group_sizes
def _sequence_test... |
db434/nn-restrict | tests/test_butterfly_old2.py | <filename>tests/test_butterfly_old2.py
import random
from structured.butterfly_old2 import *
# Each test case is a tuple of (inputs, outputs, butterfly sequence).
# The butterfly sequence is itself a list of tuples, with each element holding
# (inputs, outputs, butterfly size).
_test_cases = [
(8, 8, [(8, 8, 8), ... |
db434/nn-restrict | locations.py | """
Details about the local filesystem.
This should be the only file that needs to be changed when using a new machine.
"""
# Directory for each dataset.
mnist = "./mnist"
cifar10 = "./cifar10"
imagenet = "./imagenet"
# Directory containing accurate networks for each dataset, to be used for
# knowledge distillation.... |
db434/nn-restrict | structured/__init__.py | <reponame>db434/nn-restrict<filename>structured/__init__.py
from . import butterfly_old2
from . import butterfly_old
from . import butterfly
from . import deep_roots
from . import depthwise_butterfly
from . import depthwise_separable
from . import depthwise_shuffle
from . import fully_connected
from . import hadamard
f... |
db434/nn-restrict | datasets/WikiText2.py | <gh_stars>0
import torch
import torchtext
import torchtext.data as data
import locations
# TODO subclass an abstract Dataset class.
# Perhaps also a TextDataset class.
class WikiText2(object):
# Some sensible defaults.
name = "WikiText-2"
default_model = "wlm_lstm_medium"
location = None
# Thes... |
db434/nn-restrict | datasets/__init__.py | from .MNIST import *
from .Cifar10 import *
from .ImageNet import *
from .WikiText2 import *
|
db434/nn-restrict | util/checkpoint.py | <gh_stars>0
import csv
import numpy
import os
import shutil
import time
import torch
from modifiers.modules import Quantisable
from util import log
"""Data written to a log file at the end of each epoch."""
log_data = ["Time", "Epoch", "Train loss", "Train top1",
"Train top5", "Val loss", "Val top1", "Val... |
db434/nn-restrict | models/lenet.py | <reponame>db434/nn-restrict<gh_stars>0
import torch.nn as nn
import structured.fully_connected as fc
models = {"MNIST": ["lenet5", "mnistnet"]}
class LeNet5(nn.Module):
"""
This doesn't quite match the original, but isn't far off:
* Batch norm layers are included in convolution layers.
* The seco... |
db434/nn-restrict | datasets/MNIST.py | import torch.utils.data as data
import torchvision.datasets
import torchvision.transforms as transforms
import locations
# TODO subclass an abstract Dataset class
class MNIST(object):
_normalize = transforms.Normalize((0.1307,), (0.3081,))
# Some sensible defaults.
name = "MNIST"
default_model = "l... |
db434/nn-restrict | common.py | import os
import sys
import torch
import torch.backends.cudnn as cudnn
import models
import modifiers
import structured
import training
import util
def process(dataset):
"""
Wrap the main task with some exception handlers. Otherwise a huge,
unnecessary, parallel stacktrace is printed.
:param datase... |
db434/nn-restrict | tests/test_shift.py | <reponame>db434/nn-restrict
import random
from structured.shift import *
def _functional_test():
"""Ensure that data is being shifted properly."""
# TODO
None
def _shift_test():
"""Test creating and running Shift modules with a variety of configurations.
"""
for i in range(100):
ker... |
db434/nn-restrict | structured/depthwise_butterfly.py | import torch.nn as nn
from . import butterfly
from . import wrapped
from util import log
# Same interface as torch.nn.Conv2d (except groups -> depth_multiplier).
class Conv2d(nn.Module):
"""A drop-in replacement for torch.nn.Conv2d which uses a depthwise-
separable structure. This means that a small number of... |
db434/nn-restrict | modifiers/modules.py | <gh_stars>0
import torch
import torch.nn as nn
from . import functional
class Quantisable(nn.Module):
"""
Module which quantises its weights.
A full-precision copy of weights is retained to allow gradients to
accumulate over multiple small steps.
"""
def __init__(self, module):
super... |
db434/nn-restrict | training/__init__.py | from . import distillation
from . import lr_schedule
from . import trainer
|
db434/nn-restrict | structured/hadamard.py | <reponame>db434/nn-restrict<gh_stars>0
import torch
import torch.nn as nn
from . import wrapped
from util import log
def _power_of_two(value):
"""Returns whether the given value is a power of two."""
return (value & (value - 1)) == 0
class HadamardLayer(nn.Module):
"""Split each butterfly in two, in1 a... |
db434/nn-restrict | datasets/Cifar10.py | <gh_stars>0
import torch.utils.data as data
import torchvision.datasets
import torchvision.transforms as transforms
import locations
# TODO subclass an abstract Dataset class.
class Cifar10(object):
_normalize = transforms.Normalize(mean=[0.4914, 0.4822, 0.4465],
std=[0.202... |
db434/nn-restrict | structured/convert_to_conv.py | <reponame>db434/nn-restrict<filename>structured/convert_to_conv.py
"""
Wrappers to convert a range of different layer types to convolutions. This
allows the structured convolution to be applied to a wider range of networks.
"""
import math
import torch
import torch.nn as nn
from . import fully_connected as fc
import ... |
db434/nn-restrict | structured/shuffle.py | import torch.nn as nn
from . import wrapped
from util import log
# A simplification of the module used in:
#
# ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
# Devices
# https://arxiv.org/abs/1707.01083
#
# This implementation simply performs a grouped convolution, then permutes the
# ch... |
db434/nn-restrict | structured/deep_roots.py | <gh_stars>0
import torch.nn as nn
from . import wrapped
from util import log
# As introduced in:
#
# Deep Roots: Improving CNN Efficiency with Hierarchical Filter Groups
# https://arxiv.org/abs/1605.06489
class Conv2d(nn.Module):
"""A drop-in replacement for torch.nn.Conv2d which uses the Deep Roots
structu... |
db434/nn-restrict | structured/butterfly_old2.py | import torch
import torch.nn as nn
import torch.nn.functional
from . import wrapped
from util import log
def _next_power_of_two(value):
"""Return the first power of 2 greater than or equal to the input."""
power = 1
while power < value:
power *= 2
return power
def _power_of_two(value):
... |
db434/nn-restrict | training/trainer.py | <gh_stars>0
import time
import torch
from structured import convert_to_conv as c2c
from util import log
class Trainer(object):
"""Class which takes a model and trains it."""
def __init__(self, dataset, model, schedule, args, optimiser=None,
criterion=None):
self.dataset = dataset
... |
db434/nn-restrict | structured/butterfly.py | <filename>structured/butterfly.py
from functools import reduce
import math
import torch.nn as nn
from . import wrapped
from util import log
class Conv2dSublayer(nn.Module):
"""Class representing a single sublayer of the butterfly network.
This module performs a single grouped convolution and then reorders t... |
db434/nn-restrict | util/stats.py | <gh_stars>0
from collections import OrderedDict
import os
import torch
from . import checkpoint, log
import models
def data_distribution_hooks(model, activations=True, weights=True,
gradients=True):
"""Register hooks to print activations, weights and gradients. Input is
the root m... |
db434/nn-restrict | modifiers/functional.py | <reponame>db434/nn-restrict
"""
Wrapper for torch.nn.functional which provides allows weights to be modified
before they are used.
"""
import torch
class QuantiseFunction(torch.autograd.Function):
"""
Function with both a forward and a backward pass. I use a
straight-through estimator here: the gradients... |
db434/nn-restrict | structured/wrapped.py | <filename>structured/wrapped.py
from functools import reduce
import torch.nn as nn
class Conv2d(nn.Conv2d):
"""Simple wrapper for the default convolution class.
Adds a couple of extra methods to extract useful statistics. This module
should not be visible outside of this package.
"""
def __... |
db434/nn-restrict | models/wlm.py | # Word language model. Based on
# https://github.com/pytorch/examples/blob/master/word_language_model/model.py
import torch.nn as nn
import modifiers.modules as quantisable
import structured.convert_to_conv as c2c
import util.log
# These models should work for any text dataset.
models = {"WikiText-2": ["wlm_lstm_lar... |
db434/nn-restrict | tests/test_depthwise_separable.py | import random
import torch
from structured.depthwise_separable import *
def _separable_test():
"""Test an entire depthwise-separable module.
For a range of different input and output sizes, ensure that the layer
doesn't crash when running.
"""
for i in range(100):
inputs = random.randint... |
db434/nn-restrict | models/aaronnet.py | import torch.nn as nn
import structured.fully_connected as fc
models = {"CIFAR-10": ["aaronnet", "aaronnet_v2"]}
class AaronNet(nn.Module):
def __init__(self, input_channels=3, num_classes=10, conv2d=fc.Conv2d,
args=None):
super(AaronNet, self).__init__()
self.classes = num_clas... |
db434/nn-restrict | models/__init__.py | from functools import reduce
import torch
from modifiers.modules import Quantisable
from structured import convert_to_conv
from util import log
from . import lenet, aaronnet, alexnet, densenet, mobilenet, resnet, \
squeezenet, vgg, wlm
submodules = [lenet, aaronnet, alexnet, densenet, mobilenet, resnet,
... |
db434/nn-restrict | structured/butterfly_old.py | import torch
import torch.nn as nn
from . import wrapped
from util import log
"""This version of the butterfly module is the "true" way of performing the
computation, with O(nlogn) weights and computations. However, it relies on a
large number of grouped convolutions, which are no faster than ordinary
convolutions. T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.