text
string
# Masses of compact remnant from CO core masses __author__ = "<NAME> (<EMAIL>)" # for fit import numpy as np import scipy from scipy.optimize import curve_fit # for plot import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def linear(x, a, b): return a * x + b def f...
#!/usr/bin/env python import numpy as np from math import sin, cos, radians from functools import reduce from scipy.linalg import inv # call the class with Monocular(intrinsic, height, pitch, yaw, roll, sensor_location) class Monocular: def __init__(self, intrinsic, height, pitch, yaw, roll, sensor_location): ...
<filename>model/reader/ucf_reader.py import random import numpy as np from scipy import misc # for imread from utils.find_border import find_border import h5py import math import os from scipy.cluster.vq import kmeans,kmeans2,vq def filter_trajs_kmeans(trajs, num_centroids): num_trajs = trajs.shape[0] len_tr...
<reponame>chigur/pose<gh_stars>0 import os import re import sys import cv2 import math import time import scipy import argparse import matplotlib from torch import np import pylab as plt from joblib import Parallel, delayed import util import torch import torch as T import torch.nn as nn import torch.nn.functional as F...
<filename>fury/primitive.py """Module dedicated for basic primitive.""" from os.path import join as pjoin from distutils.version import LooseVersion import numpy as np from fury.data import DATA_DIR from fury.transform import cart2sphere from fury.utils import fix_winding_order from scipy.spatial import ConvexHull, tra...
<reponame>Chrisebell24/Copulas<filename>copulas/univariate/gaussian.py<gh_stars>0 import logging import numpy as np import pandas as pd from scipy.stats import norm from copulas.univariate.base import Univariate LOGGER = logging.getLogger(__name__) class GaussianUnivariate(Univariate): """Gaussian univariate m...
"""Main Filter class.""" import enum from dataclasses import dataclass, field from typing import Iterable, NamedTuple import numpy as np import xarray as xr from scipy import interpolate from .gpu_compat import get_array_module from .kernels import ALL_KERNELS, BaseLaplacian, GridType FilterShape = enum.Enum("Fil...
<filename>py/desispec/scatteredlight.py ''' Try to model and remove the scattered light ''' import time import numpy as np import scipy.interpolate import astropy.io.fits as pyfits from scipy.signal import fftconvolve from scipy.interpolate import interp1d from desispec.image import Image from desiutil.log import get_l...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.io import loadmat data = loadmat('ex3data1.mat') print(data) # load data X = data['X'] y = data['y'] print(X.shape,y.shape) # one-hot encoding from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse=False) y_oneh...
<filename>MHD/FEniCS/StabNS/NSprecondSetup.py import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc import numpy from dolfin import compile_extension_module, tic, toc, DirichletBC, Expression, TestFunctions, TrialFunctions, Function from scipy.sparse import coo_matrix, spdiags import time d...
<filename>credit_detection.py #coding:utf-8 # 信用卡数据异常检测 import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats import seaborn as sns from sklearn.model_selection import train_test_split LABELS=['Normal','Fraud'] # 加载数据 df=pd.read_csv('data/creditcard.csv') print(...
<reponame>pvthinker/argopy import numpy as np import pandas as pd import tools import tiles import interp import stats import computational as cpt import matplotlib.pyplot as plt import gsw from scipy import interpolate from scipy import integrate import os time_flag = 'annual' #'DJF' # 'annual' typestat = 'zmean' s...
<reponame>rjweiss/rosetta import os import unittest from StringIO import StringIO from scipy import sparse from rosetta import TokenizerBasic from rosetta.text.streamers import TextFileStreamer, TextIterStreamer from rosetta.text.streamers import MySQLStreamer, MongoStreamer from rosetta.common import DocIDError, T...
<gh_stars>1-10 from os import system import numpy as np import scipy.optimize as op import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import ListedColormap from scipy.stats import norm from scipy.stats import multivariate_normal #############################################...
<filename>sympy/physics/pring.py from __future__ import print_function, division from sympy import sqrt, exp, S, pi, I from sympy.physics.quantum.constants import hbar def wavefunction(n, x): """ Returns the wavefunction for particle on ring. n is the quantum number, x is the angle, here n can be pos...
import numpy as np import scipy.spatial.distance # listes [[x, y], [x, y], [x, y]...] def precision_recall(dets, gts, tolerance=3): dists = scipy.spatial.distance.cdist(dets, gts) idx = np.argsort(dists.flatten()) ys = (idx / gts.shape[0]).astype(int) xs = (idx % gts.shape[0]) affecte...
<reponame>bcarr092/CSignal from csignal_tests import * import re import sys import time import os import cmath import math import unittest import random import struct import string import wave dataFile = None class TestsEqualizer( unittest.TestCase ): def tearDown( self ): self.assertEquals ( csignal_de...
<gh_stars>1-10 #!/usr/bin/env python """Generate a mask that covers the tissue. """ import sys import argparse import os import numpy as np import pickle from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.morphology import binary_fill_holes from scipy.ndimage import distance_transform_edt import...
<filename>results/process_code.py import argparse import sys import re import itertools import matplotlib.pyplot as plt from collections import defaultdict import numpy as np import scipy.special import tqdm line_re = re.compile(r'([STHP])-([0-9]+)\t(.*)') def read_file(fname): with open(fname, 'r') as f: for l...
<gh_stars>0 import numpy as np import pickle as pkl import networkx as nx import scipy.sparse as sp from scipy.sparse.linalg.eigen.arpack import eigsh import sys import random def parse_index_file(filename): """Parse index file.""" index = [] for line in open(filename): index.append(int(line.strip...
<reponame>diegovalsesia/piunet<filename>Code/piunet/main.py import os import time import argparse import numpy as np import scipy.io as sio import h5py from tqdm import tqdm import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter from config import Config from losses import l1_registered_...
<gh_stars>10-100 import scipy.io import numpy as np import pickle import torch mat = scipy.io.loadmat('data_symlinks/hico_clean/anno.mat') #mat_det = scipy.io.loadmat('anno_bbox.mat') #mat_det['bbox_test'][0][1000][2][0][2][0] #0-imge name- label(2) - 0- label index(0~N) - [labelname(0~600), subj _box, obj_box] ...
import matplotlib.pyplot as plt from scipy import stats x = [5,7,8,7,2,17,2,9,4,11,12,9,6] y = [99,86,87,88,111,86,103,87,94,78,77,85,86] slope, intercept, r, p, std_err = stats.linregress(x, y) print("slope : {} , intercept : {} , std_err : {}".format(slope,intercept,std_err)) def myfunc(x): return slope * x + in...
<gh_stars>1-10 import tensorflow as tf import numpy as np import skimage.io import itertools import os import bz2 import argparse import scipy import skimage.transform import time import matplotlib.pyplot as plt plt.switch_backend('agg') gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1) CONTENT_LAYERS =...
#!/usr/bin/env python ##!/home/users/sblair/anaconda2/bin/python # -*- coding: utf-8 -*- """ Created on Wed Jul 26 14:23:52 2017 @author: stu """ import sys sys.path.insert(1,'.') import pyPartition as pp #from pymetis import part_graph #<-- requires that the PrgEnv-intel module be selected import numpy as np import...
from typing import Tuple from sympy import symbols, nsimplify, integrate from sympy.core.mul import Mul from rcdesign.is456 import ecy, ecu # from rcdesign.stressblock import StressBlock class LSMStressBlock: def __init__(self, label: str = "IS 456 LSM", ecy: float = ecy, ecu: float = ecu): self.label =...
from scipy import stats def ks_test_max_per_channel(img, mask, focus_region): """Compute a 2-sample Kolmogorov-Smirnov statistic on each channel of image returning the max value across channels. Ignore the background regions img - array of shape (x, y, z) with z being the channels. mask - bool array...
# PyVision License # # Copyright (c) 2006-2008 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list o...
<reponame>LBJ-Wade/NX01<filename>NX01_master.py #!/usr/bin/env python """ Created by stevertaylor Copyright (c) 2014 <NAME> Code contributions by <NAME> (piccard) and <NAME> (PAL/PAL2). """ from __future__ import division import os, math, optparse, time, cProfile import json, sys, glob import cPickle as pickle from...
<gh_stars>0 # 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 in writing, software ...
# # Copyright 2019 The FATE 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 appli...
import numpy as np from scipy.interpolate import UnivariateSpline def light_efficiency(electric_current, electric_voltage, radiant_power, light_type): spl_IV = UnivariateSpline(electric_current, electric_voltage) spl_IP = UnivariateSpline(electric_current, radiant_power) I = np.linspace(np.amin(electric_curren...
<reponame>markdewing/qmc_kernels<gh_stars>0 # Compare generalized eigenvalue problem from QMCPACK # Comes from using linear method. import numpy as np import scipy.linalg import h5py f = h5py.File("linear_matrices.h5","r") # Load matrices ovlp = np.array(f['overlap']) ham = np.array(f['Hamiltonian']) # Get shifts...
<filename>camera_calibration_ws/monodepth-FPN/MonoDepth-FPN-PyTorch/dataset/nyuv2_dataset.py import torch.utils.data as data import numpy as np from PIL import Image from path import Path from constants import * from torchvision.transforms import Resize, Compose, ToPILImage, ToTensor, RandomHorizontalFlip, CenterCrop, ...
<filename>modules/evaluator/FID/fid_score.py<gh_stars>0 #!/usr/bin/env python3 """Calculates the Frechet IS Distance (FID) to evalulate GANs The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while ...
from pytorch_pretrained_bert import BertTokenizer, BertConfig, BertModel from pytorch_pretrained_bert.modeling import BertPreTrainedModel, BertPreTrainingHeads import torch import pandas as pd import numpy as np from scipy.spatial.distance import cosine import time tokenizer = BertTokenizer.from_pretrained('bert-base-...
<reponame>bryan-flywire/openem __copyright__ = "Copyright (C) 2018 CVision AI." __license__ = "GPLv3" # This file is part of OpenEM, released under GPLv3. # OpenEM is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundatio...
import numpy from scipy.linalg import eigh, cholesky from scipy.stats import norm, johnsonsu from distribution import MSSKDistribution class CorrelatedNonNormalRandomVariates(object): def __init__(self,moments,correlations,num_samples, method='cholesky'): #List of 4 moments array. #NXN correl...
<gh_stars>0 import pickle import numpy as np from scipy.stats import f as F from scipy import stats from matplotlib import pyplot as plt # READ DATA ang = [0, 15, 30, 45, 60, 75] stokes_param = 'U' L = [] for a in ang: S = stokes_param + 'pol_' + str(a) + 'deg.pickle' filename = '/'.join(['data', S]) wi...
import numpy as np from scipy import ndimage as nd from .pyudwt import Denoise2D1DHardMRS b3spline = np.array([1.,4.,6.,4.,1.]) / 16. # Try to use MUCH faster median implementation # from bottleck, else fallback to numpy.median try: from bottleneck import median as the_median except ImportError: the_median =...
<gh_stars>1-10 import math from utils.MathUtils import * from utils.MathConstants import * import pandas as pd from statistics import median import numpy as np class Scheduler(): def __init__(self): self.env = None def setEnvironment(self, env): self.env = env def selection(self): ...
import sys import numpy as np from timeit import default_timer as timer from scipy.sparse import block_diag, coo_matrix from common.estimator import EstimatorModel from common.regression import max_affine_predict from optim.quadprog import qp_solve, convert_matrix_to_qp_solver_format, QP_BACKEND__DEFAULT class PCNL...
<reponame>david-zwicker/sensing-normalized-results #!/usr/bin/env python2 from __future__ import division import sys, os sys.path.append(os.path.join(os.getcwd(), '../src')) import multiprocessing as mp import itertools import numpy as np from scipy import special, optimize, stats import matplotlib.pyplot as plt im...
# -*- coding: utf-8 -*- import random from multiprocessing import Pool import numpy as np from scipy.optimize import minimize from tqdm import tqdm from . import funcs # Default settings. MAX_SEARCHES = 25 SOLVER = 'Nelder-Mead' class LPPLS: """Class for Log-Periodic Power Law Singularity Model. LPPLS is a m...
import sys import numpy as np from scipy.interpolate import interp1d from scipy.stats import norm,t #sys.path.append('/Users/jmilli/Dropbox/lib_py/image_utilities') # add path to our file #from image_tools import * # 2017-11-24 JMi: adapted the case of an odd image size # 2015-02-10 JMi: changed the definition of radi...
<filename>kaldi_io/LDA_LPLDA.py<gh_stars>10-100 # -*- coding: utf-8 -*- from __future__ import print_function import numpy as np from scipy import linalg from sklearn.utils.multiclass import unique_labels from sklearn.utils import check_array, check_X_y from sklearn.utils.validation import check_is_fitted import LDA i...
#Created by JetBrains PyCharm #Project Name: SoundAnalyzer with RaspberryPi #Author: <NAME> #University: Cergy-Pontoise #E-mail : <EMAIL> import numpy from scipy.signal import bilinear def A_weighting(fs): """Design of an A-weighting filter. b, a = A_weighting(fs) designs a digital A-weighting filter for ...
<gh_stars>0 import gym from gym import spaces from gym.utils import seeding import autograd.numpy as np from scipy.stats import beta class LQRv1(gym.Env): def __init__(self): self.dm_state = 2 self.dm_act = 1 self.dt = 0.01 self.x0 = np.array([0., 0.]) self.g = np.array...
<gh_stars>0 # -*- coding:uft-8 -*- from os import path from netCDF4 import Dataset, num2date from scipy.io import loadmat from yaml import full_load from RBR.ctd import convert2nc as conv2nc_rbr from RDI.util import gen_time from util import detect_brand def ctd_ref_data(adcp_path, time_offset, adcp_hgt): ext =...
from __future__ import absolute_import, print_function, division from nose.plugins.skip import SkipTest import numpy try: import scipy.sparse as sp import scipy.sparse except ImportError: pass # The variable enable_sparse will be used to disable the test file. import theano from theano import sparse, conf...
<filename>Selenium/QQ/utils/ocr4qqcaptcha.py import glob import numpy as np from scipy import misc from keras.layers import Input, Convolution2D, MaxPooling2D, Flatten, Activation, Dense from keras.models import Model from keras.utils.np_utils import to_categorical imgs = glob.glob('sample/*.jpg') img_size = misc.imr...
import numpy import sympy from fractions import Fraction def derive(h, height, width): rows = [] for i in range(height): row = [] for j in range(width): row.append(1 if h & (1 << (i * width + j)) else 0) rows.append(row) columns = [] for j in range(width): column = [] fo...
<reponame>rabernat/scikit-downscale import numpy as np from scipy.spatial import cKDTree from sklearn.base import RegressorMixin from sklearn.linear_model import LinearRegression from sklearn.linear_model.base import LinearModel from sklearn.utils.validation import check_is_fitted from .utils import ensure_samples_fea...
<gh_stars>0 import numpy as np import pylab from scipy.optimize import line_search def steepest_descent(grad_fun,params,num_iters, *varargs): ## Learning Rates #eta = 0.1 eta = 2 #eta = 3 ## Momentum alpha=0.7 momentum=True d = np.ones(params.shape) d = d / np.linalg.norm(d) ...
<filename>core/utils/segmentation_metrics.py import numpy as np import scipy import sklearn.metrics import skimage from skimage.segmentation.boundaries import find_boundaries from sklearn.cluster import KMeans import torch from torchvision import transforms import torch.nn.functional as F import pdb def object_id_has...
<gh_stars>1-10 import numpy as np import scipy import scipy.signal # Class used for updating plots in callbacks. class DecimatingDisplay(object): def __init__(self, data, t, dt, title_func, lines, lc, markers, histf): # assume lines and data have the same order # and first two data elements are x,...
<gh_stars>1-10 import pandas as pd import struct import numpy as np from more_itertools import run_length from bitstring import BitArray from scipy import signal def bin2df(full_path): """ Reads geneactiv .bin files into a pandas dataframe. Parameters ---------- full_path : str Full path ...
<reponame>smeschke/juggling import cv2, math import numpy as np import pandas as pd import scipy from scipy import signal # Read data and video path = 'ss5_id_321' df = pd.read_csv('/home/stephen/Desktop/'+path+'.csv') cap = cv2.VideoCapture('/home/stephen/Desktop/'+path+'.MP4') # Create video out file w,h = 480,848 v...
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib as mpl import matplotlib.font_manager as fm mpl.rcParams['font.family'] = 'CMU Serif' mpl.rcParams["mathtext.fontset"] = "stix" mpl.rcParams["font.serif"] = [mpl.rcParams['font.family']] + mpl.rcParams["font.serif"] mpl.rcParams['axes.labelsize'] = 20. m...
from typing import Optional import numpy as np # type: ignore from scipy.stats import chi2 # type: ignore from survival_evaluation.types import NumericArrayLike from survival_evaluation.utility import ( KaplanMeier, KaplanMeierArea, to_array, validate_size, ) # pylint: disable=too-many-arguments d...
''' ''' import os import sys import h5py import numpy as np from scipy.stats import chi2 np.seterr(divide='ignore', invalid='ignore') # -- abcpmc -- import abcpmc from abcpmc import mpi_util # -- galpopfm -- from . import dustfm as dustFM from . import measure_obs as measureObs dat_dir = os.environ['GALPOPFM_...
"""SOMClustering class. Copyright (c) 2019-2021 <NAME>. All rights reserved. """ import itertools from typing import List, Optional, Sequence, Tuple import numpy as np import scipy.spatial.distance as dist from joblib import Parallel, delayed, effective_n_jobs from sklearn.decomposition import PCA from sklearn.prep...
from typing import Generator, TypeVar, Generic, Tuple, List, Iterator, Union import itertools import time import random import numpy as np from scipy.special import softmax import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import seaborn as sns V = TypeVar('V') class GenCacher(Generic[V]): ...
<filename>model/metric.py """Module for computing performance metrics """ import math import numbers from pathlib import Path import numpy as np import torch import scipy.stats from sklearn.metrics import average_precision_score def t2v_metrics(sims, query_masks=None): """Compute retrieval metrics from a simili...
""" Particle Filter helper functions """ import configparser import json import math import os from collections import defaultdict from io import BytesIO from itertools import permutations from itertools import product from pathlib import Path import imageio import matplotlib.pyplot as plt import numpy as np import pa...
"""Module for remapping complex data for display.""" from inspect import getmembers, isfunction import sys import numpy as np from scipy.stats import scoreatpercentile as prctile __classification__ = "UNCLASSIFIED" __author__ = "<NAME>" def get_remap_list(): """ Create list of remap functions accessible fr...
<gh_stars>10-100 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Modules to compute the matching cost and solve the corresponding LSAP. """ import torch from scipy.optimize import linear_sum_assignment from torch import nn import numpy as np import logging class HungarianMatcher(nn.Module):...
import numpy as np import scipy as sp import scipy.linalg as spl from collections import defaultdict from sklearn.linear_model import LinearRegression # Reference Marker Configuration (in m) _THICKNESS = 0.002 _RADIUS = 0.006522 + _THICKNESS # Radius of tube _CABLE_DRIVEN_RADIUS = 0.015 def rotate_point_around_point...
<gh_stars>1-10 """ Some functions to calculate frequentist p-values (and CLs) for the "on-off" problem, that is, a counting experiment in an "on" region with background expectation, signal expectation and an uncertainty on the background expectation, constrained by a count in an "off" region. See Eur.Phys.J.C71, `arXi...
#Continuum Plotting #<NAME> #21/03/16 import numpy as np import matplotlib.pyplot as plt import scipy.interpolate as interp import pyfits as pf import glob from ipdb import set_trace as st def find_nearest(array,value,forcefloor=0): idx=(np.abs(array-value)).argmin() if forcefloor==1: if array[idx] >...
from ocetrac.track import ( _morphological_operations, _apply_mask, _label_either, _filter_area, _wrap, track, ) import pytest import xarray as xr import numpy as np import scipy.ndimage from skimage.measure import regionprops from skimage.measure import label as label_np import dask.array as ...
<reponame>dloney/proteus """Tools for working with water waves. The primary objective of this module is to provide solutions (exact and approximate) for the free surface deformation and subsurface velocity components of water waves. These can be used as boundary conditions, wave generation sources, and validation sol...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 5 12:42:47 2021 @author: mavroudo """ import pandas as pd import numpy as np from statistics import mean from autorank import autorank, create_report, plot_stats method_name = "Distance-based" methods = ['Top-ζ','LOF','Probabilistic','Distance-B...
<filename>me_biomass/load_model.py import pickle from cobrame.io.json import load_json_me_model import cobrame from sympy import Basic from os.path import dirname, abspath currency_met_to_synthesis_rxn = {'coa': 'DPCOAK', 'thf': 'DHFS', # use this reac...
<reponame>giovp/SingleCellOpenProblems from ....tools.decorators import method from ....tools.utils import check_version import numpy as np @method( method_name="NMF-reg", paper_name="Slide-seq: A scalable technology for measuring genome-wide expression at high spatial resolution", # noqa: E501 paper_ur...
<filename>attgcn_preprocessor/utils/test_utils.py import math import numpy as np from scipy.special import softmax import torch.nn.functional as F import torch.nn as nn from attgcn_preprocessor.utils.plot_utils import plot_predictions_cluster from attgcn_preprocessor.config import * from sklearn.utils.class_weight imp...
#!/usr/bin/env python import rospy import numpy as np from scipy import signal from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError # Applies a filter to images received on a specified topic and publishes the filtered image class Filter: # Initialize the filter def __init__(self, fi...
from typing import Optional, Dict, List, Tuple, AbstractSet from sympy import Poly, prod, factorial from sympy.abc import x from ccc.polynomialtracker import PolynomialTracker class Sequence(PolynomialTracker): """ Track sequences that meet specific constraints. """ def __init__( self, ...
from __future__ import print_function import os import sys import scipy import scipy import logging import scipy.io import threading import subprocess import numpy as np import pandas as pd from VGG import VGG import seaborn as sns from skimage import io from io import BytesIO import tensorflow as tf from scipy import ...
<filename>kernel_matrix_benchmarks/algorithms/ckdtree.py from __future__ import absolute_import from scipy.spatial import cKDTree from kernel_matrix_benchmarks.algorithms.base import BaseANN class CKDTree(BaseANN): """KD-Tree implementation, based on SciPy.""" def __init__(self, metric, leaf_size=20): ...
# =============================================================================== # Copyright 2012 <NAME> # # 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/LI...
import numpy as np from numpy import linalg as LA # Threshold # def omp_1(A, b): # r = b # Residual of k-1 # i = 0 # Counter # cols = A.shape[1] # rows = A.shape[0] # A_reduced = np.ones((rows, 1)) # As Matrix # A_reduced = np.delete(A_reduced, 0, 1) # X = np.zeros((cols, 1)) # s = [...
# construct pattern of direct beam and reflect from a model # build a one-d model import glob import os import numpy as np import matplotlib.pyplot as plt # for showing image #from pylab import * # for multiple figure window from skimage import io import re import statsmodels.api as sm from scipy.optimize import minimi...
from misc import ln, softmax import numpy as np import scipy.special as scs from misc import D_KL_nd_dirichlet, D_KL_dirichlet_categorical class HierarchicalPerception(object): def __init__(self, generative_model_observations, generative_model_states, generative_...
# This code is supporting material for the book # Building Machine Learning Systems with Python # by <NAME> and <NAME> # published by PACKT Publishing # # It is made available under the MIT License from __future__ import print_function import numpy as np from load_ml100k import get_train_test from scipy.spatial import...
<filename>data_munging.py import numpy as np import scipy.misc import matplotlib.pyplot as plt # import matplotlib as mpl import os import colorsys import cv2 import logging import itertools from colorcorrect.algorithm import grey_world from annotation import get_annotation, get_bbs from tools_plot import dispims fro...
import math import unittest import logging import re import numpy as np from imageio import imread from scipy.ndimage.interpolation import rotate from autocnet.examples import get_path from autocnet.transformation import roi from .. import ciratefi import pytest # Can be parameterized for more exhaustive tests upsa...
import cv2 import cv2.cv as cv import math import time import numpy as np import scipy.spatial.distance as spsd def lktrack(img1, img2, ptsI, nPtsI, winsize_ncc=10, win_size_lk=4, method=cv2.cv.CV_TM_CCOEFF_NORMED): """ **SUMMARY** Lucas-Kanede Tracker with pyramids **PARAMETERS** im...
<gh_stars>0 """My chocobo cooking script.""" """I left the chocobo here because I want to thank the chocobo package ""author for teaching me how to package!""" import os import warnings import scipy from sklearn.preprocessing import StandardScaler import scipy.stats from statsmodels.distributions.empirical_distribution...
from decimal import Decimal from fractions import Fraction f = Decimal('0.1'); print(type(f)); sum = 0; for i in range(100): sum += f; print(sum); a = Fraction(1,3); print(a);
<filename>src/util.py import time, random, math, numpy, os, sys, tempfile, pylab, subprocess, matplotlib, datetime, \ itertools as itl, copy, StringIO, cPickle as pickle, gc, collections, bisect, traceback import numpy as np import scipy.sparse import inspect #import networkx as nx #graph = nx def fail(s = ''...
import scipy.io.wavfile as wavfile import scipy.fft as fft import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import time import json import math import getopt import sys import warnings import os import subprocess import pathlib he...
from transformers import AutoModelForSeq2SeqLM, DataCollatorForSeq2Seq, Seq2SeqTrainingArguments, Seq2SeqTrainer from transformers import AutoTokenizer, MBartTokenizer from src.envs import build_env import torch.nn.functional as F import datasets import random import pandas as pd from datasets import Dataset import tor...
<filename>preoject_five_facenet/src/ForChineseCaptcha.py<gh_stars>1-10 """Validate a face recognizer on the "Labeled Faces in the Wild" dataset (http://vis-www.cs.umass.edu/lfw/). Embeddings are calculated using the pairs from http://vis-www.cs.umass.edu/lfw/pairs.txt and the ROC curve is calculated and plotted. Both t...
"""Implementation of sample attack.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import numpy as np import tensorflow as tf from tensorflow.contrib.slim.nets import inception from scipy.misc import imread from scipy.misc import i...
<reponame>ramanans1/planet # Copyright 2019 The PlaNet 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 # # Un...
import numpy as np import copy from scipy.special import expit, softmax from common.wbf_postprocess import weighted_boxes_fusion def yolo_decode(prediction, anchors, num_classes, input_dims, scale_x_y=None, use_softmax=False): '''Decode final layer features to bounding box parameters.''' batch_size = np.shape...
<gh_stars>1-10 from scipy.stats import bernoulli def generate_bernoulli_responses_contextual( actual_positive_rates, selected_action_ids, actual_cohort_ids): """ Given known actual response rates, real cohort membership, and selected actions, simulate respons`es and return list of N responses with...
import unittest from SimPEG import * from SimPEG import EM import sys from scipy.constants import mu_0 from SimPEG.EM.Utils.testingUtils import getFDEMProblem testDerivs = True testEB = True testHJ = True verbose = False TOL = 1e-5 FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order CONDUCTI...
<gh_stars>10-100 import networkx as nx import dgl import numpy as np from scipy.linalg import toeplitz import pyemd import time import concurrent.futures from scipy.linalg import eigvalsh import subprocess as sp import os from functools import partial from sklearn.metrics.pairwise import pairwise_kernels from eden.grap...