python_code stringlengths 0 83.2k |
|---|
"""
Very simple script that simply iterates over all files data/pdf/f.pdf
and create a file data/txt/f.pdf.txt that contains the raw text, extracted
using the "pdftotext" command. If a pdf cannot be converted, this
script will not produce the output file.
"""
# make sure pdftotext is installed
if not shutil.which('p... |
render_template, abort, g, flash, _app_ctx_stack
# various globals
# -----------------------------------------------------------------------------
# database configuration
if os.path.isfile('secret_key.txt'):
SECRET_KEY = open('secret_key.txt', 'r').read()
else:
SECRET_KEY = 'devkey, should be in a file'
a... |
"""
Queries arxiv API and downloads papers (the query is a parameter).
The script is intended to enrich an existing database pickle (by default db.p),
so this file will be loaded first, and then new results will be added to it.
"""
def encode_feedparser_dict(d):
"""
helper function to get rid of feedparser bs w... |
"""
Use imagemagick to convert all pfds to a sequence of thumbnail images
requires: sudo apt-get install imagemagick
"""
# make sure imagemagick is installed
if not shutil.which('convert'): # shutil.which needs Python 3.3+
print("ERROR: you don\'t have imagemagick installed. Install it first before calling this sc... |
# global settings
# -----------------------------------------------------------------------------
class Config(object):
# main paper information repo file
db_path = 'db.p'
# intermediate processing folders
pdf_dir = os.path.join('data', 'pdf')
txt_dir = os.path.join('data', 'txt')
thumbs_dir =... |
sleep_time = 60*10 # in seconds
max_days_keep = 5 # max number of days to keep a tweet in memory
def get_db_pids():
print('loading the paper database', Config.db_path)
db = pickle.load(open(Config.db_path, 'rb'))
# I know this looks weird, but I don't trust dict_keys to be efficient with "in" operator.
# I... |
timeout_secs = 10 # after this many seconds we give up on a paper
if not os.path.exists(Config.pdf_dir): os.makedirs(Config.pdf_dir)
have = set(os.listdir(Config.pdf_dir)) # get list of all pdfs we already have
numok = 0
numtot = 0
db = pickle.load(open(Config.db_path, 'rb'))
for pid,j in db.items():
pdfs = [x[... |
"""
Reads txt files of all papers and computes tfidf vectors for all papers.
Dumps results to file tfidf.p
"""
seed(1337)
max_train = 10000 # max number of tfidf training documents (chosen randomly), for memory efficiency
# read database
db = pickle.load(open(Config.db_path, 'rb'))
# read all text files for all pa... |
# Version: 0.19
"""The Versioneer - like a rocketeer, but for versions.
The Versioneer
==============
* like a rocketeer, but for versions!
* https://github.com/python-versioneer/python-versioneer
* Brian Warner
* License: Public Domain
* Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3
* [![Latest Version][pypi... |
logger.remove()
logger.add(
sys.stderr, format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | {level} | {message}"
)
TFP_URL = "https://maayanlab.cloud/Enrichr/geneSetLibrary?mode=text&libraryName=TF_Perturbations_Followed_by_Expression"
TRRUST_URL = "https://www.grnpedia.org/trrust/data/trrust_rawdata.human.tsv"
... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
# This motif file is not created by default
# * f"{self.data_dir}/reference.factor.feather"
class PeakPredictor:
def __init__(
self,
reference=None,
atac_bams=None,
histone_bams=None,
regions=None,
genome="hg38",
pfmfile=None,
factors=None,
... |
# Remove default logger
logger.remove()
# Add logger
logger.add(sys.stderr, format="{time} | {level} | {message}", level="INFO")
# This is here to prevent very high memory usage on numpy import.
# On a machine with many cores, just importing numpy can result in up to
# 8GB of (virtual) memory. This wreaks havoc on ma... |
#!/usr/bin/env python
# Copyright (c) 2009-2019 Quan Xu <qxuchn@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
"""Predict TF influence score"""
# Python imports
warnings.filterwarni... |
class Distributions:
def __init__(self):
# dist_functions = [f for f in dir(ananse.distributions) if f.endswith("_dist")]
dist_functions = [
scale_dist,
log_scale_dist,
scipy_dist,
peak_rank_dist,
peak_rank_file_dist,
]
... |
def check_path(arg, error_missing=True):
"""Expand all paths. Can check for existence."""
if arg is None:
return arg
args = [arg] if isinstance(arg, str) else arg
paths = [cleanpath(arg) for arg in args]
if error_missing:
for path in paths:
if not os.path.exists(path)... |
#!/usr/bin/env python
# Copyright (c) 2009-2019 Quan Xu <qxuchn@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
"""Build gene regulatory network"""
# Python imports
warnings.filterwa... |
bed_sort,
bed_merge,
bam_index,
bam_sort,
mosdepth,
)
class CombineBedFiles:
def __init__(self, genome, peakfiles, verbose=True):
self.genome = genome
self.list_of_peakfiles = (
peakfiles if isinstance(peakfiles, list) else [peakfiles]
)
self.verbo... |
#!/usr/bin/env python
# Copyright (c) 2009-2019 Quan Xu <qxuchn@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
def influence(args):
a = ananse.influence.Influence(
ncore=a... |
#!/usr/bin/env python
# Copyright (c) 2021 Simon van Heeringen
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
def view(args):
df = view_h5(args.infile, tfs=args.factors, fmt=args.format)
in... |
#!/usr/bin/env python
# Copyright (c) 2009-2019 Quan Xu <qxuchn@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
def network(args):
ncore = args.ncore
if ncore is None:
... |
#!/usr/bin/env python
# Copyright (c) 2009-2019 Quan Xu <qxuchn@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
def binding(args):
predict_peaks(
check_path(args.outdir, erro... |
CombineBedFiles,
ScorePeaks,
ScoreMotifs,
Binding,
)
@logger.catch
def run_binding(
genome,
peakfiles,
bams,
outdir,
peak_width=200,
dist_func="peak_rank_file_dist",
pfmfile=None,
curation_filter=None,
tf_list=None,
whitelist=True,
model=None,
ncore=1,... |
def test_distributions():
d = ananse.distributions.Distributions()
func_list = d.get()
assert isinstance(func_list, list)
for func in func_list:
d.set(func)
scores = np.array([0, 1, 2])
def test_scale_dist():
s = ananse.distributions.scale_dist(scores)
assert np.array_equal(s, np... |
@pytest.fixture
def binding_fname():
return "tests/example_data/binding2.tsv"
@pytest.fixture
def network_obj():
return Network(genome="", gene_bed="ananse/db/hg38.genes.bed")
def test_unique_enhancer(network_obj, binding_fname):
regions = network_obj.unique_enhancers(binding_fname)
regions = re... |
def test_read_expression():
res = read_expression("tests/data/dge.tsv")
assert set(res.keys()) == {"ANPEP", "CD24", "COL6A3", "DAB2", "DMKN"}
assert res["ANPEP"].score - 7.44242618323665 < 0.001
assert res["ANPEP"].realfc - 7.44242618323665 < 0.001
assert res["ANPEP"].absfc - 7.44242618323665 < 0.... |
# run tests locally with:
# pytest -vv --disable-pytest-warnings
# pytest -vv --disable-pytest-warnings tests/continuous_integration/test_01*
# pytest -vv --disable-pytest-warnings -k [substring]
# TODO: apply to all code --> targets = ["ananse/", "tests/"]
targets = [
"ananse/commands/__init__.py",
"ananse/c... |
# prep
test_dir = os.path.dirname(os.path.dirname(__file__))
outdir = os.path.join(test_dir, "output")
genomepy.utils.mkdir_p(outdir)
# beds
genome = os.path.join(outdir, "genome.fa")
write_file(genome, [">chr1", "N" * 50000])
bed1 = os.path.join(outdir, "bed1.bed")
write_file(bed1, ["chr1\t0\t1000\n", "chr1\t20... |
# prep
test_dir = os.path.dirname(os.path.dirname(__file__))
outdir = os.path.join(test_dir, "output")
genomepy.utils.mkdir_p(outdir)
def write_file(filename, lines):
with open(filename, "w") as f:
for line in lines:
if not line.endswith("\n"):
line = line + "\n"
... |
# source:
# https://stackoverflow.com/questions/6620471/fitting-empirical-distribution-to-theoretical-ones-with-scipy-python
mpl.rcParams["figure.figsize"] = (16.0, 12.0)
plt.style.use("ggplot")
# Create models from data
def best_fit_distribution(data, bins=200, ax=None):
"""Find the best fitting distribution ... |
# import numpy as np
def distplot(infile, score_col=4, show=False):
"""
generate simple distplot from bedfile
"""
# https://stackoverflow.com/questions/18534562/scipy-lognormal-fitting
# https://stackoverflow.com/questions/41940726/scipy-lognorm-fitting-to-histogram
# https://stackoverflow.co... |
CombineBedFiles,
ScorePeaks,
ScoreMotifs,
Binding,
)
# prep
run_gimme = False # takes ages
test_dir = os.path.dirname(os.path.dirname(__file__))
data_dir = os.path.join(test_dir, "data")
genomepy.utils.mkdir_p(data_dir)
outdir = os.path.join(test_dir, "output")
genomepy.utils.mkdir_p(outdir)
inter... |
#!/usr/bin/env python
# TODO maybe have sklearn transforms for dot prod and Lp dists
# TODO add L1 distance
# ================================================================ Distances
def dists_elemwise_sq(x, q):
diffs = x - q
return diffs * diffs
def dists_elemwise_l1(x, q):
return np.abs(x - q)
... |
#!/usr/bin/env python
# note that we import module generate py file, not the generated
# wrapper so (which is _bolt)
|
#!/usr/bin/env python
# from future import absolute_import, division, print_function
# import pathlib as pl
# _memory = Memory('.', verbose=0, compress=7) # compression between 1 and 9
# _memory = Memory('.', verbose=0, compress=3) # compression between 1 and 9
_memory = Memory('.', verbose=0)
_dir = os.path.di... |
#!/bin/env python
def main():
UNDEFINED = 7
M = 40000
# M = 500
# M = 2
# K = 16
# C = 64
try_Cs = np.array([2, 4, 8, 16, 32, 64, 128])
try_Us = np.array([2, 4, 8, 16, 32, 64, 128])
biases = np.zeros((try_Cs.size, try_Us.size)) + UNDEFINED
# sses = np.zeros((try_Cs.size, tr... |
#!/bin/env/python
def ls(dir='.'):
return os.listdir(dir)
def is_hidden(path):
return os.path.basename(path).startswith('.')
def is_visible(path):
return not is_hidden(path)
def join_paths(dir, contents):
return [os.path.join(dir, f) for f in contents]
def files_matching(dir, prefix=None, suf... |
# CAMERA_READY_FONT = 'Calibri'
CAMERA_READY_FONT = 'DejaVu Sans'
SAVE_DIR = os.path.expanduser('~/Desktop/bolt/figs/')
ensure_dir_exists(SAVE_DIR)
def save_fig(name):
plt.savefig(os.path.join(SAVE_DIR, name + '.pdf'), bbox_inches='tight')
def save_fig_png(name):
plt.savefig(os.path.join(SAVE_DIR, name ... |
#!/bin/env/python
# ================================================================ eigenvecs
# @numba.jit(nopython=True) # don't jit since take like 2.5s
# def top_principal_component(X, niters=50, return_eigenval=False,
def top_principal_component(X, niters=100, return_eigenval=False,
... |
# first 3 functions taken from:
# http://www.johnvinyard.com/blog/?p=268
# from .arrays import normalizeMat
def norm_shape(shape):
'''
Normalize numpy array shapes so they're always expressed as a tuple,
even for one-dimensional shapes.
Parameters
shape - an int, or a tuple of ints
Re... |
#!#!/bin/env/python
_memory = Memory('.', verbose=0)
def _to_np(A):
return A.cpu().detach().numpy()
def _class_balanced_sampling(X, labels, k):
np.random.seed(123)
N, D = X.shape
# intialize centroids by sampling from each class in proportion to its
# relative frequency
uniq_lbls, count... |
#!/usr/bin/env python
# TODO this file is hideous (but necessarily so for deadline purposes...)
#
# Also, this file is tightly coupled to figs.py; it basically has a func
# for each figure func that spits out data in exactly the required form
MCQ_RESULTS_DIR = '../results/timing/'
MATMUL_RESULTS_DIR = '../results/m... |
#!/bin/env/python
_memory = Memory('.', verbose=0)
# NUM_TRIALS = 1
NUM_TRIALS = 10
# @_memory.cache
def _estimator_for_method_id(method_id, **method_hparams):
return methods.METHOD_TO_ESTIMATOR[method_id](**method_hparams)
def _hparams_for_method(method_id):
if method_id in methods.SKETCH_METHODS:
... |
#!/bin/env/python
# from sklearn.decomposition import PCA, SparsePCA
# import ffht # https://github.com/FALCONN-LIB/FFHT; python setup.py install
_memory = Memory('.', verbose=1, compress=9)
KEY_NMULTIPLIES = 'muls'
OSNAP_DEFAULT_S = 4
# OSNAP_DEFAULT_S = 2
# ====================================================... |
#!/bin/env/python
def energy(A):
if A.ndim < 2 or len(A) < 2:
return 0
diffs = A - A.mean(axis=0)
return np.sum(diffs * diffs)
def run_trial(N=100, D=3, seed=None):
if seed is not None:
np.random.seed(seed)
w0, w = np.random.randn(2, D)
X = np.random.randn(N, D)
X1 = X... |
#!/bin/env/python
# from . import files
# from . import amm_methods as ameth
# sb.set_context('poster')
# sb.set_context('talk')
# sb.set_cmap('tab10')
FIGS_SAVE_DIR = pl.Path('../figs/amm')
USE_FONT = 'DejaVu Sans'
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = [USE_FONT]
# to avoid ... |
#!/bin/env/python
METHOD_EXACT = 'Exact'
METHOD_SCALAR_QUANTIZE = 'ScalarQuantize'
METHOD_SKETCH_SQ_SAMPLE = 'SketchSqSample'
METHOD_SVD = 'SVD' # truncated SVD run on the matrix at test time
METHOD_FD_AMM = 'FD-AMM'
METHOD_COOCCUR = 'CooccurSketch'
METHOD_PCA = 'PCA' # PCA projection, with PCA basis learned at tra... |
#!/usr/bin/env python
microbench_output = \
"""
ncodebooks = 4
amm bolt N, D, M, ncodebooks: 10000, 512, 10, 4 (5x20): 7.574 (4.225e+07/s), 7.582 (4.221e+07/s), 7.584 (4.219e+07/s), 7.587 (4.218e+07/s), 7.579 (4.222e+07/s),
amm bolt N, D, M, ncodebooks: 10000, 512, 100, 4 (5x20): 7.747 (1.652e+08/s), 7.743 ... |
#!/usr/bin/env python
# import types
_memory = Memory('.', verbose=0)
# ================================================================ misc
def is_dict(x):
return isinstance(x, dict)
def is_list_or_tuple(x):
return isinstance(x, (list, tuple))
def as_list_or_tuple(x):
return x if is_list_or_tupl... |
#!/usr/bin/env python
# ================================================================ Funcs
def nbits_cost(diffs, signed=True):
"""
>>> [nbits_cost(i) for i in [0, 1, 2, 3, 4, 5, 7, 8, 9]]
[0, 2, 3, 3, 4, 4, 4, 5, 5]
>>> [nbits_cost(i) for i in [-1, -2, -3, -4, -5, -7, -8, -9]]
[1, 2, 3, 3, ... |
#!/usr/bin/env python
_memory = Memory('.', verbose=1)
pd.options.mode.chained_assignment = None # suppress stupid warning
RESULTS_DIR = os.path.join('results', 'amm')
TIMING_RESULTS_DIR = os.path.join(RESULTS_DIR, 'timing')
# we log these, but don't need them for the plots
AMM_DROP_COLS = ['__pyience_timestam... |
#!/usr/bin/env python
KEY_NLOOKUPS = 'nlookups'
class VQMatmul(amm.ApproxMatmul, abc.ABC):
def __init__(self, ncodebooks, ncentroids=None):
self.ncodebooks = ncodebooks
self.ncentroids = (self._get_ncentroids() if ncentroids is None
else ncentroids)
self.enc =... |
#!/bin/env/python
"""utility functions for running experiments"""
# from sklearn.model_selection import StratifiedKFold
try:
from joblib import Memory
memory = Memory('.', verbose=0)
cache = memory.cache
except Exception:
def cache(f):
return f
# ==========================================... |
#!/usr/bin/env python
# import datasets
_memory = Memory('.', verbose=0)
np.set_printoptions(precision=3)
SAVE_DIR = '../results'
# ================================================================ Distances
def dists_elemwise_sq(x, q):
diffs = x - q
return diffs * diffs
def dists_elemwise_l1(x, q):
... |
#!/bin/env/python
_memory = Memory('.', verbose=0)
# def bucket_id_to_new_bucket_ids(old_id):
# i = 2 * old_id
# return i, i + 1
class Bucket(object):
__slots__ = 'N D id sumX sumX2 point_ids support_add_and_remove'.split()
def __init__(self, D=None, N=0, sumX=None, sumX2=None, point_ids=None,
... |
#!/usr/bin/env python
# ================================================================ misc funcs
def dists_elemwise_sq(x, q):
diffs = x - q
return diffs * diffs
def dists_elemwise_l1(x, q):
return np.abs(x - q)
def dists_elemwise_dot(x, q):
return x * q
def extract_random_rows(X, how_many... |
#!/bin/env/python
# from . import files
sb.set_context('poster')
# sb.set_context('talk')
# sb.set_cmap('tab10')
RESULTS_DIR = pl.Path('results/amm')
FIGS_SAVE_DIR = pl.Path('../figs/amm')
if not os.path.exists(FIGS_SAVE_DIR):
FIGS_SAVE_DIR.mkdir(parents=True)
def save_fig(name):
plt.savefig(os.path.jo... |
#!/usr/bin/env python
_memory = Memory('.', verbose=0)
# ================================================================ PQ
@_memory.cache
def learn_pq(X, ncentroids, nsubvects, subvect_len, max_kmeans_iters=16):
codebooks = np.empty((ncentroids, nsubvects, subvect_len))
assignments = np.empty((X.shape[0... |
#!/bin/env/python
def ls(dir='.'):
return os.listdir(dir)
def is_hidden(path):
return os.path.basename(path).startswith('.')
def is_visible(path):
return not is_hidden(path)
def join_paths(dir, contents):
return [os.path.join(dir, f) for f in contents]
def files_matching(dir, prefix=None, suf... |
#!/bin/env python
# ================================ TODO rm duplicate code from imagenet.py
# adapted from https://github.com/keras-team/keras-preprocessing/blob/master/
# keras_preprocessing/image/utils.py under MIT license
def img_to_array(img, layout='nhwc', dtype='float32', mode='RGB'):
"""Converts a PI... |
#!/bin/env python
# from python import imagenet, svhn, caltech
# from python.datasets import caltech
_memory = Memory('.', verbose=1)
# DATA_DIR = os.path.expanduser('~/Desktop/datasets/nn-search')
DATA_DIR = os.path.expanduser('data')
join = os.path.join
DEFAULT_AUG_KWARGS = {
'shear_range': 0.2,
'zoom_... |
#!/bin/env python
# import pyedflib as edf # pip install pyedflib
# import mne
ECG_DIR = paths.UCD_ECG
NUM_RECORDINGS = 25
def main():
pass
print("ecg dir: ", ECG_DIR)
fpaths = files.list_files(ECG_DIR, abs_paths=True)
# fpaths = files.list_files(ECG_DIR)
assert len(fpaths) == NUM_RECORDINGS
... |
#!/usr/env/python
DATASETS_DIR = os.path.expanduser("~/Desktop/datasets/")
def to_path(*args):
return os.path.join(DATASETS_DIR, *args)
# straightforward datasets
MSRC_12 = to_path('MSRC-12', 'origData')
UCR = to_path('ucr/UCRArchive_2018')
UCR_INFO = to_path('ucr/DataSummary.csv')
UWAVE = to_path('uWave', 'e... |
#!/bin/env python
_memory = Memory('.', verbose=1)
DATA_DIR = os.path.expanduser('~/Desktop/datasets/nn-search')
join = os.path.join
class Random:
UNIFORM = 'uniform'
GAUSS = 'gauss'
WALK = 'walk'
BLOBS = 'blobs'
class Gist:
DIR = join(DATA_DIR, 'gist')
TRAIN = join(DIR, 'gist_train.np... |
#!/usr/bin/env python
# import matplotlib as mpl
_memory = Memory('./')
def _list_csvs(directory):
return files.list_files(directory, endswith='.csv', abs_paths=True)
ELECTRIC_PATHS = _list_csvs(paths.AMPD2_POWER)
GAS_PATHS = _list_csvs(paths.AMPD2_GAS)
WATER_PATHS = _list_csvs(paths.AMPD2_WATER)
WEATHER_PAT... |
#!/bin/env python
# import warnings
_memory = Memory('.', verbose=1)
IMAGENET_ONE_OF_EACH_PATH = '../datasets/one-of-each-imagenet'
IMAGENET_ONE_OF_EACH_FLOW_PATH = '../datasets/one-of-each-imagenet-as-folders'
# IMAGENET_64_PATH = os.path.expanduser("~/Desktop/datasets/imagenet64")
# IMAGENET_TINY_PATH = os.pa... |
#!/usr/bin/env/python
_memory = Memory('.', verbose=1, compress=9)
UCR_DATASETS_DIR = paths.UCR
UCR_INFO_PATH = paths.UCR_INFO
# ================================================================
# Public
# ================================================================
def all_ucr_datasets():
for dataDir in... |
#!/bin/env python
_memory = Memory('.', verbose=1)
DATADIR = '../datasets/svhn'
TRAIN_PATH = os.path.join(DATADIR, 'train_32x32.mat')
TEST_PATH = os.path.join(DATADIR, 'test_32x32.mat')
EXTRA_PATH = os.path.join(DATADIR, 'extra_32x32.mat')
def extract_data_from_mat_file(path):
matlab_dict = io.loadmat(path)
... |
#!/bin/env/python
"""utility functions for data munging"""
def split_train_test(X, Y, train_frac=.8, random_state=123):
"""Returns X_train, X_test, y_train, y_test"""
np.random.seed(123)
return sklearn.model_selection.train_test_split(
X, Y, train_size=train_frac, random_state=random_state)
d... |
#!/bin/env python
# Load 3-lead ECG recordings from SHAREE Database:
# https://physionet.org/content/shareedb/1.0.0/
_memory = Memory('.', verbose=0)
DATA_DIR = paths.SHAREE_ECG
NUM_RECORDINGS = 139
NUM_CHANNELS = 3
RAW_DTYPE = np.uint16
# RAW_DTYPE = np.int16
SAMPLES_PER_SEC = 128
SAMPLES_PER_MIN = SAMPLES_PER... |
#!/bin/env python
# Load 3-lead ECG recordings from SHAREE Database:
# https://physionet.org/content/shareedb/1.0.0/
_memory = Memory('.', verbose=0)
DATA_DIR = paths.INCART_ECG
NUM_RECORDINGS = 75
NUM_CHANNELS = 12
RAW_DTYPE = np.int16
SAMPLES_PER_SEC = 257
SAMPLES_PER_MIN = SAMPLES_PER_SEC * 60
SAMPLES_PER_HO... |
#!/bin/env python
# from __future__ import absolute_import, division, print_function
_memory = Memory('.', verbose=1)
DATADIR_101 = paths.CALTECH_101
DATADIR_256 = paths.CALTECH_256
# _DEFAULT_CALTECH_KWARGS = dict(resample=(224, 224), crop='center', verbose=2)
_DEFAULT_CALTECH_KWARGS = dict(resample=(224, 224)... |
#!/bin/env python
_memory = Memory('.', verbose=1)
DATADIR_101 = '../datasets/caltech/101_ObjectCategories'
def main():
import matplotlib.pyplot as plt
# caltech 101
(X, y), label2cls = imgs.load_jpegs_from_dir(
# TODO
)
if isinstance(X, np.ndarray):
print("X shape: ", X... |
#!/usr/bin/env python
# ================================================================ utils
def _dists_sq(X, q):
diffs = X - q
return np.sum(diffs * diffs, axis=-1)
def _dists_l1(X, q):
diffs = np.abs(X - q)
return np.sum(diffs, axis=-1)
def _element_size_bytes(x):
return np.dtype(x.dty... |
# This file is part of Eigen, a lightweight C++ template library
# for linear algebra.
#
# Copyright (C) 2012 Keir Mierle <mierle@gmail.com>
#
# This Source Code Form is subject to the terms of the Mozilla
# Public License v. 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://m... |
# Intentionally empty
|
# -*- coding: utf-8 -*-
# This file is part of Eigen, a lightweight C++ template library
# for linear algebra.
#
# Copyright (C) 2009 Benjamin Schindler <bschindler@inf.ethz.ch>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
... |
from attention_tensorflow_mesh.attention_tensorflow_mesh import transformer_lm, transformer, attention |
# helpers
def default(val, d):
return val if val is not None else d
# simple linear layer
def linear(x, dim_out, scope = 'linear', bias = True):
with tf.variable_scope(scope):
*_, dim_in = x.shape
w_init_stdev = 1 / math.sqrt(dim_in.size)
return mtf.layers.dense(x, new_dims=[dim_ou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.