text
string
<filename>mvlearn/decomposition/ajive.py # MIT License # Copyright (c) [2017] [<NAME>] # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ...
__author__ = "<NAME>" import unittest from copy import deepcopy from random import uniform from typing import List, Union from numpy import asarray, eye, ndarray from scipy.stats import unitary_group from theboss.boson_sampling_simulator import BosonSamplingSimulator from theboss.boson_sampling_utilities.permanent_c...
<filename>data_utility.py import os import glob import numpy as np from scipy import misc import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils import random class ToTensor(object): def __call__(self, sample): return...
import numpy import os import nltk import pdb import time import skipthoughts import cPickle from training import tools from scipy.io import loadmat def preprocess(line, vocab): '''Perform the same kind of preprocessing as in the IMDB experiments.''' tokens = nltk.word_tokenize(line) tokenized_sentence = ...
"""charcnn.py: classes that might be used when modeling classes. <NAME> <<EMAIL>>, 2020. No rights reserved. # C0 1.0 Universal _Official translations of this legal tool are available [in other languages]( https://creativecommons.org/publicdomain/zero/1.0/legalcode)._ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM...
<filename>IPythonWorkflow/uniformgradientboosting.py from __future__ import print_function from __future__ import division from collections import defaultdict, OrderedDict from itertools import izip import numbers from time import time import itertools import math import scipy.sparse as sparse import sklearn from skle...
<reponame>tesserato/envelope<filename>06graph.py import numpy as np import signal_envelope as se from scipy import interpolate import plotly.graph_objects as go for file in listdir("test_samples"): name = file.split(".")[0] print(name) W, _ = se.read_wav(f"test_samples/{name}.wav") amp = np.max(np.abs(W)) ...
<reponame>ManMohan291/PyProgram<gh_stars>1-10 from os import system import numpy as np import scipy.optimize as op import matplotlib.pyplot as plt #################################################################### def getPlot(): return plt #################################################################### def...
<reponame>Integrative-Transcriptomics/VIPurPCA import matplotlib.pyplot as plt import seaborn as sns from matplotlib import rcParams from sklearn.metrics.pairwise import euclidean_distances import pandas as pd import numpy as np #from Animation import gs import matplotlib from generate_samples import easy_example_data_...
<reponame>bthyreau/hippodeep from __future__ import print_function from lasagne.layers import get_output, InputLayer, DenseLayer, ReshapeLayer, NonlinearityLayer from lasagne.nonlinearities import rectify, leaky_rectify, elu import sys, os, time import nibabel import numpy as np import scipy.ndimage import theano imp...
<gh_stars>0 import os import glob import random import math import numpy as np from tqdm import tqdm from scipy.io import loadmat class ACCORDDataset(object): def __init__(self, data_dir, fault_flags, ab_range, time_steps, channels, k, use_normal): self.data_dir = data_dir # CWRUデータフォルダ self.fault_...
import numpy as np import matplotlib.pyplot as mpl from scipy.optimize import fmin_powell as fmin from scipy.odr import * from scipy.stats import chi2 t = np.asfarray([ 352 , 701 , 1048 , 1398 , 1751 , 2099 , 2446 , 2805 ]) t_err = np.asfarray([ 5 , 9 , 9 , 9 , 9 , 15 , 15 , 15 ]) dT = np.asfarray([ 10.0 , 19.7 ...
# tutorial on how to generate Poisson random numbers using the "direct method" # if we have a sequence of random numbers E following an exp. distribution lam * exp(-x/lam) # than the integer values where the cumulative sum \sum_{k=1}^n E_k > 1 follows a Poisson # distribution (homogeneous Poisson point process) import...
<gh_stars>0 """Contains code basic implementation of GAN modeling a Gaussian. - Improvement on version 1. - Better choice of latent variables. - Better learning rate decay. """ from pprint import pprint import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import scipy as sp import seaborn as sn...
""" total generalized variation zooming to demonstrate the cuda implementation You have to install pycuda and the cuda toolchain to be able to use the pycuda implementation. If you get errors during cuda kernel compilation, you might have to set the environment variable PYCUDA_DEFAULT_NVCC_FLAGS to an appropriate v...
import os import time import numpy as np import tensorflow as tf from scipy.misc import imread, imresize, imsave from tensorflow.contrib import rnn from data_manager import DataManager from utils import ( sparse_tuple_from, resize_image, label_to_array, ground_truth_to_word, levenshtein, ) os.envi...
<filename>gbra/attackers/attacker.py<gh_stars>1-10 import random import numpy as np from scipy import stats import snap from abc import abstractmethod from collections import Counter from gbra.recommender.recommenders import PixieRandomWalkRecommender class BaseAttacker(object): """Base configurations for an Atta...
import numpy as np import numpy.fft as fft import mrcfile from scipy import ndimage from scipy.interpolate import interp1d import scipy.stats as st def read_mrc(file): with mrcfile.open(file, permissive=True) as m: return m.data.astype(np.float32) def resize(arr, target_shape, **kwargs): idx = [] ...
""" Utility functions for the multiway matching """ import numpy as np import scipy.optimize as sco def u_projector(v, sizes): """ Projections over a set of permutation (for each graph) :param v: the current approximation matrix :param sizes: the sizes of the different graphs :return: the project...
from sympy import * def test_sin(): x, y = symbols('xy') k = Symbol('k', integer=True) assert sin(nan) == nan assert sin(oo*I) == oo*I assert sin(-oo*I) == -oo*I assert sin(0) == 0 assert sin(1) == sin(1) assert sin(-1) == -sin(1) assert sin(x) == sin(x) assert sin(-x) ==...
## Machine Learning Online Class # Exercise 8 | Anomaly Detection and Collaborative Filtering # # Instructions # ------------ # # This file contains code that helps you get started on the # exercise. You will need to complete the following functions: # # estimateGaussian.m # selectThreshold.m # cofiCos...
import math from scipy.stats import norm class BSM: def __init__(self, price, strike, interest_rate, volatility, time): self.S = price self.X = strike self.r = interest_rate self.v = volatility self.T = time @property def d1(self): d1_numerator = math.log(...
<gh_stars>1-10 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from sympy import symbols from sympy import limit if __name__ == '__main__': x = np.random.randn(1000) y = np.arange(1001) # plt.plot(x) # plt.show() print y s = np.random.dirichlet((10, 5, 3), 20).transpo...
import numpy as np from scipy.interpolate import interp1d import matplotlib import matplotlib.pyplot as plt from Make_Timelist import * import sys sys.path.insert(0, '/tera/phil/nchaparr/python') import nchap_fun as nc from matplotlib import rcParams rcParams.update({'font.size': 10}) """ Plots """ Fig1 = plt.f...
<reponame>h-mayorquin/g_node_data_analysis_205 import numpy as np import matplotlib.pyplot as plt import scipy.signal from load_data import responses_strong, stimulus_strong from math import floor plot_firing_rate = True plot_correlation = True ratio = 0.1 size_to_use = int(ratio * stimulus_strong.size) stimulus_stro...
<filename>patch_trcking_full.py # import the necessary packages from shape import ShapeDetector import argparse import imutils import cv2 import time # construct the argument parse and parse the arguments from imutils.video import VideoStream,FileVideoStream import numpy as np from scipy.spatial import distance # cons...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import glob import logging import argparse from collections import namedtuple from scipy.stats import poisson LEVEL = logging.INFO LOGFILE, LOGFILEMODE = '', 'w' HANDLERS = [logging.StreamHandler(sys.stdout)] if LOGFILE: HANDLERS.append(logging....
#!/usr/bin/env python # -*- coding: utf-8 -*- """ PSF Photometry. .. codeauthor:: <NAME> <<EMAIL>> """ import os.path import numpy as np import logging #from copy import deepcopy from scipy.optimize import minimize from . import BasePhotometry, STATUS from .psf import PSF from .utilities import mag2flux from .plots i...
<reponame>SkillsFundingAgency/das-data-management-ai import pickle import os import pandas as pd import numpy as np import pyarrow.parquet as pq import joblib import datetime import shap import math import xgboost as xgb import matplotlib.pyplot as plt from azureml.core.run import Run from azureml.core import Dataset, ...
"""Some sample datasets""" from __future__ import division import os import numpy as np from scipy import ndimage from sklearn.utils import check_random_state def get_megaman_image(factor=1): """Return an RGBA representation of the megaman icon""" imfile = os.path.join(os.path.dirname(__file__), 'megaman.pn...
<gh_stars>10-100 import tensorflow as tf import os import sys import data_generation import networks import scipy.io as sio import param import util import cv2 import truncated_vgg from keras.backend.tensorflow_backend import set_session from keras.optimizers import Adam from PIL import Image import numpy as np from ht...
<filename>bay_opt/acq.py<gh_stars>0 import numpy as np from scipy.stats import norm def lower_confidence_bound(X, Y, model, kappa=1.96): mu, sigma = model.predict(X, return_std=True) return mu - kappa * sigma def upper_confidence_bound(X, Y, model, kappa=1.96): mu, std = model.predict(X, return_std=True...
<reponame>srodney/romansims import os import numpy as np from matplotlib import pyplot as plt from scipy import interpolate as scinterp from datetime import datetime from astropy.io import fits from astropy.table import Table, Column, Row, MaskedColumn from astropy import table from astropy import units as u import s...
<reponame>Chenguang-Zhu/relancer #!/usr/bin/env python # coding: utf-8 # ## Sample End to End ML Project # # Note: made while learning with Chapter 2 of [Hands on ML Book](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/) , official code at [Github](https://github.com/ageron/handson-ml/bl...
<reponame>Conengmo/ovencontrol import matplotlib.pyplot as plt import control import numpy as np import scipy.linalg class PID: """Discrete PID control""" def __init__(self, Kp, Ki, Kd, u_max=None, u_min=None, integrator_max=None, integrator_min=None): self.Kp = Kp self.Ki = Ki self.Kd...
<gh_stars>1-10 from multiprocessing.pool import Pool import datajoint as dj from tqdm import tqdm from ..utils.measures import corr import numpy as np from scipy import stats from .parameters import DataConfig from .data import MovieMultiDataset, MovieScan from ..utils.logging import Messager schema = dj.schema('n...
<reponame>winsheng1996/fuzzy #################################################################### # # Pattern Search (PS) and Local Unimodal Sampling (LUS). # Heuristic optimization methods for real-valued functions. # # This is a preliminary version that needs a few features before release. # # Reference: # # Tuning ...
<reponame>OleBo/Stock-Prediction-Models import numpy as np import pandas as pd from scipy.cluster.hierarchy import dendrogram, linkage from scipy.cluster.hierarchy import cophenet from scipy.spatial.distance import pdist import pylab # On 20151227 by MLdP <<EMAIL>> # Hierarchical Risk Parity def getIVP(cov...
<gh_stars>0 import math from statistics import mean import random import numpy as np import pandas as pd from copy import deepcopy import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.cluster import MeanShift from sklearn.cluster import KMeans from sklearn.linear_model im...
import numpy as np def chan_vese(im_input, im_mask, sigma, dt=1.0, mu=0.2, lambda1=1, lambda2=1, iter=100): """Region-based level sets. Region-based level set implementation based on the Chan-Vese method. Provides cost terms for boundary length, the variance of intensities inside the ze...
from copy import deepcopy import numpy as np from scipy.stats import gamma, norm from ... import constants from ...constants import Version from .base import BMDModel, DefaultParams class Dichotomous(BMDModel): dtype = constants.DICHOTOMOUS possible_bmr = ("Extra", "Added") def get_bmr_text(self): ...
<reponame>FabianKaechele/Multivariate_Extension_Lorenz_Gini import pandas as pd import numpy as np import matplotlib.pyplot as plt import math import scipy.stats as st from matplotlib.colors import LightSource ####--------------------------------#### # This is the corresponing Python code to the paper "A multi...
#!/usr/bin/env python from __future__ import print_function, division import bayesloop as bl import numpy as np import sympy.stats as stats class TestTwoParameterModel: def test_step_set1TM_0hp(self): # carry out fit S = bl.OnlineStudy(storeHistory=True) S.setOM(bl.om.Gaussian('mean', bl....
<reponame>Amihaeseisergiu/Advanced-Chapters-Of-Neural-Networks import numpy as np, pickle, gzip, os from numpy.random import normal as rnorm, uniform as runif, shuffle, binomial from scipy import ndimage from scipy.ndimage import rotate, shift class Utility: def read_data(path): f = gzip.open(path, 'rb') ...
# (C) <NAME> and the Qrack contributors 2017-2021. All rights reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file or at https://opensource.org/licenses/MIT. import math, cmath from ctypes import * from .qrack_system import Qrack from .pauli import Pauli c...
import sys import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from sympy import symbols sys.path.append('../') from dmd import dmd if __name__ == '__main__': # Parameters t_start = 0.0 # start simulation time t_stop = 20.0 # stop simulations time ...
<reponame>liyang0711/puffins """Functionality relating to statistics, timeseries, etc.""" from eofs.xarray import Eof import numpy as np import scipy.stats import xarray as xr from .names import LAT_STR, YEAR_STR from .nb_utils import cosdeg # Trends: computing trends, detrending, etc. def trend(arr, dim, order=1, r...
# -*- Mode: python # # Licenses # Authors """\ Functions to handle openDX files ================================ Comments """ ########################################################################### #### imports # ########################################################################### import numpy...
<reponame>rcmalli/polimi-dl-project<filename>tools/create_fake_dataset.py<gh_stars>1-10 import numpy as np import os import pickle from tqdm import tqdm from scipy.ndimage import imread image_folder = '../data/fake/image' depthmap_folder = '../data/fake/depth' data = {'image':[],'depth':[]} image_paths = sorted([os....
<reponame>sekilas13/Python from __future__ import annotations from cmath import sqrt def akar_kuadrat(a: int, b: int, c: int) -> tuple[complex, complex]: """ diberikan koefisien numerik a, b dan c, menghitung akar untuk setiap persamaan kuadrat dalam bentuk ax^2 + bx + c >>> akar_kuadrat(a = 1,b = ...
import cPickle import numpy as np from scipy.io.wavfile import read from sklearn.mixture import GaussianMixture from featureextraction import extract_features #from speakerfeatures import extract_features import warnings warnings.filterwarnings("ignore") #path to training data # source = "development_set/" source ...
<reponame>dennis-l/tolteca #! /usr/bin/env python # Author: # <NAME> # # History: # 2020/02/15 <NAME>: # - First staged. """ This recipe makes use of the `KidsSimulator` to investigate the total PSD noise as function of Qr and the readout noise. """ from astropy import units as u from kidsproc.kidsmodel....
""" Location–Scale Family Distribution Base Class A location–scale family is a family of probability distributions parametrized by a location parameter and a non-negative scale parameter """ from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Type, TypeVar from jax import jit, scip...
<reponame>EgorOrachyov/MachineLearning import numpy as np import pandas as pd import random import array import csv from sklearn.preprocessing import OneHotEncoder from scipy.sparse import hstack from scipy.sparse import vstack from sklearn.utils import shuffle class Model: def __init__(self, n, k): self...
<filename>tests/cupyx_tests/scipy_tests/fft_tests/test_realtransforms.py<gh_stars>0 import numpy as np import pytest from cupyx.scipy import fft as cp_fft from cupy import testing try: # scipy.fft is available since scipy v1.4.0+ import scipy.fft as scipy_fft # noqa except ImportError: scipy_fft = None ...
import unittest import numpy as np import scipy.sparse from sklearn.datasets import load_boston, load_iris, load_wine from flaml import AutoML from flaml.data import get_output_from_log from flaml.model import SKLearnEstimator from rgf.sklearn import RGFClassifier, RGFRegressor from flaml import tune class MyRegul...
<gh_stars>1-10 # Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
from scipy.stats import chisquare import scipy.stats as stats import numpy as np # keypoints # nose-to-neck # neck-to-rsho, rsho-to-relb, relb-to-rwrist # neck-to-lsho, lsho-to-lelb, lelb-to-lwrist # neck-to-midhip # midhip-to-rhip, rhip-to-rknee, rknee-to-rankle # midhip-to-lhip, lhip-to-lknee, lknee-to-lankle man = ...
<reponame>OOAmusat/idaes-pse # -*- coding: utf-8 -*- ################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (ID...
""" Evaluate hermite polynomials using cuda * use modified version of previously written polynomial evaluator """ import warnings warnings.simplefilter('ignore',Warning) import numpy import time from math import sqrt, log10, exp, ceil import sys from optparse import OptionParser from scipy.special import hermite im...
import sys import os import jieba import logging import math import gensim import numpy as np from scipy.spatial import distance from pathlib import Path def sentence_similarity(input1, input2, model = None): # Word2Vec Cosine distance if len(input1) == 0 or len(input2) == 0: if len(input1) == 0: ...
<gh_stars>1-10 # coding: utf-8 # public items __all__ = [ "allan_variance", "copy_function", "deprecation_warning", "one_thread_per_process", "psd", "slicewhere", ] # standard library from collections import OrderedDict from contextlib import contextmanager from functools import wraps from lo...
<reponame>maoshenl/StarSampler import numpy as np import random as rand import scipy.optimize import scipy.special as ss import time def impt_sample(model_class, steps, resample_factor, samplesize, replace=True, r_vr_vt=False, r_v=False, filename=None): ''' Sampling Importance Resamplin...
<reponame>zhubaiyuan/learning-algorithms import numpy as np import timeit from scipy.optimize import curve_fit from common.table import DataTable from common.modeling import numpy_error, log_model def binary_array_search(nums, target): """ Use Binary Array Search to search for target in ordered list nums. ...
import pdb import numpy as np from scipy import linalg, optimize import cov class GP(object): def __init__(self,X,y,cov_type='covSEard'): self.X = X # training inputs, 2d array self.y = y # training outputs, 1d array self.cov_type = cov_type # string specifying covariance function ...
<filename>Files/pogo-bot.py #!/usr/bin/env python # -*- coding: utf-8 -*- # import the necessary packages import cv2 import numpy as np import imutils #colors from webcolors import rgb_to_name,CSS3_HEX_TO_NAMES,hex_to_rgb #python3 -m pip install webcolors from scipy.spatial import KDTree def convert_rgb_to_names(rgb_tu...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
<reponame>rickyHong/MS-CNTK # ============================================================================== # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # =======================================================...
<reponame>jazminferreiro/simulacion<gh_stars>0 # -*- coding: utf-8 -*- import datetime, time class GeneradorLinealCongruente: def __init__(self,a,c,m, inicial): self.a = a self.c = c self.m= m self.actual = inicial def generar(self): self.actual = (self.a*self.actual + ...
import datetime from datetime import timedelta from statistics import mean from typing import Dict from typing import Optional from typing import Tuple from django.utils import timezone from chat_wars_database.app.business_core.models import Item from chat_wars_database.app.business_exchange.models import StatsByDay ...
<filename>examples/double_pendulum/double_pendulum.py # # from modeling.mechanics.dynamics import MechanicalSystem from lib.symbolical_dynamics.euler_lagrange import MechanicalSystem from sympy import Matrix, symbols, cos, sin, simplify, lambdify from sympy.utilities.autowrap import autowrap from sympy.utilities.codege...
# coding=utf-8 # Copyright 2021 The Google Research 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
<filename>classifiers.py from skimage.transform import hough_line, hough_line_peaks from skimage.morphology import disk, binary_erosion from skimage.measure import label, regionprops import numpy as np from scipy import stats from skimage.draw import line from itertools import groupby import math import cv2 from common...
<gh_stars>1-10 import torch import torch.nn as nn import torch.nn.functional as F class ResBlock(nn.Module): def __init__(self, channels, scale=0.1): super(ResBlock, self).__init__() self.conv1 = nn.Conv2d(channels, channels, 3, 1, padding=1) self.conv2 = nn.Conv2d(channels, channels, 3, 1,...
<filename>udacity/assigment1.py from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy import ndimage from sklearn.linear_model import LogisticRegression from six.moves.urllib.request import urlr...
#!python3 from ut import p from fractions import * F = Fraction p("Fraction") fr1 = F('0.2') print(fr1) print(fr1.numerator) print(fr1.denominator) p("num/den") fr1 = F(2, 10) print(fr1) print(fr1.numerator) print(fr1.denominator) p('from float') print(Fraction.from_float(0.2))
import numpy as np import scipy.sparse as sparse import matplotlib.pyplot as plt import matplotlib.colors as c import matplotlib as mpl import scipy.sparse.linalg as slinalg import time as time import cv2 # Default arguments: # delta_x Numpy array of length 3 containing the size of the grid # dx: Numpy...
<filename>tabular/src/autogluon/tabular/models/tabular_nn/categorical_encoders.py """ Variant of the sklearn OneHotEncoder and OrdinalEncoder that can handle unknown classes at test-time as well as binning of infrequent categories to limit the overall number of categories considered. Unknown categories are returned a...
<reponame>YiZhan2854/ppnp import numpy as np import scipy.sparse as sp import tensorflow as tf from .utils import sparse_matrix_to_tensor, sparse_dropout sparse_dot = tf.sparse_tensor_dense_matmul def calc_A_hat(adj_matrix: sp.spmatrix) -> sp.spmatrix: nnodes = adj_matrix.shape[0] A = adj_matrix + sp.eye(nn...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2020 Intel Corporation # # 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...
<filename>scripts/sources/S_FlexibleCombinationsModels.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.4 # kernelspec: # display_name: Python 3 ...
import numpy as np import cvxpy as cvx from scipy import sparse from time import time def project(W, **kw): verbose = kw.get('verbose', False) M = len(W) V = cvx.Variable(M) p = cvx.Problem(cvx.Minimize(cvx.norm2(V-W)), [cvx.sum_entries(V) == 1., V > 0.]) try: p.solve(max_iters=100000, ver...
<filename>skextremes/models/wind.py """ This module contains algorithms found in the literature and used extensively in wind energy engineering as standard methods. For more information visit: https://www.ecn.nl/publications/ECN-C--98-096 https://webstore.iec.ch/preview/info_iec61400-1%7Bed3.0%7Den.pdf """ import n...
import os import pickle import glob import re import pyedflib import numpy as np import scipy.signal as ssignal from tqdm import tqdm from sklearn import preprocessing # AUTHOR: https://github.com/drasros/sleep_staging_shhs/blob/master/shhs.py # NOTE: Does not work on SHHS2 yet... # SHHS2 has a mix of 125Hz recor...
import numpy as np from numpy.linalg import norm from scipy.sparse import issparse import scipy.sparse.linalg as slinalg from sparse_ho.forward import get_beta_jac_iterdiff class Backward(): def __init__(self, criterion): self.criterion = criterion def get_beta_jac_v( self, X, y, log_alph...
<gh_stars>1-10 import scipy.io as sio import scipy.stats as sps import numpy as np import teneto import matplotlib.pyplot as plt import pandas as pd #import teneto.stats.shufflegroups as shuffle plt.rcParams['image.cmap'] = 'gist_gray' Eeo=np.zeros([46]) Eec=np.zeros([46]) for s in range(0,46): print('Calculati...
<filename>PyQuantum/TC_closed/Hamiltonian.py<gh_stars>0 # --------------------------------------------------------------------------------------------------------------------- # system # --------------------------------------------------------------------------------------------------------------------- # scientific im...
<gh_stars>1-10 """ Implementation of simple bandit and gradient bandit algorithm from chapter 2 of Sutton andBarto's "Reinforcement Learning" """ import numpy as np from scipy.special import softmax def simple_bandit_alg(MAB, epsilon, max_steps, alpha = 0, Q1 = 0, UCB = False, c = 2, ru...
""" Test the ColumnTransformer. """ import numpy as np from scipy import sparse import pytest from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing i...
import numpy as np import networkx as nx import matplotlib.pyplot as plt import matplotlib.patches as patches import scipy from sklearn.cluster import KMeans import AnchorSet MAX_PAIRWISE_SCORE = 11 #based on blosum62, probably needs adjustment for other matrices # based on an anchor set, defines a set of patterns ...
<reponame>edu-gp/annotation_tool<gh_stars>1-10 import json import os import shlex import subprocess import numpy as np import pandas as pd from scipy.special import softmax from sklearn.model_selection import train_test_split BINARY_CLASSIFICATION = "binary" MULTILABEL_CLASSIFICATION = "multilabel" # TODO: Move loa...
from pytexmex.core import * import numpy as np, pandas as pd import scipy.stats import warnings def read_otu_table(fn, transpose=False): ''' Read an OTU table from a filename (or filehandle). It expects to have OTUs on the rows and samples on the columns (i.e., QIIME style). If the table is wider than ...
import pysal as ps import numpy as np import scipy.spatial as ss from random import shuffle import itertools #Build the lattices and save as a shapefile lattices = [32,100,224,317] for lattice in lattices: ps.weights.build_lattice_shapefile(lattice,lattice,"{}.shp".format(lattice**2)) polys = [1000,10000,500...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram, fcluster from dtaidistance import dtw, dtw_visualisation, clustering from dtaidistance import dtw_visualisation as dtwvis from sklearn.preprocessing import RobustScaler, StandardScaler import pickle fr...
<reponame>umarov90/DeepFake<filename>deepfake.py import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = '0' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from tensorflow.python.keras import regularizers from tensorflow.python.keras import backend as K from tensorflow.python.keras.laye...
<filename>tensorflow_quantum/python/layers/high_level/noisy_pqc_test.py # Copyright 2020 The TensorFlow Quantum 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 #...
import gym import numpy as np import random import scipy.special import rl from gym.spaces import Box from gym.spaces import Discrete from rl.np.distributions import CategoricalProbabilityDistributionType from rl.np.distributions import DiagonalGaussianProbabilityDistributionType class ProbabilityDistributionTypeFact...
<gh_stars>0 import numpy as np import scipy from scipy.stats import norm #import astropy functions for use in bootstrap (optional) try: import astropy from astropy.stats import biweight_location except ImportError: astropy = None # BCES fitting # =============== def bces(y1, y1err, y2, ...
## EKE SPEC PLOT from __future__ import print_function path1 = '/network/aopp/cirrus/pred/kloewer/swm_back_ronew/' path2 = '/network/aopp/cirrus/pred/kloewer/swm_bf_cntrl/data/' outpath = '/network/home/aopp/kloewer/swm/paperplot/' import os; os.chdir(path2) # change working directory import numpy as np from scipy im...
import numpy as np from skimage.exposure import equalize_adapthist import torch from scipy.ndimage import gaussian_filter import scipy import random import torch as th from PIL import Image from scipy.interpolate import RectBivariateSpline class MyRandomImageContrastTransform(object): def __init__(self, random_s...