arxiv_id stringlengths 0 16 | text stringlengths 10 1.65M |
|---|---|
from Perceptron.functions.function import Function
import numpy as np
class SoftMax(Function):
"""
Class representing the softmax function
"""
def __init__(self):
"""Construct of the softmax"""
super().__init__()
self.is_diff = True
def compute(self, a):
"""
... | |
# coding: utf-8
""" Astropy coordinate class for the Ophiuchus coordinate system """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Third-party
import numpy as np
from astropy.coordinates import frame_transform_graph
from astropy.utils.data import get_pkg_data_filen... | |
import ipdb
import os
import math
import benepar
import spacy
import hashlib
import ntpath
import collections
import numpy as np
import pandas as pd
import jieba
from tqdm import tqdm
from nltk import ngrams as compute_ngrams
import _pickle as pickle
class TextAnalyzer:
def __init__(self, do_lower=True, language=... | |
import numpy as np
from numpy import random
import time
input = random.randint(100,500,size=(500,500))
vector = random.randint(100,500,size=(500,1))
output = np.zeros((500,1))
np.savetxt("input.txt",input)
np.savetxt("vector.txt",vector)
start_time = time.time()
for m in range(1):
for i in range(500):
f... | |
import random
import gym
import numpy as np
import torch
from yarll.common.evaluation import evaluate_policy
def zipsame(*seqs):
"""
Performs a zip function, but asserts that all zipped elements are of the same size
:param seqs: a list of arrays that are zipped together
:return: the zipped arguments... | |
# -*- coding: utf-8 -*-
import numpy as np
import scipy.io
import os
from sklearn.preprocessing import MinMaxScaler
import logging
logging.basicConfig(level=logging.INFO)
class Dataset:
attribute = None
train_feature = None
train_label = None
dataset_folder = None
seen_class = None
unseen... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import os
import numpy as np
from numpy import pi,cos,sin
import pandas as pd
import logging
from plotnine import *
from scipy.stats.mstats import winsorize
from plotnine.stats.stat_summary import bootstrap_statistics
#%% put PUPIL LABS data into PANDAS... | |
import viewport
from math import cos, sin, pi
import time
import numpy
from OpenGL.GL import *
import udim_vt_lib
import perf_overlay_lib
PREPASS_VERTEX_SHADER_SOURCE = """
#version 460 core
layout(location = 0) uniform mat4 modelViewProjection;
layout(location = 0) in vec3 P;
layout(location = 1) in vec2 uv... | |
try:
from pycorenlp import StanfordCoreNLP
except:
pass
from subprocess import call
import numpy as np
from get_args import *
import os
UNK = "$UNK$"
NUM = "$NUM$"
NONE = "O"
def get_iso_lang_abbreviation():
iso_lang_dict = {}
lang_iso_dict = {}
with open("iso_lang_abbr.txt") as file:
lin... | |
import pandas as pd
import numpy as np
import datetime
from pyloopkit.dose import DoseType
# from tidepool_data_science_simulator.models.simple_metabolism_model import get_iob_from_sbr, simple_metabolism_model
from tidepool_data_science_simulator.legacy.risk_metrics_ORIG import get_bgri, lbgi_risk_score, hbgi_risk_sc... | |
import os
from numpy.lib.npyio import save
from tqdm import trange
from argparse import ArgumentParser
import logging
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
from imitation_cl.train.utils import check_cuda, set_seed, get_sequence
from imitation_cl.model.hypernetwork... | |
import cv2
import math
from operator import itemgetter
import numpy as np
try:
import onnxruntime
except ImportError:
onnxruntime = None
class ORTWrapper:
def __init__(self, onnx_f) -> None:
self.onnx_f = onnx_f
so = onnxruntime.SessionOptions()
so.intra_op_num_threads = 6
... | |
import logging
import time
import sys
import networkx as nx
from multiprocessing import Pool
from fractions import Fraction
import numpy as np
import scipy.spatial as spatial
from opensfm import dataset
from opensfm import geo
from opensfm import matching
logger = logging.getLogger(__name__)
class Command:
name... | |
"""Custom utilities for interacting with the Materials Project.
Mostly for getting and manipulating structures. With all of the function definitions and docstrings,
these are more verbose """
import fnmatch
import os
from pymatgen import MPRester
from fireworks import LaunchPad
import numpy as np
import scipy
# TOD... | |
import torch
import numpy as np
# z y
# '\` /|\
# \ |
# \ |
# \ |
# \|
# x <--------------------------------
# |\
# | \
# | \
# | \
# | \
... | |
import numpy as np
import argparse, os, sys, h5py
from hfd.variables import label_df
parser = argparse.ArgumentParser(description='Add latent annotations to h5s.')
parser.add_argument('folder', type=str, help='Folder to search for h5 files.')
parser.add_argument('fontsize', type=int, help='Fontsize.')
args = parser.... | |
import os
import shutil
import subprocess
from typing import List
import cv2
import numpy as np
from PIL import Image
from skatingAI.utils.utils import BodyParts, segmentation_class_colors, body_part_classes
class DataAdmin(object):
def __init__(self, chunk_amount: int = 1):
self.chunk_amount = chunk_am... | |
from __future__ import annotations
import enum
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union, cast
if TYPE_CHECKING:
from arkouda.categorical import Categorical
import numpy as np # type: ignore
from typeguard import typechecked
from arkouda.client import generic_msg
from arkou... | |
import re
import numpy as np
from enum import Enum
from syntactical_analysis.sa_utils import State, Input, Token
__all__ = [
'Lexer',
]
class Lexer:
def __init__(self):
self.separators = ['(', ')', '[', ']', r'\{', r'\}', '.', ',', ':', ';', ' ', r'\cdot']
self.operators = ['+', '-', '=', '/'... | |
import os
import mini_topsim.parameters as par
import numpy as np
from scipy.interpolate import interp1d
def init_sputtering():
"""
initializes the get_sputter_yield module variable
Depending on the set parameters this function either attaches a callable
object that implements the yamamura function... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
import os
import pandas as pd
import numpy as np
import argparse
def main():
# Parse args
args = parse_arguments()
# Load
df = pd.read_csv(args.i, sep="\t")
# Drop NA
df = df.loc[~pd.isnull(df[args.col]), :]
# Calc sum of p... | |
import copy
import numpy as np
from pgdrive.envs import PGDriveEnvV2
from pgdrive.scene_creator.vehicle.base_vehicle import BaseVehicle
from pgdrive.scene_creator.vehicle_module.distance_detector import DetectorMask
from pgdrive.utils import panda_position
def _line_intersect(theta, center, point1, point2, maximum: ... | |
#!/usr/bin/env python
import os, random, subprocess, sys, threading
from decimal import *
import numpy as np
libs = ["atlas", "cublas", "mkl", "plasma"]
# libs = ["cublas", "plasma", "ublas"]
prefix = 1000**3
# Process manipulation
#------------------------------------------------------------------------------#
clas... | |
import torchvision, torchvision.transforms
import sys, os
sys.path.insert(0,"../torchxrayvision/")
import torchxrayvision as xrv
import matplotlib.pyplot as plt
import torch
from torch.nn import functional as F
import glob
import numpy as np
import skimage, skimage.filters
import captum, captum.attr
import torch, torc... | |
# By Nick Erickson
# Contains Save/Load Functions
import json
import os
import pickle
import numpy as np
from utils import globs as G
def save_memory_subset(agent, pointer_start, pointer_end, frame_saved, skip=8):
memory = agent.brain.brain_memory
if pointer_end < pointer_start:
pointer_end += memo... | |
from astropy import table, constants as const, units as u
import numpy as np
import os
import mpmath
# Abbbreviations:
# eqd = equivalent duration
# ks = 1000 s (obvious perhaps :), but not a common unit)
#region defaults and constants
# some constants
h, c, k_B = const.h, const.c, const.k_B
default_flarespec_path = ... | |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set(style="whitegrid", font_scale=1.5, context="talk")
"""
For details on the params below, see the matplotlib docs:
https://matplotlib.org/users/customizing.html
"""
plt.rcParams["axes.edgecolor"] = "0.6"
plt.rcParams["figure.dpi"] = 200
p... | |
# Copyright 2021 The WAX-ML Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | |
'''Scaler operation'''
import numpy as np
from .base import Operation
class Scaler(Operation):
'''Scaler Operation'''
@staticmethod
def apply(data, xmin: float, xmax: float):
'''Applies scaling in forward direction'''
return (data - xmin) / (xmax - xmin)
@staticmethod
def revers... | |
import logging as log
import pandas as pd
import numpy as np
import sklearn as sk
from pprint import pprint
def ewma(df, col, span):
log.info('Adding {0} ewma to df on {1}'.format(span, col))
ewma = pd.stats.moments.ewma(df[col], span=span)
# print df
return ewma
def rsi(df, n):
"""
RSI = 10... | |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | |
"""
Reading gif (lawnmover.gif)
"""
# Import Library
import cv2 as cv
import numpy as np
import os
# Absolute path to read
abs_path = os.path.dirname(os.path.dirname(__file__))
gif_path = os.path.join(abs_path, 'input/gif/lawnmover.gif')
# Read a gif with video capture
gif = cv.VideoCapture(gif_path)
frame_counter ... | |
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def matrix_networks_plot(M, network_colors, dpi = 300, colorbar = False, group = None, ses = None, suffix = None, out_dir = None):
"""Creates and saves matrixplot with networks color labels. """
small = 15
medium = 15
bigger ... | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable, Function
from sklearn.metrics import f1_score, average_precision_score, confusion_matrix
from sklearn.cluster.bicluster import SpectralCoclustering
import numpy as np
import csv
from loss_func import eszsl_loss_func... | |
import re
import collections
import operator
import numpy as np
import scipy.sparse as sp
from .osutils import get_linewise
# some helper functions for easy access to the libsvmformat
#
# <label> <index1>:<value1> <index2>:<value2> ... <indexn>:<valuen> # comment
#
def create_libsvmline(label, features, comment=No... | |
import configparser
import json
import numpy as np
import os
from path import Path
from cv2 import imread
from tqdm import tqdm
class test_framework_stillbox(object):
def __init__(self, root, test_files, seq_length=3, min_depth=1e-3, max_depth=80, step=1):
self.root = root
self.min_depth, self.ma... | |
# --------------
# import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Code starts here
data = pd.read_csv(path)
print(data.shape)
print(data.describe())
data.drop(columns = "Serial Number", axis = 1, inplace = True)
print(data.shape)
# code ends here
# --------------
#Import... | |
import os
import torch
import torch.utils.data
import pandas as pd
import numpy as np
class LoadDataset(torch.utils.data.Dataset):
def __init__(self, dataset_path):
"""
Args:
dataset_path (string): path to dataset file
"""
print("\nLoading datasets...")
self... | |
import logging
from collections import defaultdict
import time
import multiprocessing
import os
import argparse
import numpy as np
from flexp import flexp
from vsbd.dataset import DatasetReader
from vsbd.models import Vowpal, UniformPolicy
def parse_args():
"""
Parse input arguments of the program.
"""
... | |
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Activation, BatchNormalization, Conv2D, Concatenate, Dropout, Input
from tensorflow.keras.layers import ZeroPadding2D,Conv2DTranspose,LeakyReLU
from tensorflow.keras.layers import Conv2DTranspose, Concatenate
from tensorflow.keras.models imp... | |
import shor
def test_shor():
import numpy as np
limit = 1000
for x in range(2, limit):
factors = shor.factorize(x)
assert np.prod(factors) == x, "product({}) != {}".format(factors, x)
for f in factors:
assert shor.prime(f), "{} (factor of {}) is not prime!".format(
... | |
# Copyright (c) 2015,2016,2017,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Tests for the `skewt` module."""
import matplotlib
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
import numpy as np
import pytest
from ... | |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
#!/usr/bin/python3
import cv2
import numpy as np
import sys
import os
import pickle
import datetime
import base64
import io
from matplotlib import pyplot as plt
from PIL import Image
import extract_feature
# x = np.random.randint(25,100,25)
# y = np.random.randint(175,255,25)
# z = np.hstack((x,y))
# z = z.reshape((... | |
import numpy
import os
import sys
from setuptools import setup, find_packages, Extension
# Setup C module include directories
include_dirs = [numpy.get_include()]
# Setup C module macros
define_macros = [('NUMPY', '1')]
# Handle MSVC `wcsset` redefinition
if sys.platform == 'win32':
define_macros += [
(... | |
import polygon_primitives.helper_methods as hm
import numpy as np
from line_extraction_primitives.line import Line
import plotting
"""Definition for the edge class. Extends the Line class from line_extraction_primitives."""
class Edge(Line):
def __init__(self, point1, point2, edge_id=-1, temp_edge=False, order_poi... | |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator as mpl
import datetime
from datetime import datetime as dtime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
data1 = pd.read_csv('../preprocess_data/month9a_reshape.csv',header=0,inde... | |
# pynhanes/data.py
__doc__ = """
Loading NHANES data.
"""
#-----------------------------------------------------------------------------
# Logging
#-----------------------------------------------------------------------------
import logging
_l = logging.getLogger(__name__)
#-----------------------------------------... | |
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix, csgraph
import scipy
import igraph as ig
import leidenalg
import time
import hnswlib
import matplotlib.pyplot as plt
import matplotlib
import math
import multiprocessing
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy import s... | |
"""
Utilities for interacting with PubChem.
"""
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "3-clause BSD"
import numpy as np
import re
import time
import urllib
import urllib2
from .pug import PugQuery
class PubChem(object):
"""
Submit queries to PUG a... | |
import json
import sys
import os
from logging import getLogger
from pathlib import Path
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import click
import torch
import pandas as pd
import numpy as np
# todo: make this better
sys.path.append('./') # aa
from aa.pytorch.data_provider import ReadingImagePr... | |
import unittest
from unittest.mock import patch
from unittest import mock
import tensorflow as tf
import numpy as np
import numpy.testing as npt
from laplace.curvature import LayerMap, DiagFisher, BlockDiagFisher, KFAC
from tests.testutils.tensorflow import ModelMocker
class LayerMapTest(unittest.TestCase):
@pat... | |
"""
Module that provide a classifier template to train a model on embeddings in
order to predict the family of a given protein.
The model is built with pytorch_ligthning, a wrapper on top of
pytorch (similar to keras with tensorflow)
"""
from biodatasets import load_dataset
from deepchain.models.utils import (
dat... | |
"""
The :mod:`fatf.utils.metrics.subgroup_metrics` module holds sub-group metrics.
These functions are mainly used to compute a given performance metric for every
sub population in a data set defined by a grouping on a selected feature.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
import insp... | |
from copy import deepcopy
from pyquaternion import Quaternion
import numpy as np
def interpolate(key0, key1, t=0.5):
mesh = deepcopy(key0)
# TODO: Takes too long
print("Interpolating IICs")
for eid, fids in enumerate(mesh.edge2face):
left = fids[0]
right = fids[1]
if left is N... | |
# Creating Quantile RBF netowrk class
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.models import Model
from keras import regularizers
from tensorflow.keras import layers
from keras.models import Sequential
from keras.engine.input_layer import Input
from keras.layers.core import D... | |
# This is a first cut at using my own python script to check a student file
import numpy as np
import sys
# load the student array
y = np.load('product.npy')
ytrue = np.load('true_product.npy')
# output shape, but do not proceed if the shapes do not match
print(y.shape)
if y.shape != ytrue.shape:
sys.e... | |
"""
This script should make a big ol' data file with the angular and specular
resolved T, R_f, and R_b for a PV window in a format edible by EnergyPlus
"""
import numpy as np
from wpv import Layer,Stack
import matplotlib.pyplot as plt
# This whole thing uses microns for length
degree = np.pi/180
inc_angles = np.li... | |
#!/usr/bin/env python3.5
# coding=utf-8
'''
@date = '17/12/1'
@author = 'lynnchan'
@email = 'ccchen706@126.com'
'''
import pandas as pd
import os
import random
import numpy as np
from numpy import random as nr
class CsvReader():
def __init__(self,dic=''):
if dic is not '':
self.csv_dict=dic+... | |
# Authors: Soledad Galli <solegalli@protonmail.com>
# License: BSD 3 clause
from typing import List, Union
import numpy as np
import pandas as pd
from feature_engine.encoding.base_encoder import BaseCategoricalTransformer
from feature_engine.variable_manipulation import _check_input_parameter_variables
class WoEEn... | |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def salinity(path):
"""Water Salinity and River Discharge
The `salinit... | |
# -*- coding: utf-8 -*-
"""
Created on Thu May 9 13:46:08 2019
@author: Leheng Chen
"""
from binomialTreePricer import asianOptionBinomialTree
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
uly_names = ['Crude Oil WTI', 'Ethanol', 'Gold', 'Silver', 'Natural Gas']
uly_init = df_uly[u... | |
# -*- coding:utf-8 -*-
import cv2
import numpy as np
import tensorflow as tf
from PIL import Image
from mask.utils import load_tflite_model
from config import config_import as conf
from mask import utils
MODEL_PATH = conf.get_config_data_by_key("mask_detection")["MODEL_PATH"]
interpreter, input_details, output_deta... | |
import numpy as np
import math as m
import random
"""
the first 3 coordinates tell which joints are connected in a linear fashion.
the 4 th coordinate tells the allowed angle movement is +ve or -ve in Elbow.
5th and 6th tell in what angles it must lie if a rotation is done.
All rotations in Z axis only
"""
CONNECTED_... | |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
class CAAnimate:
@staticmethod
def animate_ca(x: np.ndarray, filepath: str, interval: int = 10):
"""
Generates a animated gif of the input x.
Parameters
----------
x: np.ndarra... | |
from collections import defaultdict
import os
from scipy import sparse
from tqdm import tqdm
import numpy as np
import pandas as pd
def load_ratings(filename):
dirpath = './data/ml-latest-small'
ratings = pd.read_csv(os.path.join(dirpath, filename))
return ratings
def get_user_movie_dictionary(datafram... | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... | |
# load_data.py
import numpy as np
import matplotlib.pyplot as plt
import torch
training_data = np.load('training_data.npy', allow_pickle=True)
print(len(training_data))
X = torch.Tensor([i[0] for i in training_data]).view(-1, 50, 50)
X = X/255.0
y = torch.Tensor([i[0] for i in training_data])
plt.imshow(X[0], cmap=... | |
"""
Created on Feb 28, 2017
@author: Siyuan Qi
Description of the file.
"""
import os
import itertools
import pickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import sklearn.metrics
import tabulate
import config
import metadata
def plot_segmentation(input_labels_list, endframe):
p... | |
from coranking import coranking_matrix
from coranking.metrics import trustworthiness, continuity, LCMC
from nose import tools as nose
import numpy as np
import numpy.testing as npt
from sklearn import manifold, datasets
def test_coranking_matrix_perfect_case():
high_data = np.eye(3)
low_data = np.eye(3)
Q... | |
import gc
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from tqdm import tqdm
from misc.point_utils import transform_point_cloud, npmat2euler
def vcrnetIter(net, src, tgt, iter=1):
transformed_src = src
bFir... | |
"""
Module to parse all the data provided for Telstra Network Disruption
competition. Additionally perform feature engineering.
"""
from __future__ import print_function
import numpy as np
import pandas as pd
def parse_single_attr(attribute=None, frame=None, use_frame=False):
"""Parse single attribute DataFrame.... | |
#!/usr/bin/env python
import sys, os, time, numpy, scipy
def somefunc1(x): # function of a scalar argument
if x < 0:
r = 0
else:
r = scipy.sin(x)
return r
def somefunc2(x): # function of a scalar argument
if x < 0:
r = 0
else:
r = math.sin(x)
return r
def some... | |
#!/bin/python
"""
A module to handle 3D data with axes.
colorview2d.Data consists of a 2d array and x and y axes.
The class provides methods to rotate, flipp, copy and save
the datafile.
Example
-------
::
file = Data(np.random.random(100, 100))
file.rotate_cw()
file.report()
file.save('newdata.dat'... | |
import brightway2 as bw
import pandas as pd
import numpy as np
import math
def is_method_uncertain(method):
"""check if method is uncertain"""
cfs = bw.Method(method).load()
cf_values = [cf_value for flow, cf_value in cfs]
return any(isinstance(x, dict) for x in cf_values)
def uncertain... | |
import shutil
from pathlib import Path
import pytest
import numpy as np
from spikeinterface.extractors import *
@pytest.mark.skip('')
def test_klustaextractors():
# no tested here, tested un run_klusta
pass
# klusta_folder = '/home/samuel/Documents/SpikeInterface/spikeinterface/spikeinterface/sorters/... | |
#!/usr/bin/env python3
import torch, random, sys, os, pickle, argparse
import numpy as np, pathos.multiprocessing as mp
import gym_util.common_util as cou
import polnet as pnet, util_bwopt as u
from collections import defaultdict
from poleval_pytorch import get_rpi_s, get_Ppi_ss, get_ppisteady_s
def main():
arg = ... | |
# coding : utf-8
"""
ResFGB for multiclass classificcation problems.
"""
from __future__ import print_function, absolute_import, division, unicode_literals
from logging import getLogger, ERROR
import time
from tqdm import tqdm
import sys
import numpy as np
import theano
from resfgb.models import LogReg, SVM, ResGrad
... | |
import numpy as np
from typing import Union, Tuple
class Rotation:
def __init__(self,input_type: str, parameters: Union[np.ndarray, Tuple[Union[str,np.ndarray], np.ndarray]]):
"""
"""
assert type(input_type) is str, 'TODO'
assert len(parameters) >= 1, 'TODO'
if inpu... | |
import io
import json
import math
import numpy
import os
import os.path
import skimage.io
import struct
import sys
import skyhook.ffmpeg as ffmpeg
def eprint(s):
sys.stderr.write(str(s) + "\n")
sys.stderr.flush()
# sometimes JSON that we input ends up containing null (=> None) entries instead of list
# this helper... | |
import models, torch, copy
import numpy as np
from server import Server
class Client(object):
def __init__(self, conf, public_key, weights, data_x, data_y):
self.conf = conf
self.public_key = public_key
self.local_model = models.LR_Model(public_key=self.public_key, w=weights, encrypted=True)
#print... | |
'''
Factory for dataloaders
Author: Filippo Aleotti
Mail: filippo.aleotti2@unibo.it
'''
import tensorflow as tf
import numpy as np
from sceneflow.training.dataloader import Loader as SYNTH_LOADER
from kitti.training.dataloader import Loader as KITTI_LOADER
from sceneflow.test.dataloader import Loader as SF_TESTING_LO... | |
# Copyright (c) Open-MMLab. All rights reserved.
import cv2
import numpy as np
def _scale_size(size, scale):
"""Rescale a size by a ratio.
Args:
size (tuple[int]): (w, h).
scale (float): Scaling factor.
Returns:
tuple[int]: scaled size.
"""
w, h = size
return int(w * ... | |
import os.path as op
import numpy as np
import nipype.pipeline.engine as pe
import nipype.interfaces.io as nio
import ephypype
from ephypype.nodes import create_iterator
from ephypype.datasets import fetch_omega_dataset
#base_path = op.join(op.dirname(ephypype.__file__), '..', 'examples')
#data_path = fetch_omega_dat... | |
import unittest
import skimage.io
import numpy as np
from detector import Detector
detector = Detector("../weight/mask_rcnn_fashion.h5", "detection")
image_input = [10,10,20,20]
class TestDetector(unittest.TestCase):
def test_detection(self):
# Test with image fashion
image = skimage.io.imread("test.jpg")
det... | |
import cv2
import numpy as np
img = cv2.imread('images/bookpage.jpg')
retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)
## different kinds of threshold
# grayscale
grayscaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# normal threshold
retval2, threshold2 = cv2.threshold(grayscaled, 12, 255, cv2.T... | |
#!/usr/bin/env python3
import csv
import numpy as np
import pandas as pd
import os
import logging
import tqdm
import math
from data_class import data_util
from info import data_info
from util import io_util
from type import OpUnit, Target, ExecutionFeature
def write_extended_data(output_path, symbol, index_value_l... | |
"""
Compute
Inception Score (IS),
Frechet Inception Discrepency (FID), ref "https://github.com/mseitzer/pytorch-fid/blob/master/fid_score.py"
Maximum Mean Discrepancy (MMD)
for a set of fake images
use numpy array
Xr: high-level features for real images; nr by d array
Yr: labels for real images
Xg: high-level features... | |
"""
This module contains code that creates n-dimensional arrays
"""
import numpy as np
mat = np.array([[1, 2], [3, 4]])
vec = np.array([1, 2])
mat.shape # (2, 2)
vec.shape # (2,)
mat.reshape(4,)
# array([1, 2, 3, 4])
mat1 = [[1, 2], [3, 4]]
mat2 = [[5, 6], [7, 8]]
mat3 = [[9, 10], [11, 12]]
arr_3d = np.array([mat1... | |
from resizeimage import resizeimage
from PIL import Image,ImageDraw
from skimage import measure
import matplotlib.pyplot as plt
import numpy as np
import cv2
import csv
import os
import sys
specs_path = "../level1specs/"
im_array = []
unique_symbols = ["=","E","=","C","C","F","P","?","C","#","-","P","P","P","#","?","=... | |
import math
import numpy as np
import pytest
from skspatial.objects import Vector, Line, Plane, Circle, Sphere
@pytest.mark.parametrize(
"point, point_line, vector_line, point_expected, dist_expected",
[
([0, 5], [0, 0], [0, 1], [0, 5], 0),
([0, 5], [0, 0], [0, 100], [0, 5], 0),
([1,... | |
import argparse
import os
from functools import lru_cache
from glob import glob
import albumentations as albu
import cv2
import numpy as np
import pandas as pd
import torch
from torch.jit import load
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
BATCH_SIZE = 32
torch.backends.cudnn.benchmark... | |
import numpy as np
import random as rn
# The below is necessary in Python 3.2.3 onwards to
# have reproducible behavior for certain hash-based operations.
# See these references for further details:
# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED
# https://github.com/fchollet/keras/issues/2280#i... | |
import os
import cv2
import numpy as np
import torch
from torch import nn
import torch.fft
"""
# --------------------------------------------
# Sobel Filter
# --------------------------------------------
# Jiahao Huang (j.huang21@imperial.uk.ac)
# 30/Jan/2022
# --------------------------------------------
"""
# Sob... | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import TruncatedSVD
## data load ##
rent = pd.read_csv("d:/data/KNN_data_rent.csv",
encoding='euc-kr')
all_data = pd.read_csv("d:/data/KK_k150_2021.csv",
... | |
import datetime
import numpy as np
import pandas as pd
from util import log, timeit
from CONSTANT import *
@timeit
def clean_df(df):
fillna(df)
@timeit
def fillna(df):
for c in [c for c in df if c.startswith(NUMERICAL_PREFIX)]:
df[c].fillna(-1, inplace=True)
for c in [c for c in df if c.startswit... | |
"""
##
Code modified by Yuhan Helena Liu, PhD Candidate, University of Washington
Modified to keep adjacency matrix, i.e. disable stochastic rewiring by Deep R, for better biological plausibility
Modified from https://github.com/IGITUGraz/LSNN-official
with the following copyright message retained from the origina... | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import random
import numpy as np
import torch
from torch import nn
from typing import Dict
def mem2str(num_bytes):
assert num_bytes >= 0
if num_bytes >= 2 ** 30: # GB
val = float(num_bytes) / (2 ** 30)
result = "%.3f GB"... | |
import unittest
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal
import dymos as dm
from dymos.utils.lgl import lgl
from dymos.models.eom import FlightPathEOM2D
import numpy as np
class TestInputParameterConnections(unittest.TestCase):
def test_dynamic_input_parameter_connec... | |
import sys
sys.path.append("./helpers/")
import json
import pyspark
import helpers
import postgres
import numpy as np
from pyspark.streaming.kafka import KafkaUtils, TopicAndPartition
####################################################################
class SparkStreamerFromKafka:
"""
class that streams me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.