text string |
|---|
<reponame>hossam-mossalam/Speech-Recognition<filename>speech_utils.py<gh_stars>0
import glob as glob
import re
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import signal
from scipy.io import wavfile
labels = 'silence unknown'
# labels = 'yes no up down left right on off stop go... |
#################################################################################
# Copyright (c) 2011-2013, Pacific Biosciences of California, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are me... |
import numpy as np
from scipy import linalg
from functools import reduce
from scigym.envs.quantum_physics.quantum_information.entangled_ions.operations.qudit_qm import QuditQM
class LaserGates(QuditQM):
def __init__(self, dim, num_ions, phases):
"""
This class generates the required gate set for a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''astrokep.py - <NAME> (<EMAIL>) - 05/2016
Contains various useful tools for analyzing Kepler light curves.
'''
#############
## LOGGING ##
#############
import logging
from datetime import datetime
from traceback import format_exc
# setup a logger
LOGGER = None
LOGM... |
import h5py
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
hdf5_file = "/Volumes/lowegrp/Data/Kristina/MDCK_90WT_10Sc_NoComp/17_07_24/pos13/HDF/segmented.hdf5"
with h5py.File(hdf5_file, 'r') as f:
cell_map = f["tracks"]["obj_type_2"]["map"][0]
print (cell_map)
cell_tracks ... |
from plyfile import PlyData, PlyElement
import open3d as o3d
from pyobb.obb import OBB
import numpy as np
import os
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from scipy.spatial.transform import Rotation as R
import matplotlib.pyplot as plt
import argparse
import utils
def obb_calc(filename, gravity=np.... |
"""
Recurrent Neural Network Layer
"""
__authors__ = "<NAME>"
__copyright__ = "Copyright 2014, Universite de Montreal"
__credits__ = "<NAME>"
__license__ = "3-clause BSD"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import numpy as np
import scipy.linalg
from functools import wraps
from theano import config, scan,... |
<filename>python files/stokes_7_27.py
from sympy import symbols, diff, lambdify
from sympy import sinh,cosh, besselj
import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np
import mpmath as mp
mp.dps = 15
mp.pretty = True
# Step1: Define funcitons and variables.
# H is the height of the sec... |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 00:12:13 2018
Calculate Handcrafted Features
from autocorrelation
"""
from __future__ import division, print_function
import gc # garbage collector
import logging
import multiprocessing
import os
import sys
import time as t
from coll... |
#!/Users/areich/anaconda/bin/python
"""fitdist: Find the continuous probability distribution that best fits a dataset
.. moduleauthor:: <NAME> (<EMAIL>)
"""
import sys
import os
import logging
import csv
import numpy as np
import pandas as pd
import scipy.stats
# import statsmodels.api as sm
# Names of all contin... |
## dea_temporaltools.py
'''
Description: This file contains a set of python functions for conducting
temporal (time-domain) analyses on Digital Earth Australia data.
License: The code in this notebook is licensed under the Apache License,
Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). Digital Earth
Austral... |
<reponame>Jerin111/chameleon
import numpy as np
from scipy.special import comb
def external_index(v1, v2):
TP, FN, FP, TN = confusion_index(v1, v2)
RI = (TP + TN) / (TP + FN + FP + TN);
ARI = 2 * (TP * TN - FN * FP) / ((TP + FN) * (FN + TN) + (TP + FP) * (FP + TN));
JI = TP / (TP + FN + FP);
FM = T... |
<filename>Mock_Data/mock_data_generation/gen_posterior.py
import numpy as np
import argparse
from scipy.stats import truncnorm
from scipy.interpolate import interp1d
from astropy.cosmology import Planck18
cosmo = Planck18
import os
import sys
cdir = os.path.dirname(os.path.dirname(sys.path[0]))
np.random... |
<filename>bce/parser/molecule/ast/substitution.py<gh_stars>0
#!/usr/bin/env python
#
# Copyright 2014 - 2016 The BCE Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the license.txt file.
#
import bce.parser.molecule.ast.base as _ast_base
import bce.p... |
import sys
from abc import ABC
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Union
import numpy as np
from sympy import Symbol, symbols
from PartSegImage.image import Spacing
from ..algorithm_describe_base import AlgorithmDescribeBase, AlgorithmDescribeNotFound, AlgorithmProperty
from ..ch... |
<gh_stars>1-10
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import norm
from matplotlib import cm
class Net(nn.Module):
def __init__(self, hidden_layer_num, node_num):
... |
<reponame>warpalatino/public<gh_stars>1-10
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
from statsmodels.tsa.arima_model import ARMA
from scipy.stats.distributions import chi2
import statsmodels.tsa.stattools as sts
from math import sqrt
# ------... |
<filename>wavresample.py
from scipy.io import wavfile
# 读取文件
def wavwrite(wavsrc):
return wavsrc
# 文件压缩
def wavzip(wavsrc, filename, ziprate):
# 读取原始文件采样率
sampleRate, musicdata = wavfile.read(wavsrc)
# 压缩,储存
wavfile.write(filename, sampleRate // ziprate, musicdata[::5])
# wavzip(... |
<reponame>dan-zam/cdg
# --------------------------------------------------------------------------------
# Copyright (c) 2017-2020, <NAME>, All rights reserved.
#
# Implements several two-sample tests.
# --------------------------------------------------------------------------------
import numpy as np
from tqdm import... |
#!/usr/bin/env python
##########################################################################################################
# Modulo Bioestadistica - 2015 de la Universidad del Comahue. Centro Regional Bariloche
#http://crubweb.uncoma.edu.ar/
# Dr. <NAME>
# email: <EMAIL>
# licence: MIT. http://opensource.org/lic... |
# ==============================================================================
# This file demonstrates a bokeh applet. The applet has been designed at TUM
# for educational purposes. The structure of the following code bases to large
# part on the work published on
# https://github.com/bokeh/bokeh/tree/master/exampl... |
# Standard library imports
import os
import warnings
# Third party imports
import numpy as np
import astropy.units as u
from astropy.io import fits
from astropy import constants
from galpy.orbit import Orbit
from galpy.util.bovy_conversion import time_in_Gyr
from scipy.integrate import solve_ivp
from scipy.interpolate... |
<gh_stars>100-1000
import statistics
import math
l = [10, 1, 3, 7, 1]
mean = statistics.mean(l)
print(mean)
# 4.4
my_mean = sum(l) / len(l)
print(my_mean)
# 4.4
harmonic_mean = statistics.harmonic_mean(l)
print(harmonic_mean)
# 1.9408502772643252
my_harmonic_mean = len(l) / sum(1 / x for x in l)
print(my_harmonic_... |
# -*- coding: UTF-8 -*-
"""
@CreateDate: 2021/07/18
@Author: <NAME>
@File: _scale.py
@Project: stagewiseNN
"""
import os
import sys
from pathlib import Path
from typing import Sequence, Mapping, Optional, Union, Callable
import logging
import pandas as pd
import numpy as np
from scipy import sparse
import scanpy as sc
... |
<reponame>pythonhacker/talks
"""
Fix the code to perform float division and fix the assertion
"""
import fractions
def check(x, y):
""" A function checking for fractions """
ans = 1.0*x/y
# check fractional part
assert(fractions.Fraction(ans).denominator > 1)
if __name__ == "__main__":
chec... |
<gh_stars>1-10
'''
Copyright (c) 2021. IIP Lab, Wuhan University
'''
import numpy as np
import pandas as pd
from scipy.interpolate import interp1d
def linear_interpolation(l, r, alpha):
return l + alpha * (r - l)
class PiecewiseSchedule():
def __init__(self,
endpoints,
... |
# -*- coding: utf-8 -*-
"""
Multi-lib backend for POT
The goal is to write backend-agnostic code. Whether you're using Numpy, PyTorch,
or Jax, POT code should work nonetheless.
To achieve that, POT provides backend classes which implements functions in their respective backend
imitating Numpy API. As a convention, we ... |
"""
A fast, binary search tree-based algorithm for computing a series of aoK's
for a given list of times in O(N log K) for a list of length N
binary tree, initially record where cutoff for < or > 5% is.
keep track of sum of left/right bounds.
look at upper bound.
when removing/adding time, lower/lower - no effect
uppe... |
<filename>viroconcom/plot.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plots datasets, model fits and contour coordinates.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
__all__ = ["plot_sample", "plot_marginal_fit", "plot_dependence_functions",
"plot_con... |
<reponame>reddigari/pybaseball
from functools import partial
from typing import Tuple
import attr
import numpy as np
import pandas as pd
from scipy.integrate import RK45
from pybaseball.analysis.trajectories.unit_conversions import RPM_TO_RAD_SEC
from pybaseball.analysis.trajectories.utils import spin_components, uni... |
"""
Author: <NAME>
Date created: Mon 27 Apr 18:11:03 IST 2020
Description:
Main jetson/pc python file for controlling gimbal via the tracked object.
This file sends 3 peicewise spine curves coeff to the MCU @ 3fps.
License :
------------------------------------------------------------
"THE BEERWARE LICENSE"... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy.linalg import cho_factor, cho_solve
from gedi import gpKernel
def build_matrix(kern, x, yerr):
"""
build_matrix() creates the covariance matrix
Parameters
kern = kernel in use
x = range of v... |
<filename>cozy/syntax_tools.py<gh_stars>0
"""Utilities for working with syntax trees.
Important functions:
- pprint: prettyprint a syntax tree
- free_vars: compute the set of free variables
- alpha_equivalent: test alpha equivalence of two expressions
- unpack_representation: separate a packed expression into its ... |
from .preprocess import preprocess
from .affinity import (
compute_topics, compute_affinity,
calculate_affinity_distance,
create_lp_matrix, create_assignment
)
from .vectorizer import LogEntropyVectorizer, BM25Vectorizer
try:
from .lp import linprog
print("Using Google ortools library for ILP solver... |
<gh_stars>100-1000
#!/usr/bin/env python
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
<reponame>btalamini/optimism
import unittest
import scipy.spatial.transform.rotation as rotation
from optimism.test.TestFixture import TestFixture
from optimism.JaxConfig import *
from optimism import TensorMath
from jax import custom_jvp, random
from jax.test_util import check_grads
from jax.scipy import linalg
def... |
<reponame>cluhmann/segmented
import warnings
import numpy as np
import pandas as pd
import scipy.optimize
import scipy.stats
import patsy
tol = 1e-6
class segmented:
"""
Class implementing segmented regression.
...
Attributes
----------
models : list
List of model specifications i... |
<reponame>jchowk/rbcodes
# Code to compute wilsonscore confidence interval
from scipy.special import ndtri
import numpy as np
def rb_wilsonscore(count,nobs,confint):
#-----------------------------------------------------------------------------------
# This function computes the wilson score confidence intervals Sco... |
# -*- coding: utf-8 -*-
"""
Functions to compute fluxes of standard radio sources, the Sun, Venus,
Jupiter and Saturn. The brightness of the Galactic background emission
is also provided.
The origin of the data is given in the documentation for ``radio_flux``,
``planet\_brightness``, ``get\_planet\_flux``, and
``gala... |
<reponame>iksteen/pyxclib<filename>xclib/classifier/base.py
import logging
import scipy.sparse as sparse
import os
import numpy as np
import _pickle as pickle
import sys
from operator import itemgetter
class BaseClassifier(object):
"""
Base classifier for sparse or dense data
(suitable for large label set... |
<reponame>RoMeLaUCLA/ReDUCE<gh_stars>1-10
import os, sys
dir_ReDUCE = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(dir_ReDUCE+"/utils")
path_dataset = dir_ReDUCE + "/bookshelf_generator/bookshelf_scene_data"
from get_vertices import get_vertices, plot_rectangle
from book_problem_classes... |
import numpy as np
import scipy
from scipy.linalg import sqrtm
from tqdm import tqdm
from .utils import fill_doc
from .base import Connectivity, EpochConnectivity
@fill_doc
def vector_auto_regression(
data, times=None, names=None, model_order=1, l2_reg=0.0,
compute_fb_operator=False, model='dynamic',... |
from sympy import *
import sys
sys.path.insert(1, '..')
from rodrigues_R_utils import *
xsl, ysl, zsl = symbols('xsl ysl zsl')
xtg, ytg, ztg = symbols('xtg ytg ztg')
px, py, pz = symbols('px py pz')
sx, sy, sz = symbols('sx sy sz')
vzx, vzy, vzz = symbols('vzx vzy vzz')
position_symbols = [px, py, pz]
rodrigues_symbo... |
<filename>sl1m/planner_scenarios/talos/ramp_noGuide.py
import numpy as np
from sl1m.constants_and_tools import *
from numpy import array, asmatrix, matrix, zeros, ones
from numpy import array, dot, stack, vstack, hstack, asmatrix, identity, cross, concatenate
from numpy.linalg import norm
from sl1m.planner import *... |
<filename>dcnn/Basset/Basset/basset.py
import h5py
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import keras
import h5py
import numpy as np
from keras.layers import Input, Dense, Conv1D, MaxPooling2D, MaxPooling1D, BatchNormalization
from keras.layers.core import Dropout, Activation,... |
<filename>veritastool/metrics/tradeoff.py<gh_stars>1-10
import numpy as np
import sklearn.metrics as skm
from .fairness_metrics import FairnessMetrics
from .modelrates import *
from ..config.constants import Constants
from scipy.ndimage.filters import gaussian_filter
class TradeoffRate(object):
"""
Class to co... |
from sklearn.metrics import (accuracy_score, precision_score,
recall_score, f1_score,
classification_report)
from scipy.stats import pearsonr
from .finetuning_metrics import *
import numpy as np
class FinetuningMonitor:
def __init__(self, monitor_metric="... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Plotting functions for property histograms.
"""
#...for the logging.
import logging as lg
#...for even more MATH.
import numpy as np
#...for the factorial function.
from scipy.misc import factorial
#...for the least squares fitting.
from scipy import optimize
# Im... |
<reponame>mholowko/Solaris
import numpy as np
from matplotlib import pylab as plt
from sklearn.gaussian_process import GaussianProcessRegressor
import sklearn.kernel_approximation
from sklearn.gaussian_process.kernels import DotProduct
import scipy.optimize as opt
class GPUCB():
"""
Perform GPUCB algorithm
... |
<gh_stars>0
import copy
import textwrap
import astropy.constants as const
import astropy.units as u
import numpy as np
from scipy import interpolate
import xarray as xr
import psipy.visualization as viz
__all__ = ['Variable']
class Variable:
"""
A single scalar variable.
This class primarily contains... |
"""
Tests module connected.
# Author: <NAME>
# $Id$
"""
from __future__ import unicode_literals
from __future__ import absolute_import
__version__ = "$Revision$"
from copy import copy, deepcopy
import importlib
import unittest
import numpy
import numpy.testing as np_test
import scipy
from pyto.segmentation.grey... |
#from ...pybids import BIDSLayout
import os
import numpy as np
import pandas as pd
import nibabel as nb
from nibabel.processing import smooth_image
from scipy.stats import gmean
from nipype import logging
from nipype.utils.filemanip import fname_presuffix,split_filename,copyfiles
from nipype.interfaces.base import (
... |
# -*- coding: utf-8 -*-
"""Fcc_book_recommendation_knn.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1t3_cgmy4Dc58bTKKB5sEdZ4wDp05jXo-
*Note: You are currently reading this using Google Colaboratory which is a cloud-hosted version of Jupyter No... |
# Copyright (c) 2021 <NAME>, Helmholtz-Zentrum für Infektionsforschung GmbH (HZI)
# Copyright (c) 2021 <NAME>, Ostfalia Hochschule für angewandte Wissenschaften
# This software is distributed under the terms of the MIT license
# which is available at https://opensource.org/licenses/MIT
"""Pruner for hyperparameter op... |
<filename>src/dp_diff_gen.py
# Algorithm description
# DiffGen: differentially private anonymization based on generalization Mohammed et al. [26] proposed DiffGen to
# publish histograms for classification under differential privacy. It consists of 2 steps, partition and perturbation.
# Given a dataset D and taxonomy t... |
"""Helper which makes math calcs"""
import scipy
class MathHelper():
"""Class which makes math calcs"""
def rsquared(self, real_data, prediction):
""" Return R^2 where x and y are array-like."""
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(real_data, prediction)
... |
__copyright__ = """
Copyright (C) 2020 <NAME>
Copyright (C) 2020 <NAME>
"""
__license__ = """
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 ... |
"""
Contains functions for generating prior pseudo-samples and maximizing weighted log likelihood in logistic regression examples
Uses scipy optimize for gradient descent
"""
import numpy as np
import copy
import scipy as sp
from scipy.stats import bernoulli
def sampleprior(x,N_data,D_covariate,T_trunc,B_postsamples... |
"""Modified from https://github.com/CSAILVision/semantic-segmentation-pytorch"""
import os
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.io import loadmat
from torch.nn.modules import BatchNorm2d
from inference.segmentation import resnet
# constants
ARCH_ENCODER =... |
import torch
import os
import sys
import yaml
import numpy as np
import random
random.seed(1337)
import shutil
from utils.multipathvisualizerCombine import DrawpathCombine
from torch import nn
import utils.graphUtils.graphTools as graph
from scipy.spatial.distance import squareform, pdist
from dataloader.statetrans... |
<reponame>tirkarthi/odin-ai<gh_stars>1-10
from __future__ import print_function, division, absolute_import
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
import numpy as np
from scipy.signal import medfilt
from odin.visual import plot_save
from odin.preprocessing import signal, speech... |
<gh_stars>100-1000
# Copyright (c) 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Total load in each load zone.
"""
from sys import stderr
from numpy import zeros, ones, array, arange
from numpy import flatnonzero as find... |
<filename>paddleslim/quant/quant_post_hpo.py
# Copyright (c) 2021 PaddlePaddle 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/licen... |
# -*- coding: utf-8 -*-
"""Testing how the Stream works in Sounddevice
Created on Wed Dec 06 16:16:46 2017
@author: tbeleyur
"""
import sounddevice as sd
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
plt.rcParams['agg.path.chunksize'] = 10000
dev_id = 42
inout_ch = [24,3]
fs = 192000
s... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:17:42 2016
@author: ibackus
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
def _hexline(nx, firstSpacing=1):
"""
"""
x = np.zeros(nx)
nx0 = int((nx + 1)/2)
nx1 = nx - nx0
x0 = 3 * np.arang... |
from NEAT.neatLearner import NeatLearner
from NEAT.utils import unison_shuffle, print_hyperparameters
from arff_loader import load_arff
import matplotlib.pyplot as plt
import numpy as np
from os.path import join, exists
import pickle
from scipy.spatial.distance import euclidean
import shutil
import tqdm
GENERATIONS ... |
<filename>cieg/utils/covariance/_cov_cov/_cov_cov_cases.py
# Python translation: <NAME> 2020
# Code refactoring: <NAME>, <NAME> 2020
# Author: <NAME> - <EMAIL>
# Copyright (c) 2016
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe... |
<filename>Two-Way/visualiser.py
#lattice visualizer
import numpy as np
import scipy
import matplotlib as mpl
import matplotlib.pyplot as plt
"""
N = 10
fig, ax = plt.subplots()
#fig.set_size_inches(10,2)
ax.set_aspect(aspect=1)
"""
def lattice_grid(n,m,ax):
#plot horizontal lines
for i in range(m+1):
... |
<filename>ocv.py<gh_stars>10-100
import numpy as np
import cv2
import dimage
import statistics
import constants as c
MIN_WIDTH = 40
MIN_HEIGHT = 40
DEBUG = False
# imgBuf -> buffered image
# return list of dict (color, rects)
def analyze(imgBuf, debug = False):
global DEBUG
DEBUG = debug
rects = []
i... |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on 18/07/19
Author : <NAME>
"""
from __future__ import print_function, division
import os
import sys
import copy
import re
import getpass
os.environ["OMP_NUM_THREADS"] = "2"
os.environ["OPENBLAS_NUM_THREADS"] = "2"
os.environ["MKL_NUM_THREADS"] = "2"
os.environ["VECL... |
<reponame>jkcm/lagrangian-cset
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 6 16:42:46 2016
@author: jkcm
"""
import numpy as np
import warnings
from scipy import integrate
warnings.simplefilter("ignore")
p0 = 1000. # reference pressure, hPa
Rdry = 287. # gas const for dry air, J/K/kg
Rvap = 461. # gas const for... |
<filename>xg_boost_ensemble5.py
import xgboost as xgb
from sklearn.cross_validation import KFold
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix,hstack
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import *
from random import randint
class XgBoost:
def __ini... |
<filename>sd/algorithms/sdalgo.py
#!/usr/bin/env python
"""sdalgo.py: module is dedicated to SuperDARN custom algorithms."""
__author__ = "<NAME>."
__copyright__ = "Copyright 2020, SuperDARN@VT"
__credits__ = []
__license__ = "MIT"
__version__ = "1.0."
__maintainer__ = "<NAME>."
__email__ = "<EMAIL>"
__status__ = "Re... |
<gh_stars>1-10
#!/usr/bin/env python
#------------------------------------------------------------
# Purpose: Program to straight line parameters
# to data with errors in both coordinates
# Vog, 27 Nov, 2011
#------------------------------------------------------------
import numpy
from matplotlib.pyplot impor... |
<gh_stars>100-1000
"""
Simple example demonstrating a bilateral filter implented in C++.
Note that this is NOT the accelerated bilateral filter discussed in the Paper. This is just something fun I tried out that works for generalized meshes.
The accelerated bilateral filter for **organized** point clouds is found in Or... |
import random
import warnings
import numpy as np
import scipy.special
from sklearn import preprocessing
from scipy import stats
def softmax(x, temperature=1):
"""Applies softmax on a given list considering a temperature value. Softmax is applied row-wise if list is 2D.
Args:
x (ndarray(dtype=float, n... |
""" OpenPTV-Python is the GUI for the OpenPTV (http://www.openptv.net) liboptv library
based on Python/Enthought Traits GUI/Numpy/Chaco
Copyright (c) 2008-2013, Tel Aviv University
Copyright (c) 2013 - the OpenPTV team
The software is distributed under the terms of MIT-like license
http://opensource.org/licenses/M... |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank=pd.read_csv(path)
#print(bank.head())
categorical_var=bank.select_dtypes(include='object')
print(categorical_var)
numerical_var=bank.select_dtypes(include='number')
print(numerical_var)
... |
<filename>util_write_cap.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Utilities to prepare files for CAP
For reference see versions prior to Aug 25, 2016 for:
getwaveform_iris.py
getwaveform_llnl.py
20160825 cralvizuri <<EMAIL>>
"""
import obspy
from obspy.io.sac import SACTrace
import obspy.signal.r... |
<filename>src/utils/batch_generator.py<gh_stars>1-10
# batch gen
import random
import h5py
import numpy as np
from scipy.ndimage.interpolation import rotate, shift, affine_transform, zoom
from numpy.random import random_sample, rand, random_integers, uniform
# import matplotlib.pyplot as plt
import cv2
from tqdm import... |
from __future__ import absolute_import, division, print_function
import itertools
import inspect
from functools import wraps, partial
import numpy as np
import scipy.interpolate
import scipy.linalg
from future.builtins import zip, range
from future.backports import OrderedDict
import torch
from matplotlib.colors impo... |
<gh_stars>0
from typing import Tuple
import pandas as pd
import numpy as np
import os
import pickle
import obspy
from subprocess import call
import json
import datetime
from scipy.spatial import distance_matrix
import matplotlib.pyplot as plt
from PhaseNet_Analysis import PhaseNet_Analysis
from initial_param import *... |
<filename>analysis/.ipynb_checkpoints/analysis_backend-checkpoint.py<gh_stars>0
############## import modules and functions ###################
import seaborn
import pandas as pd
import numpy as np
import subprocess
import matplotlib.pyplot as plt
from scipy.stats import linregress
from vasppy.calculation import *
impo... |
<gh_stars>1-10
# script for collaborative filtering with K nearest users and L nearest questions
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial import distance
import pdb
import warnings
from scipy import sparse
import cPickle... |
#!/usr/bin/env python
from collections import OrderedDict
import numpy as np
from scipy import ndimage
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
import matplotlib.pyplot as plt
import time
import andys_models
import resnet
class reinforc... |
<gh_stars>1-10
import sys
sys.path.append(".")
import py
from sympy import *
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) == ((3*x**2-1)/2).expand()
assert legendre(3, x) == ((5*x**3-3*x)/2).expand()
assert legendre(10... |
"""
Implementations of functions for
Black-Scholes European Options Pricing
"""
import numpy as np
from numpy.random import default_rng
from scipy.stats import norm
from scipy.optimize import brentq
def generate_GBM_paths(n_samples, S0, T, r, sigma, dt, seed=2021):
"""
Exact simulation of GBM under the risk... |
#!/usr/bin/env python
from __future__ import print_function
import math
from scipy.stats import chisquare
from collections import defaultdict
def count_block_appearances(arr, m, sigma):
d = defaultdict(lambda: 0)
for i in range(math.floor(len(arr)/m)):
d["".join(map(str, arr[i*m:(i+1)*m]))] += 1
... |
# diststats.py - Distance distribution descriptors
# -----------------------------------------------
# This file is a part of DeerLab. License is MIT (see LICENSE.md).
# Copyright(c) 2019-2021: <NAME>, <NAME> and other contributors.
import numpy as np
import warnings
import copy
from scipy.signal import find_p... |
import gc
import glob
import os
import cv2
import numpy as np
import scipy.io as sio
from PIL import Image
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
class DataHandler:
def __init__(self):
print('data handler')
self.train_labels = None
... |
<filename>train_classifier.py<gh_stars>0
"""
Author: <NAME>
Contact: <EMAIL>
Date: 2017
MIT License: https://opensource.org/licenses/MIT
"""
import os
import logging
import argparse
import sys
import csv
import logging.config
from pathlib import Path
from sklearn import preprocessing
from sklearn.model_selection i... |
from transformers import BertTokenizer, BertModel
import torch
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
plt.rcParams.update({'font.size': 30, 'legend.fontsize': 20})
plt.rc('font', size=25)
plt.rc('axes', titlesize=25)
import sys
sys.path.append(".... |
import pytest
from UQpy.distributions import JointIndependent, Normal
from UQpy.sampling import MonteCarloSampling
from UQpy.distributions import Uniform
from UQpy.sensitivity.PceSensitivity import PceSensitivity
from UQpy.surrogates import *
import numpy as np
from UQpy.surrogates.polynomial_chaos.polynomials.TotalD... |
<filename>parameter_optimization/svc_using_GridSearchCV.py
# Baseline
import sys
import codecs
import logging
import os
import re
from collections import defaultdict
from lxml import etree
from collections import OrderedDict
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g.... |
import glob
import numpy as np
import random as random
import pandas as pd
from math import *
from datetime import datetime
from scipy.stats import rankdata
from pipeline_helper_functions import *
from get_edge_data import *
def get_test_cases(G, active_years, num_test_cases, seed=None):
"""
Get a list of te... |
# coding: utf8
# Author: <NAME> (~wy)
# Date: 2017
# Square Root Convergents
# Looking at root 2 approximations
from typing import Tuple
from fractions import Fraction
def approximation(n: int) -> Fraction:
# n ranges from 1 to infinity
if n == 1:
return Fraction(3,2)
else:
f = Fraction(1... |
"""
SIFT PCA Implementation based on implementation from
https://github.com/ahojnnes/local-feature-evaluation
Author: <NAME>
"""
from .DetectorDescriptorTemplate import DetectorAndDescriptor
import features.feature_utils as fu
import cv2
import numpy as np
from scipy.io import loadmat
import os
MAX_CV_KPTS = 1000
di... |
import numpy as np
import scipy.sparse
class Embeddings:
def __init__(self, embeddings, word2id):
self.embeddings = embeddings
self.embeddings /= (np.linalg.norm(self.embeddings, ord=2, axis=-1, keepdims=True) + 1e-4)
self.word2id = word2id
self.id2word = {i: w for w, i in word2id.... |
<filename>ODE.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 5 21:13:44 2016
@author: Xiao
"""
import numpy as np
from scipy import integrate
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import scipy.linalg as la
###Forward Euler Method
##delta_t 0.0012
delta_x = 0.05
delta_t = 0.00... |
<gh_stars>0
import pandas as pd
import sys
from os.path import basename
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.linear_model import Logis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.