code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import math
import numpy as _np
import numba as _numba
import contextlib
@contextlib.contextmanager
def corrfunction(shape, z, qmax, xcenter=None, ycenter=None):
"""
CPU based radial Autocorrelation with q correction
parameters:
shape (tuple) of inputs in pixels
z (scalar) distance of detector in... | [
"numpy.sqrt",
"numba.njit",
"numpy.asarray",
"math.sqrt",
"numpy.zeros",
"numba.prange",
"numpy.arange"
] | [((864, 898), 'numpy.sqrt', '_np.sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (872, 898), True, 'import numpy as _np\n'), ((740, 779), 'numpy.arange', '_np.arange', (['shape[1]'], {'dtype': '_np.float64'}), '(shape[1], dtype=_np.float64)\n', (750, 779), True, 'import numpy as _np\n'), ((... |
from builtins import zip
# Gamma-ray burst afterglow metric
# <EMAIL>
import rubin_sim.maf.metrics as metrics
import numpy as np
__all__ = ['GRBTransientMetric']
class GRBTransientMetric(metrics.BaseMetric):
"""Detections for on-axis GRB afterglows decaying as
F(t) = F(1min)((t-t0)/1min)^-alpha. No jet break... | [
"numpy.log10",
"numpy.unique",
"numpy.where",
"numpy.searchsorted",
"numpy.floor",
"numpy.diff",
"numpy.argsort",
"builtins.zip",
"numpy.zeros",
"numpy.sum",
"numpy.random.randn",
"numpy.arange"
] | [((4028, 4060), 'numpy.zeros', 'np.zeros', (['time.size'], {'dtype': 'float'}), '(time.size, dtype=float)\n', (4036, 4060), True, 'import numpy as np\n'), ((4080, 4110), 'numpy.where', 'np.where', (['(time > self.peakTime)'], {}), '(time > self.peakTime)\n', (4088, 4110), True, 'import numpy as np\n'), ((5151, 5212), '... |
import numpy as np
from pickle import load
import random
import os
from sklearn.model_selection import train_test_split
from keras.models import load_model
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import confusion_matrix, classification_report
from Model_setup import single_lstm
import warning... | [
"keras.models.load_model",
"sklearn.model_selection.train_test_split",
"os.getcwd",
"numpy.array",
"Model_setup.single_lstm",
"numpy.load",
"warnings.filterwarnings",
"numpy.save"
] | [((322, 355), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (345, 355), False, 'import warnings\n'), ((383, 394), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (392, 394), False, 'import os\n'), ((591, 664), 'numpy.load', 'np.load', (['f"""/home/ubuntu/Final-Project-Group1/... |
import sys
import csv
import numpy as np
STATES = ["NEU", "NEG", "POS", "BOS"]
def build_transition(fpath, num_states):
transitions = []
with open(fpath) as f:
reader = csv.reader(f)
for idx, row in enumerate(reader):
#if idx == 3:
#break
s = row[-5:]
... | [
"numpy.zeros",
"csv.reader"
] | [((457, 495), 'numpy.zeros', 'np.zeros', (['(num_states + 1, num_states)'], {}), '((num_states + 1, num_states))\n', (465, 495), True, 'import numpy as np\n'), ((189, 202), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (199, 202), False, 'import csv\n')] |
import numpy as np
import time
from SWMMSE import SWMMSE
def channel(N, num_train, Pmax=1, Pmin=0, var_noise=1, seed=1758):
print('Generate Data ... (seed = %d)' % seed)
np.random.seed(seed)
Pini = Pmax * np.ones(N)
X = np.zeros((N ** 2, num_train))
Y = np.zeros((num_train, N ))
X_t = np.zeros(... | [
"numpy.reshape",
"numpy.ones",
"numpy.sqrt",
"numpy.zeros",
"numpy.random.randn",
"numpy.random.seed",
"SWMMSE.SWMMSE",
"time.time"
] | [((179, 199), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (193, 199), True, 'import numpy as np\n'), ((237, 266), 'numpy.zeros', 'np.zeros', (['(N ** 2, num_train)'], {}), '((N ** 2, num_train))\n', (245, 266), True, 'import numpy as np\n'), ((275, 299), 'numpy.zeros', 'np.zeros', (['(num_train, ... |
# Generate preprocessed image/label datasets
from pathlib import Path
from random import shuffle
from termios import VMIN
import numpy as np
#from matplotlib import pyplot as plt
import torch
from torchvision import datasets,transforms
Path("./prepped_mnist").mkdir(parents=True, exist_ok=True)
#device = torch.devi... | [
"random.shuffle",
"pathlib.Path",
"torch.load",
"torch.max",
"torch.min",
"torch.fill_",
"numpy.random.randint",
"torch.save",
"torchvision.transforms.Normalize",
"torchvision.transforms.ToTensor",
"torch.cat",
"torch.ones"
] | [((978, 1033), 'torch.save', 'torch.save', (['train', '"""./prepped_mnist/centered_train.dat"""'], {}), "(train, './prepped_mnist/centered_train.dat')\n", (988, 1033), False, 'import torch\n'), ((1035, 1088), 'torch.save', 'torch.save', (['test', '"""./prepped_mnist/centered_test.dat"""'], {}), "(test, './prepped_mnist... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 08 09:26:27 2016
@author: <NAME>
"""
from financepy.finutils.FinTestCases import FinTestCases, globalTestCaseMode
from financepy.market.curves.FinPolynomialCurve import FinPolynomialCurve
from financepy.finutils.FinDate import FinDate
import numpy as np
import sys
sys.pa... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"financepy.finutils.FinTestCases.FinTestCases",
"numpy.linspace",
"matplotlib.pyplot.figure",
"financepy.finutils.FinDate.FinDate",
"financepy.market.curves.FinPolynomialCurve.FinPolynomialCurve",
"sys.path.append",
... | [((314, 339), 'sys.path.append', 'sys.path.append', (['"""..//.."""'], {}), "('..//..')\n", (329, 339), False, 'import sys\n'), ((629, 671), 'financepy.finutils.FinTestCases.FinTestCases', 'FinTestCases', (['__file__', 'globalTestCaseMode'], {}), '(__file__, globalTestCaseMode)\n', (641, 671), False, 'from financepy.fi... |
import argparse
import importlib
import json
import math
import os
import matplotlib
import numpy as np
import tensorflow as tf
import utils
from config_rnn import defaults
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# -----------------------------------------------------------------------------
parser = ... | [
"numpy.sqrt",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"utils.find_model_metadata",
"math.gamma",
"argparse.ArgumentParser",
"tensorflow.placeholder",
"tensorflow.Session",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.max",
"numpy.exp",
"matplotlib.pyplot.close",... | [((176, 197), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (190, 197), False, 'import matplotlib\n'), ((320, 345), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (343, 345), False, 'import argparse\n'), ((639, 668), 'config_rnn.defaults.set_parameters', 'defaults.set_pa... |
import numpy as np
import pandas as pd
import struct
import os
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
'''
#### Script designed to use 6 cores
#### Network configuration are analyzed in serie and stimuli intensitie in parallel
#### run from terminal using: 'mpirun -np 6 python get_psth.py'
... | [
"numpy.histogram",
"numpy.ones",
"pandas.read_csv",
"numpy.arange",
"numpy.where",
"struct.unpack",
"numpy.save"
] | [((1727, 1751), 'numpy.arange', 'np.arange', (['lb', 'ub', 'dtbin'], {}), '(lb, ub, dtbin)\n', (1736, 1751), True, 'import numpy as np\n'), ((919, 943), 'numpy.arange', 'np.arange', (['lb', 'ub', 'dtbin'], {}), '(lb, ub, dtbin)\n', (928, 943), True, 'import numpy as np\n'), ((3125, 3171), 'numpy.save', 'np.save', (["('... |
"""Functions necessary for synthetic seismic modelling (e.g. sim2seis).
"""
from typing import Any, Literal, List, Sequence
import numpy as np
import xarray as xr
from numpy import typing as npt
from scipy.interpolate import interp1d
from scipy.signal import fftconvolve
import scipy.ndimage
from tqdm import ... | [
"numpy.pad",
"numpy.isnan",
"numpy.full_like",
"scipy.signal.fftconvolve"
] | [((1191, 1221), 'numpy.full_like', 'np.full_like', (['velp[:-1]', 'theta'], {}), '(velp[:-1], theta)\n', (1203, 1221), True, 'import numpy as np\n'), ((2140, 2160), 'numpy.pad', 'np.pad', (['refl', '(1, 0)'], {}), '(refl, (1, 0))\n', (2146, 2160), True, 'import numpy as np\n'), ((498, 509), 'numpy.isnan', 'np.isnan', (... |
import torch
from torch.utils.data import Dataset
import numpy as np
import pandas as pd
import utils
class DatasetWithNegativeSampling(Dataset):
"""
We create new Dataset class because for pairwise ranking loss, an important step is negative sampling.
For each user, the items that a user has not interact... | [
"utils.torch_from_pandas",
"numpy.random.choice",
"utils.split_data",
"torch.from_numpy",
"pandas.DataFrame"
] | [((2249, 2323), 'numpy.random.choice', 'np.random.choice', (['user_df[self.item_col].values', 'self.num_positive_in_test'], {}), '(user_df[self.item_col].values, self.num_positive_in_test)\n', (2265, 2323), True, 'import numpy as np\n'), ((3826, 3929), 'pandas.DataFrame', 'pd.DataFrame', (['{self.user_col: users, self.... |
# import sys
# sys.path.append('../../')
import numpy as np
import pandas as pd
import json
import copy
from plot_helper import coloring_legend, df_col_replace
from constant import REPORTDAYS, HEADER_NAME, COLUMNS_TO_DROP, FIRST_ROW_AFTER_BURNIN
def single_setting_IQR_json_generator(fpath_pattern_list, outfile_dir, ou... | [
"pandas.read_csv",
"plot_helper.df_col_replace",
"numpy.quantile",
"copy.deepcopy",
"json.dump"
] | [((833, 877), 'numpy.quantile', 'np.quantile', (['all_100_T01s', '[0.25, 0.5, 0.75]'], {}), '(all_100_T01s, [0.25, 0.5, 0.75])\n', (844, 877), True, 'import numpy as np\n'), ((1079, 1104), 'copy.deepcopy', 'copy.deepcopy', (['dflist_arg'], {}), '(dflist_arg)\n', (1092, 1104), False, 'import copy\n'), ((1584, 1628), 'nu... |
# Analytic Hierarchy Process
import numpy as np
# class myAHP
class myAHP:
# __init__(self)
def __init__(self):
# print("__init__(self).start...")
self.RI_dict = {
1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32,
8: 1.41, 9: 1.45,... | [
"numpy.array",
"numpy.transpose"
] | [((507, 747), 'numpy.array', 'np.array', (['[[0.5, 0.77, 0.48, 0.68, 0.47, 0.38], [0.23, 0.5, 0.28, 0.45, 0.32, 0.23],\n [0.52, 0.72, 0.5, 0.75, 0.48, 0.4], [0.32, 0.55, 0.25, 0.5, 0.23, 0.2],\n [0.53, 0.68, 0.52, 0.77, 0.5, 0.48], [0.62, 0.77, 0.6, 0.8, 0.52, 0.5]]'], {}), '([[0.5, 0.77, 0.48, 0.68, 0.47, 0.38],... |
import os
import numpy as np
import torch as T
import torch.nn.functional as F
from networks import ActorNetwork, CriticNetwork
from noise import OUActionNoise
from buffer import ReplayBuffer
import gym
from matplotlib import pyplot as plt
class Agent():
def __init__(self, alpha, beta, input_dims, tau, ... | [
"numpy.mean",
"torch.nn.functional.mse_loss",
"torch.mean",
"torch.tensor",
"numpy.zeros",
"numpy.array",
"networks.CriticNetwork",
"buffer.ReplayBuffer",
"numpy.save",
"gym.make",
"networks.ActorNetwork"
] | [((5107, 5130), 'gym.make', 'gym.make', (['"""Pendulum-v0"""'], {}), "('Pendulum-v0')\n", (5115, 5130), False, 'import gym\n'), ((606, 651), 'buffer.ReplayBuffer', 'ReplayBuffer', (['max_size', 'input_dims', 'n_actions'], {}), '(max_size, input_dims, n_actions)\n', (618, 651), False, 'from buffer import ReplayBuffer\n'... |
import numpy as np
from collections.abc import Sequence
from typing import BinaryIO
from ..gmxflow import GmxFlow, GmxFlowVersion
# Fields expected to be read in the files.
__FIELDS = ['X', 'Y', 'N', 'T', 'M', 'U', 'V']
# Fields which represent data in the flow field, excluding positions.
__DATA_FIELDS = ['N', 'T',... | [
"numpy.prod",
"numpy.fromfile",
"numpy.zeros",
"numpy.meshgrid",
"numpy.arange"
] | [((1343, 1357), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (1350, 1357), True, 'import numpy as np\n'), ((1373, 1407), 'numpy.zeros', 'np.zeros', (['(num_bins,)'], {'dtype': 'dtype'}), '((num_bins,), dtype=dtype)\n', (1381, 1407), True, 'import numpy as np\n'), ((2430, 2462), 'numpy.meshgrid', 'np.meshgrid'... |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
\file processData.py
\copyright Copyright (c) 2019 Visual Computing group of Ulm University,
Germany. See the LICENSE file at the top-level directory of
this distribution.
\author <NAME>... | [
"os.listdir",
"os.path.join",
"os.path.isfile",
"numpy.array",
"os.path.abspath"
] | [((556, 581), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (571, 581), False, 'import os\n'), ((600, 637), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""MCCNN/utils"""'], {}), "(ROOT_DIR, 'MCCNN/utils')\n", (612, 637), False, 'import os\n'), ((726, 757), 'os.path.isfile', 'isfile', (["(... |
import os
from base64 import b64encode, b64decode
from typing import AnyStr, List, Dict
from collections import Counter
import numpy as np
import cv2 as cv
import keras
import tensorflow as tf
from yolo4.model import yolo4_body
from decode_np import Decode
__all__ = ("DetectJapan", "detect_japan_obj")
session = tf.... | [
"cv2.imencode",
"decode_np.Decode",
"tensorflow.Session",
"keras.backend.set_session",
"base64.b64decode",
"collections.Counter",
"numpy.array",
"keras.Input",
"numpy.frombuffer",
"cv2.resize",
"os.path.expanduser"
] | [((317, 329), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (327, 329), True, 'import tensorflow as tf\n'), ((330, 364), 'keras.backend.set_session', 'keras.backend.set_session', (['session'], {}), '(session)\n', (355, 364), False, 'import keras\n'), ((415, 447), 'os.path.expanduser', 'os.path.expanduser', (['c... |
from pathlib import Path
import pathlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from typing import Union , Tuple
class QuestionnaireAnalysis:
def __init__(self, data_fname: Union[pathlib.Path, str]):
self.data_fname = pathlib.Path(data_fname).resolve()
if not s... | [
"numpy.histogram",
"pandas.read_json",
"pathlib.Path"
] | [((443, 472), 'pandas.read_json', 'pd.read_json', (['self.data_fname'], {}), '(self.data_fname)\n', (455, 472), True, 'import pandas as pd\n'), ((591, 665), 'numpy.histogram', 'np.histogram', (["df['age']"], {'bins': '[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]'}), "(df['age'], bins=[0, 10, 20, 30, 40, 50, 60, 70, 80,... |
import os
import sys
import argparse
import numpy as np
import matplotlib.pyplot as plt
from ruamel import yaml
# in order to import modules from a folder in path '../cli/'
sys.path.insert(1, '../cli/') # insert at 1, 0 is the script path (or '' in REPL)
import modules.utilities as utilities
import modules.Mat... | [
"os.listdir",
"sys.path.insert",
"argparse.ArgumentParser",
"ruamel.yaml.load",
"numpy.trunc",
"os.path.realpath",
"matplotlib.pyplot.close",
"os.mkdir",
"sys.exit",
"matplotlib.pyplot.subplots_adjust"
] | [((174, 203), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""../cli/"""'], {}), "(1, '../cli/')\n", (189, 203), False, 'import sys\n'), ((887, 1146), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""plottestgrid.py"""', 'usage': '""" \n python3 plottestgrid.py <folder> <distribution name> <di... |
import numpy as np
import tflite_runtime.interpreter as tflite
import os, fnmatch
class ML_Loader(object):
def __init__(self, model_info):
# Init loader by loading model into the object
self.model_info = model_info
if (self.model_info["mlinfrastructure"] == "edge"):
file_list = ... | [
"tflite_runtime.interpreter.Interpreter",
"os.listdir",
"numpy.array",
"tensorflow.keras.models.load_model",
"numpy.empty",
"fnmatch.fnmatch"
] | [((320, 350), 'os.listdir', 'os.listdir', (["model_info['path']"], {}), "(model_info['path'])\n", (330, 350), False, 'import os, fnmatch\n'), ((596, 647), 'tflite_runtime.interpreter.Interpreter', 'tflite.Interpreter', (["(model_info['path'] + model_file)"], {}), "(model_info['path'] + model_file)\n", (614, 647), True,... |
import numpy as np
from deepthought.experiments.encoding.experiment_templates.base import NestedCVExperimentTemplate
class SVCBaseline(NestedCVExperimentTemplate):
def pretrain_encoder(self, *args, **kwargs):
def dummy_encoder_fn(indices):
if type(indices) == np.ndarray:
ind... | [
"deepthought.experiments.encoding.classifiers.linear_svc.LinearSVCClassifierFactory",
"numpy.ascontiguousarray"
] | [((727, 765), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['data[source_idx]'], {}), '(data[source_idx])\n', (747, 765), True, 'import numpy as np\n'), ((1208, 1236), 'deepthought.experiments.encoding.classifiers.linear_svc.LinearSVCClassifierFactory', 'LinearSVCClassifierFactory', ([], {}), '()\n', (1234, 1236... |
#####################################################
# This file is a component of ClusterGB #
# Copyright (c) 2018 <NAME> #
# Released under the MIT License (see distribution) #
#####################################################
"""
Run `voro++ <http://math.lbl.gov/voro++/>`_ on a s... | [
"os.path.join",
"yaml.load",
"os.path.realpath",
"numpy.genfromtxt",
"os.remove"
] | [((2430, 2448), 'numpy.genfromtxt', 'genfromtxt', (['vorout'], {}), '(vorout)\n', (2440, 2448), False, 'from numpy import genfromtxt\n'), ((2712, 2728), 'os.remove', 'os.remove', (['vorin'], {}), '(vorin)\n', (2721, 2728), False, 'import os\n'), ((2733, 2750), 'os.remove', 'os.remove', (['vorout'], {}), '(vorout)\n', (... |
import os
import time
import argparse
import torch
import pickle
import copy
import numpy as np
from tqdm import tqdm
import rdkit
from rdkit.Chem import AllChem
from rdkit import Chem
from confgf import utils, dataset
import multiprocessing
from functools import partial
def generate_conformers(mol, num_confs):
... | [
"numpy.median",
"pickle.dump",
"argparse.ArgumentParser",
"rdkit.Chem.AllChem.EmbedMultipleConfs",
"pickle.load",
"numpy.array",
"confgf.dataset.GEOMDataset_PackedConf",
"functools.partial",
"multiprocessing.Pool",
"copy.deepcopy",
"torch.cat"
] | [((329, 347), 'copy.deepcopy', 'copy.deepcopy', (['mol'], {}), '(mol)\n', (342, 347), False, 'import copy\n'), ((422, 522), 'rdkit.Chem.AllChem.EmbedMultipleConfs', 'AllChem.EmbedMultipleConfs', (['mol'], {'numConfs': 'num_confs', 'maxAttempts': '(0)', 'ignoreSmoothingFailures': '(True)'}), '(mol, numConfs=num_confs, m... |
## set up logging
import logging, os
logging.basicConfig(level=os.environ.get("LOGLEVEL","INFO"))
log = logging.getLogger(__name__)
## import modules
import octvi.exceptions, octvi.array, gdal
from gdalnumeric import *
import numpy as np
def getDatasetNames(stack_path:str) -> list:
"""
Returns list of... | [
"logging.getLogger",
"numpy.maximum.reduce",
"gdal.Open",
"numpy.minimum.reduce",
"logging.debug",
"os.environ.get",
"os.path.splitext",
"os.path.basename",
"numpy.full"
] | [((107, 134), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (124, 134), False, 'import logging, os\n'), ((710, 734), 'gdal.Open', 'gdal.Open', (['stack_path', '(0)'], {}), '(stack_path, 0)\n', (719, 734), False, 'import octvi.exceptions, octvi.array, gdal\n'), ((1287, 1311), 'gdal.Open',... |
# adapted from https://github.com/JTT94/filterflow/blob/master/scripts/stochastic_volatility.py
import enum
import os
import sys
import time
from datetime import datetime
import random
sys.path.append('../')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from absl impor... | [
"tensorflow.train.Checkpoint",
"filterflow.resampling.differentiable.loss.SinkhornLoss",
"tensorflow.GradientTape",
"tensorflow.control_dependencies",
"tensorflow.reduce_mean",
"filterflow.resampling.RegularisedTransform",
"filterflow.resampling.SystematicResampler",
"sys.path.append",
"filterflow.r... | [((187, 209), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (202, 209), False, 'import sys\n'), ((16436, 16537), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""resampling_method"""', 'ResamplingMethodsEnum.REGULARIZED', '"""resampling_method"""'], {}), "('resampling_method', Resamp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 10:54:48 2019
@author: ethan
"""
import topas2numpy as t2np
import numpy as np
import matplotlib.pyplot as plt
exp_dose = np.genfromtxt('ChrisOBrien_Linac_Data.csv',delimiter=',')
field_sizes = [5,20,30,40]
for field_size in field_sizes... | [
"numpy.where",
"numpy.squeeze",
"topas2numpy.BinnedResult",
"numpy.genfromtxt",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((201, 259), 'numpy.genfromtxt', 'np.genfromtxt', (['"""ChrisOBrien_Linac_Data.csv"""'], {'delimiter': '""","""'}), "('ChrisOBrien_Linac_Data.csv', delimiter=',')\n", (214, 259), True, 'import numpy as np\n'), ((370, 393), 'numpy.arange', 'np.arange', (['(0)', '(30.5)', '(0.5)'], {}), '(0, 30.5, 0.5)\n', (379, 393), T... |
import matplotlib.pyplot as plt
#from skimage.io import imread
from keras import backend as K
import numpy as np
def resize_crop_image(image,scale,cutoff_percent):
image = cv2.resize(image,None,fx=scale, fy=scale, interpolation = cv2.INTER_AREA)
cut_off_vals = [image.shape[0]*cutoff_percent/100, image.shape[1]*cutof... | [
"keras.backend.sum",
"numpy.fliplr",
"numpy.array",
"numpy.zeros",
"keras.backend.log",
"numpy.rot90",
"keras.backend.epsilon"
] | [((883, 914), 'numpy.array', 'np.array', (['[0.32, 10, 1.3, 0.06]'], {}), '([0.32, 10, 1.3, 0.06])\n', (891, 914), True, 'import numpy as np\n'), ((1306, 1343), 'keras.backend.sum', 'K.sum', (['y_pred'], {'axis': '(-1)', 'keepdims': '(True)'}), '(y_pred, axis=-1, keepdims=True)\n', (1311, 1343), True, 'from keras impor... |
import pandas as pd
import numpy as np
import umap
import pyarrow.parquet as pq
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.manifold import TSNE
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from pyensembl... | [
"plotly.graph_objs.layout.scene.YAxis",
"pyarrow.parquet.read_table",
"pandas.read_parquet",
"pandas.DataFrame",
"sklearn.pipeline.Pipeline",
"sklearn.model_selection.train_test_split",
"sklearn.decomposition.PCA",
"pandas.read_csv",
"plotly.graph_objs.layout.scene.XAxis",
"sklearn.manifold.TSNE",... | [((424, 442), 'pyensembl.EnsemblRelease', 'EnsemblRelease', (['(96)'], {}), '(96)\n', (438, 442), False, 'from pyensembl import EnsemblRelease\n'), ((1174, 1213), 'pandas.read_parquet', 'pd.read_parquet', (['path'], {'engine': '"""pyarrow"""'}), "(path, engine='pyarrow')\n", (1189, 1213), True, 'import pandas as pd\n')... |
"""
A wrapper for generic and symmetric tensors
providing required functionality for PEPS calculations
Author: <NAME> <<EMAIL>>
Date: January 2020
"""
from numpy import float_
from cyclopeps.tools.utils import *
try:
import symtensor.sym as symlib
from symtensor.tools.la import symqr, symsvd
except:
symli... | [
"itertools.chain",
"numpy.prod",
"sys.exit",
"symtensor.sym.SYMtensor",
"symtensor.sym.zeros",
"uuid.uuid1",
"ctf.from_nparray",
"shutil.copyfile",
"copy.deepcopy",
"numpy.divide"
] | [((30175, 30198), 'itertools.chain', 'itertools.chain', (['*_axes'], {}), '(*_axes)\n', (30190, 30198), False, 'import itertools\n'), ((2336, 2366), 'numpy.prod', 'np.prod', (['ten_shape[:split_ind]'], {}), '(ten_shape[:split_ind])\n', (2343, 2366), True, 'import numpy as np\n'), ((2372, 2402), 'numpy.prod', 'np.prod',... |
import itertools
from collections import defaultdict
import numpy as np
from g2o import SE3Quat, CameraParameters
from map_processing.as_graph import matrix2measurement, se3_quat_average
from map_processing import graph
def as_graph(dct, fix_tag_vertices=False):
"""Convert a dictionary decoded from JSON into a gr... | [
"itertools.chain",
"numpy.eye",
"numpy.unique",
"numpy.hstack",
"map_processing.graph.Vertex",
"numpy.asarray",
"g2o.CameraParameters",
"numpy.array",
"map_processing.graph.Graph",
"numpy.zeros",
"collections.defaultdict",
"numpy.vstack",
"numpy.concatenate",
"map_processing.as_graph.se3_q... | [((478, 504), 'numpy.array', 'np.array', (["dct['pose_data']"], {}), "(dct['pose_data'])\n", (486, 504), True, 'import numpy as np\n'), ((673, 719), 'map_processing.as_graph.matrix2measurement', 'matrix2measurement', (['pose_matrices'], {'invert': '(True)'}), '(pose_matrices, invert=True)\n', (691, 719), False, 'from m... |
import os
import time
import pandas as pd
import numpy as np
from tqdm import tqdm
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from skmultiflow.utils import c... | [
"sklearn.metrics.f1_score",
"os.listdir",
"skmultiflow.utils.calculate_object_size",
"sklearn.metrics.balanced_accuracy_score",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",... | [((708, 737), 'pandas.read_csv', 'pd.read_csv', (['f"""{path}/{file}"""'], {}), "(f'{path}/{file}')\n", (719, 737), True, 'import pandas as pd\n'), ((1114, 1141), 'skmultiflow.utils.calculate_object_size', 'calculate_object_size', (['obj1'], {}), '(obj1)\n', (1135, 1141), False, 'from skmultiflow.utils import calculate... |
import numpy as np
import nibabel as nib
from scipy import ndimage
from utils import *
def segment_airway(params, I, I_affine, Mlung):
#####################################################
# Initialize parameters
#####################################################
Radius = params['airwayRadiusMask']
... | [
"numpy.int8",
"scipy.ndimage.iterate_structure",
"scipy.ndimage.generate_binary_structure",
"scipy.ndimage.binary_dilation",
"nibabel.Nifti1Image"
] | [((421, 460), 'scipy.ndimage.generate_binary_structure', 'ndimage.generate_binary_structure', (['(3)', '(1)'], {}), '(3, 1)\n', (454, 460), False, 'from scipy import ndimage\n'), ((477, 515), 'scipy.ndimage.iterate_structure', 'ndimage.iterate_structure', (['struct_s', '(3)'], {}), '(struct_s, 3)\n', (502, 515), False,... |
import torch
from torch.optim import Optimizer
from torch.distributions import Normal
import numpy as np
class SGLD(Optimizer):
def __init__(self, params, lr, norm_sigma=0.0, alpha=0.99, eps=1e-8, centered=False, addnoise=True, p=True):
weight_decay = 1/(norm_sigma ** 2 + eps)
if weight_de... | [
"numpy.sqrt",
"torch.enable_grad",
"torch.sqrt",
"torch.no_grad",
"torch.zeros_like"
] | [((787, 802), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (800, 802), False, 'import torch\n'), ((910, 929), 'torch.enable_grad', 'torch.enable_grad', ([], {}), '()\n', (927, 929), False, 'import torch\n'), ((1308, 1364), 'torch.zeros_like', 'torch.zeros_like', (['p'], {'memory_format': 'torch.preserve_format'}... |
import tensorflow as tf
import numpy as np
from PIL import Image
from tensorflow.core.framework import graph_pb2
from tensorflow.python.platform import gfile
from tensorflow.python.data.experimental import parallel_interleave
from tensorflow.python.data.experimental import map_and_batch
def read_graph(input_graph):
... | [
"tensorflow.transpose",
"tensorflow.compat.v1.data.make_one_shot_iterator",
"tensorflow.data.TFRecordDataset.list_files",
"tensorflow.compat.v1.FixedLenFeature",
"tensorflow.core.framework.graph_pb2.GraphDef",
"tensorflow.python.data.experimental.map_and_batch",
"numpy.asarray",
"tensorflow.python.dat... | [((465, 485), 'tensorflow.core.framework.graph_pb2.GraphDef', 'graph_pb2.GraphDef', ([], {}), '()\n', (483, 485), False, 'from tensorflow.core.framework import graph_pb2\n'), ((1100, 1144), 'tensorflow.compat.v1.VarLenFeature', 'tf.compat.v1.VarLenFeature', ([], {'dtype': 'tf.float32'}), '(dtype=tf.float32)\n', (1126, ... |
# coding:UTF-8
# 2018-10-15
# k-means
# python 机器学习算法
import numpy as np
def loadData(file_path):
'''导入数据
input: file_path(string):文件的存储位置
output: data(mat):数据
'''
f = open(file_path)
data = []
for line in f.readlines():
row = [] # 记录每一行
lines = line.strip().split("\t")
... | [
"numpy.mat",
"numpy.random.rand",
"numpy.ones",
"numpy.max",
"numpy.zeros",
"numpy.min",
"numpy.shape"
] | [((443, 455), 'numpy.mat', 'np.mat', (['data'], {}), '(data)\n', (449, 455), True, 'import numpy as np\n'), ((927, 941), 'numpy.shape', 'np.shape', (['data'], {}), '(data)\n', (935, 941), True, 'import numpy as np\n'), ((620, 634), 'numpy.shape', 'np.shape', (['data'], {}), '(data)\n', (628, 634), True, 'import numpy a... |
#!/usr/bin/env python
import rospy
import sys
import cv2
import numpy as np
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Image
from rgb_hsv import BGR_HSV
class LineFollower(object):
def __init__(self, rgb_to_track, colour_error = 10.0,colour_cal=Fa... | [
"rospy.init_node",
"cv2.imshow",
"numpy.array",
"rospy.Rate",
"cv2.__version__.split",
"cv_bridge.CvBridge",
"rospy.spin",
"rospy.Subscriber",
"cv2.waitKey",
"geometry_msgs.msg.Twist",
"cv2.circle",
"cv2.cvtColor",
"cv2.moments",
"cv2.resize",
"rospy.Publisher",
"rgb_hsv.BGR_HSV",
"r... | [((8524, 8578), 'rospy.init_node', 'rospy.init_node', (['"""line_follower_start"""'], {'anonymous': '(True)'}), "('line_follower_start', anonymous=True)\n", (8539, 8578), False, 'import rospy\n'), ((509, 518), 'rgb_hsv.BGR_HSV', 'BGR_HSV', ([], {}), '()\n', (516, 518), False, 'from rgb_hsv import BGR_HSV\n'), ((686, 71... |
import logging
import cv2
import numpy as np
import PIL
from dice_roller import roll_value
from spoilers.abstract_filter import AbstractFilter
class TextSpoiler(AbstractFilter):
"""Dilate text and replace with grey."""
def __init__(self, grey=127, dilate_k=3, **kwargs):
super(TextSpoiler, self).__i... | [
"PIL.Image.fromarray",
"logging.debug",
"numpy.array",
"cv2.morphologyEx",
"cv2.getStructuringElement",
"dice_roller.roll_value"
] | [((436, 457), 'dice_roller.roll_value', 'roll_value', (['self.grey'], {}), '(self.grey)\n', (446, 457), False, 'from dice_roller import roll_value\n'), ((477, 502), 'dice_roller.roll_value', 'roll_value', (['self.dilate_k'], {}), '(self.dilate_k)\n', (487, 502), False, 'from dice_roller import roll_value\n'), ((511, 58... |
# coding: utf-8
from keras.applications.vgg19 import VGG19
from keras.preprocessing import image
from keras.applications.vgg19 import preprocess_input
from keras.models import Model
import numpy as np
base_model = VGG19(weights='imagenet', include_top=True)
model = Model(inputs=base_model.input, outputs=base_model.get_... | [
"keras.preprocessing.image.img_to_array",
"keras.applications.vgg19.preprocess_input",
"keras.applications.vgg19.VGG19",
"numpy.expand_dims",
"keras.preprocessing.image.load_img"
] | [((214, 257), 'keras.applications.vgg19.VGG19', 'VGG19', ([], {'weights': '"""imagenet"""', 'include_top': '(True)'}), "(weights='imagenet', include_top=True)\n", (219, 257), False, 'from keras.applications.vgg19 import VGG19\n'), ((388, 436), 'keras.preprocessing.image.load_img', 'image.load_img', (['img_path'], {'tar... |
import numpy as np
from pandas import DataFrame
from tensorflow.keras.preprocessing.sequence import pad_sequences
import csv
import os
class ECGDataIterator:
def __init__(self, f, subsample=1):
self.ifd = open(f, "rb")
self._ss = subsample
self._offset = 2048
def __next__(self):
... | [
"os.path.join",
"numpy.empty",
"csv.reader",
"tensorflow.keras.preprocessing.sequence.pad_sequences"
] | [((966, 1000), 'numpy.empty', 'np.empty', (['(length, num_samples, 2)'], {}), '((length, num_samples, 2))\n', (974, 1000), True, 'import numpy as np\n'), ((1009, 1025), 'numpy.empty', 'np.empty', (['length'], {}), '(length)\n', (1017, 1025), True, 'import numpy as np\n'), ((1148, 1220), 'tensorflow.keras.preprocessing.... |
from sampi.sdes.util import draw_brownian
from sampi.sdes.solvers import euler_maruyama
import numpy as np
class StochDiffEq():
def __init__(self, drift=lambda x, t : 1, diffusion=lambda x, t : 1, true_sol=None, eqn=""):
self.drift = drift
self.diffusion = diffusion
self.true_sol = true_s... | [
"sampi.sdes.solvers.euler_maruyama",
"sampi.sdes.util.draw_brownian",
"numpy.repeat"
] | [((402, 433), 'sampi.sdes.util.draw_brownian', 'draw_brownian', (['t'], {'nsamps': 'nsamps'}), '(t, nsamps=nsamps)\n', (415, 433), False, 'from sampi.sdes.util import draw_brownian\n'), ((453, 496), 'numpy.repeat', 'np.repeat', (['t[:, np.newaxis]', 'nsamps'], {'axis': '(1)'}), '(t[:, np.newaxis], nsamps, axis=1)\n', (... |
########################################################################################################################
#WORD2VEC MODEL
########################################################################################################################
# Import libaries
from sklearn.manifold import TSNE
from rando... | [
"numpy.sqrt",
"numpy.random.rand",
"numpy.hstack",
"math.sqrt",
"numpy.array",
"matplotlib.pyplot.annotate",
"tensorflow.set_random_seed",
"tensorflow.Graph",
"tensorflow.nn.embedding_lookup",
"os.path.exists",
"collections.deque",
"tensorflow.placeholder",
"tensorflow.Session",
"sklearn.m... | [((11881, 11905), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'size'}), '(figsize=size)\n', (11891, 11905), True, 'import matplotlib.pyplot as plt\n'), ((2016, 2041), 'os.makedirs', 'os.makedirs', (['self.out_dir'], {}), '(self.out_dir)\n', (2027, 2041), False, 'import os\n'), ((2296, 2365), 'collections... |
# -*- coding: utf-8 -*-
# @Time : 2020/10/8 14:53
# @Author : Breeze
# @Email : <EMAIL>
"""
用于与接口交互
1、get到目标图片
2、将目标图片计算出像素值,从而在childIndex中映射得到"坐标",找到原图
3、将原图均分九块,目标图片也均分九块,分别计算每一块的像素值从而确定打乱了的目标图片的编号
4、将此编号返回与ai算法相结合
"""
from PK.ai9 import ai as AI
import numpy as np
import requests
import jso... | [
"json.loads",
"requests.post",
"utils.getSequence",
"json.dumps",
"base64.b64decode",
"requests.get",
"numpy.array",
"PK.ai9.ai"
] | [((479, 496), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (491, 496), False, 'import requests\n'), ((688, 705), 'requests.get', 'requests.get', (['Url'], {}), '(Url)\n', (700, 705), False, 'import requests\n'), ((1128, 1142), 'json.dumps', 'json.dumps', (['po'], {}), '(po)\n', (1138, 1142), False, 'import... |
import numpy as np
import xml.etree.ElementTree as ET
import chainer
from chainercv.utils import read_image
from os import listdir
from os.path import isfile, join
from chainercv.datasets import voc_bbox_label_names
LABEL_NAMES = ('other',
'berlinerdom',
'brandenburgertor',
... | [
"os.listdir",
"xml.etree.ElementTree.parse",
"os.path.join",
"numpy.stack",
"chainercv.utils.read_image"
] | [((2045, 2077), 'chainercv.utils.read_image', 'read_image', (['img_file'], {'color': '(True)'}), '(img_file, color=True)\n', (2055, 2077), False, 'from chainercv.utils import read_image\n'), ((1341, 1363), 'xml.etree.ElementTree.parse', 'ET.parse', (["(id_ + '.xml')"], {}), "(id_ + '.xml')\n", (1349, 1363), True, 'impo... |
import argparse
from comet_ml import Experiment
import numpy as np
import copy
import scipy.optimize
import pandas as pd
import operator
import scipy.io
import scipy
import scipy.sparse
import time
import sys
import os
import matplotlib.pyplot as plt
#Import mmort modules
sys.path.append(os.path.abspath(os.path.join(os... | [
"comet_ml.Experiment",
"torch.LongTensor",
"scipy.io.loadmat",
"numpy.log",
"numpy.array",
"scipy.optimize.lsq_linear",
"torch.cuda.is_available",
"copy.deepcopy",
"numpy.arange",
"argparse.ArgumentParser",
"numpy.vstack",
"scipy.sparse.coo_matrix",
"scipy.sparse.csr_matrix",
"torch.zeros_... | [((545, 589), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MMORT"""'}), "(description='MMORT')\n", (568, 589), False, 'import argparse\n'), ((10684, 10724), 'numpy.squeeze', 'np.squeeze', (["data['OAR_constraint_types']"], {}), "(data['OAR_constraint_types'])\n", (10694, 10724), True, ... |
#!/usr/bin/env python3
# Name: <NAME> and <NAME>
# Student ID: 2267883
# Email: <EMAIL>
# Course: PHYS220/MATH220/CPSC220 Fall 2017
# Assignment: CLASSWORK 6
import numpy as np
import matplotlib.pyplot as plt #Used to plot in python
#First Derivative code
def derivative(a,b,n):
'''derivative(a,b,n)
Creating t... | [
"numpy.eye",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((1546, 1561), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (1556, 1561), True, 'import matplotlib.pyplot as plt\n'), ((1585, 1600), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (1595, 1600), True, 'import matplotlib.pyplot as plt\n'), ((1753, 1769), 'matplotlib.py... |
import numpy as np
import matplotlib.pyplot as plt
# Generate data
n = 500
t = np.linspace(0,20.0*np.pi,n)
X = np.sin(t) # X is already between -1 and 1, scaling normally needed | [
"numpy.sin",
"numpy.linspace"
] | [((80, 111), 'numpy.linspace', 'np.linspace', (['(0)', '(20.0 * np.pi)', 'n'], {}), '(0, 20.0 * np.pi, n)\n', (91, 111), True, 'import numpy as np\n'), ((112, 121), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (118, 121), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
import os
import torchvision
from joblib import load
from settings import DIR_DATA, DIR_OUTPUT, SYNTHETIC_DIM, SYNTHETIC_SAMPLES, SYNTHETIC_NOISE_VALID, \
SYNTHETIC_DATASPLIT, MNIST_BINARIZATION_CUTOFF, PATTERN_THRESHOLD, K_PATTERN_DIV
"""
noise 'symmetric': the ... | [
"numpy.count_nonzero",
"numpy.array",
"matplotlib.pyplot.imshow",
"os.path.exists",
"sklearn.cluster.AgglomerativeClustering",
"scipy.cluster.hierarchy.linkage",
"joblib.load",
"torchvision.transforms.ToTensor",
"numpy.eye",
"scipy.spatial.distance.squareform",
"matplotlib.pyplot.savefig",
"nu... | [((11288, 11337), 'numpy.array', 'np.array', (['[1, 1, 1, 1, -1, -1, -1, -1]'], {'dtype': 'int'}), '([1, 1, 1, 1, -1, -1, -1, -1], dtype=int)\n', (11296, 11337), True, 'import numpy as np\n'), ((11365, 11410), 'numpy.array', 'np.array', (['[1, 1, 1, 1, 1, 1, 1, 1]'], {'dtype': 'int'}), '([1, 1, 1, 1, 1, 1, 1, 1], dtype... |
"""
Module with interface and default configurations for the used clustering algorithms
"""
import os
import subprocess
from warnings import warn
import numpy as np
from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, AgglomerativeClustering
from sklearn.metrics import pairwise_distances
# from excut.mis... | [
"sklearn.cluster.KMeans",
"sklearn.cluster.SpectralClustering",
"sklearn.cluster.AgglomerativeClustering",
"os.path.join",
"sklearn.metrics.pairwise_distances",
"os.path.realpath",
"warnings.warn",
"numpy.loadtxt",
"sklearn.cluster.DBSCAN"
] | [((1371, 1447), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': "clustering_params['k']", 'n_init': '(20)', 'random_state': 'self.seed'}), "(n_clusters=clustering_params['k'], n_init=20, random_state=self.seed)\n", (1377, 1447), False, 'from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, Agglomerati... |
from pyAudioAnalysis import audioBasicIO
from pyAudioAnalysis import audioFeatureExtraction
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import cross_val_score
import io
from sklearn.mixture import gaussian_mixture
my_dir = ['A','B','C','D']
my_file = ['1.wav','2.wav','3.wav','4.wav'... | [
"pyAudioAnalysis.audioBasicIO.readAudioFile",
"numpy.mat",
"pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction_modified",
"numpy.hstack",
"sklearn.mixture.gaussian_mixture.GaussianMixture",
"numpy.array",
"numpy.zeros",
"numpy.empty",
"numpy.vstack",
"numpy.full",
"numpy.random.permutati... | [((597, 620), 'numpy.zeros', 'np.zeros', ([], {'shape': '(13, 1)'}), '(shape=(13, 1))\n', (605, 620), True, 'import numpy as np\n'), ((625, 648), 'numpy.zeros', 'np.zeros', ([], {'shape': '(13, 1)'}), '(shape=(13, 1))\n', (633, 648), True, 'import numpy as np\n'), ((653, 676), 'numpy.zeros', 'np.zeros', ([], {'shape': ... |
import torch
import numpy as np
import scipy
import scipy.stats
import scipy.spatial.distance
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def mse(x, y):
res = (x - y)**2
return res.mean()
def diss(divtau, theta)... | [
"numpy.abs",
"numpy.repeat",
"numpy.where",
"numpy.min",
"numpy.max",
"torch.cuda.is_available",
"numpy.cumsum",
"torch.utils.data.DataLoader",
"torch.no_grad",
"matplotlib.pyplot.subplots",
"scipy.spatial.distance.jensenshannon"
] | [((449, 524), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'tests_batch', 'shuffle': '(False)'}), '(dataset, batch_size=tests_batch, shuffle=False)\n', (476, 524), False, 'import torch\n'), ((1326, 1401), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['data... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
#data = np.loadtxt("data.txt").reshape((2048,2048))
data = np.memmap("DenseOffset.off", dtype=np.float32, mode='r', shape=(100,100,2))
data1=data[:,:,0]
print(data1)
plt.imshow(data1, cmap=cm.coolwarm) ... | [
"matplotlib.pyplot.imshow",
"numpy.memmap",
"matplotlib.pyplot.show"
] | [((177, 254), 'numpy.memmap', 'np.memmap', (['"""DenseOffset.off"""'], {'dtype': 'np.float32', 'mode': '"""r"""', 'shape': '(100, 100, 2)'}), "('DenseOffset.off', dtype=np.float32, mode='r', shape=(100, 100, 2))\n", (186, 254), True, 'import numpy as np\n'), ((284, 319), 'matplotlib.pyplot.imshow', 'plt.imshow', (['dat... |
# coding: utf-8
import numpy as np
import cPickle
import utils
import h5py
import os
def convert_files(file_paths, vocabulary, punctuations, output_path):
inputs = []
outputs = []
punctuation = " "
for file_path in file_paths:
with open(file_path, 'r') as corpus:
for line in c... | [
"os.path.exists",
"cPickle.dump",
"utils.load_vocabulary",
"os.makedirs",
"utils.punctuation_index",
"h5py.File",
"numpy.array",
"utils.input_word_index"
] | [((2755, 2793), 'utils.load_vocabulary', 'utils.load_vocabulary', (['VOCABULARY_FILE'], {}), '(VOCABULARY_FILE)\n', (2776, 2793), False, 'import utils\n'), ((2011, 2046), 'h5py.File', 'h5py.File', (["(output_path + '.h5')", '"""w"""'], {}), "(output_path + '.h5', 'w')\n", (2020, 2046), False, 'import h5py\n'), ((2660, ... |
import pickle
import itertools
import os
import math
from sklearn.preprocessing import normalize
import re
from operator import add
import matplotlib.pyplot as plt
import numpy as np
import argparse
import pylab as pl
from utils import compute_embds_matrix
if __name__ == "__main__":
parser = argparse.ArgumentPa... | [
"argparse.ArgumentParser",
"numpy.argpartition",
"numpy.asarray",
"pickle.load",
"os.path.join",
"numpy.arange"
] | [((301, 367), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Visualize nearest neighbors"""'}), "(description='Visualize nearest neighbors')\n", (324, 367), False, 'import argparse\n'), ((1073, 1100), 'os.path.join', 'os.path.join', (['path', '"""embds"""'], {}), "(path, 'embds')\n", (10... |
import numpy as np
class MotionFeatureExtractor:
""" Functor for extracting motion features from a detection.
"""
def __init__(self, stats):
""" Constructor.
"""
## Dict containing mean and std of motion features.
self.stats = stats
def __call__(self, det, last=None... | [
"numpy.array",
"numpy.divide"
] | [((1219, 1257), 'numpy.divide', 'np.divide', (['features', "self.stats['std']"], {}), "(features, self.stats['std'])\n", (1228, 1257), True, 'import numpy as np\n'), ((601, 636), 'numpy.array', 'np.array', (['[0.0, 0.0, width, height]'], {}), '([0.0, 0.0, width, height])\n', (609, 636), True, 'import numpy as np\n'), (... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class QNetwork(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, hidden_layers=[64, 32], drop_p=0.2):
"""Initialize parameters and build model.
Params
======
... | [
"torch.manual_seed",
"torch.nn.Dropout",
"numpy.sqrt",
"torch.nn.ModuleList",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.cat"
] | [((741, 764), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (758, 764), False, 'import torch\n'), ((1048, 1087), 'torch.nn.Linear', 'nn.Linear', (['state_size', 'hidden_layers[0]'], {}), '(state_size, hidden_layers[0])\n', (1057, 1087), True, 'import torch.nn as nn\n'), ((1117, 1145), 'torch.nn.... |
import numpy as np
from py.forest import Node
class Cube():
def __init__(self, node):
assert isinstance(node, Node)
self.start = node.start
self.end = node.end
self.dim = node.dim
self.id_string = node.id_string
self.split_axis = node.split_axis
self.split_v... | [
"numpy.shape"
] | [((876, 889), 'numpy.shape', 'np.shape', (['pts'], {}), '(pts)\n', (884, 889), True, 'import numpy as np\n')] |
import numpy as np
import scipy as sp
def mutual_information(signal1, signal2, bins=40):
pdf_, _, _ = np.histogram2d(signal1, signal2, bins=bins, normed=True)
pdf_ /= np.float(pdf_.sum())
Hxy = joint_entropy(pdf_)
Hx = entropy(pdf_.sum(axis=0))
Hy = entropy(pdf_.sum(axis=1))
... | [
"numpy.abs",
"scipy.stats.stats.pearsonr",
"numpy.histogram2d",
"numpy.log2",
"numpy.arange"
] | [((112, 168), 'numpy.histogram2d', 'np.histogram2d', (['signal1', 'signal2'], {'bins': 'bins', 'normed': '(True)'}), '(signal1, signal2, bins=bins, normed=True)\n', (126, 168), True, 'import numpy as np\n'), ((426, 450), 'numpy.arange', 'np.arange', (['pdf_.shape[0]'], {}), '(pdf_.shape[0])\n', (435, 450), True, 'impor... |
# -*- coding: utf-8 -*-
"""
Tests.
"""
import unittest
from numpy import linspace, sin, pi, amax
from bruges.attribute import energy
class EnergyTest(unittest.TestCase):
def setUp(self):
"""
Makes a simple sin wave with 1 amplitude to use as test data.
"""
self.n_samples = 1001
... | [
"numpy.linspace",
"numpy.sin",
"bruges.attribute.energy",
"numpy.amax",
"unittest.TextTestRunner",
"unittest.TestLoader"
] | [((400, 439), 'numpy.linspace', 'linspace', (['(0.0)', 'duration', 'self.n_samples'], {}), '(0.0, duration, self.n_samples)\n', (408, 439), False, 'from numpy import linspace, sin, pi, amax\n'), ((461, 471), 'numpy.sin', 'sin', (['(w * t)'], {}), '(w * t)\n', (464, 471), False, 'from numpy import linspace, sin, pi, ama... |
import time
import numpy as np
import cupy as cp
import acc_image_utils as acc
ori_size = 96
new_size = 32
#n1 = np.zeros((ori_size,ori_size,ori_size,ori_size),dtype=np.float32)
n1 = np.random.rand(ori_size,ori_size,ori_size,ori_size)
loop_tester = 4
t1 = time.time()
for ii in range(loop_tester):
#real in 0,1 Q in... | [
"cupy.transpose",
"cupy.asnumpy",
"numpy.random.rand",
"cupy.fft.ifft2",
"acc_image_utils.cupy_jit_resizer4D",
"acc_image_utils.gpu_rot4D",
"acc_image_utils.cupy_pad",
"time.time",
"cupy.fft.fft2"
] | [((184, 238), 'numpy.random.rand', 'np.random.rand', (['ori_size', 'ori_size', 'ori_size', 'ori_size'], {}), '(ori_size, ori_size, ori_size, ori_size)\n', (198, 238), True, 'import numpy as np\n'), ((257, 268), 'time.time', 'time.time', ([], {}), '()\n', (266, 268), False, 'import time\n'), ((891, 902), 'time.time', 't... |
"""
QA model code.
"""
from collections import namedtuple
import concurrent.futures
import glob
import json
import os
import random
import sys
import featurize
import ops
import numpy as np
import tensorflow as tf
from framework import Model
from constants import EMBEDDING_DIM, PAD
ModelConfig = namedtuple("QAModel",... | [
"tensorflow.equal",
"tensorflow.shape",
"tensorflow.get_variable",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.reduce_sum",
"tensorflow.contrib.layers.variance_scaling_initializer",
"ops.scalar_summaries",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"numpy.array",
"tensor... | [((299, 575), 'collections.namedtuple', 'namedtuple', (['"""QAModel"""', "['vocab_size', 'question_layers', 'document_layers', 'pick_end_word_layers',\n 'layer_size', 'beam_size', 'embedding_dropout_prob',\n 'hidden_dropout_prob', 'learning_rate', 'anneal_every', 'anneal_rate',\n 'clip_norm', 'l2_scale', 'weig... |
import os
import astropy.time
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pickle
import re
import pandas as pd
import radvel
from astroquery.simbad import Simbad
import wget, zipfile, shutil
from . import config
norm_mean = lambda x: x/np.nanmean(x)
def pickle_dump(filename,obj):
... | [
"wget.download",
"zipfile.ZipFile",
"matplotlib.colorbar.ColorbarBase",
"numpy.nanmean",
"numpy.nanmin",
"matplotlib.colorbar.make_axes",
"numpy.mod",
"pandas.to_datetime",
"os.remove",
"numpy.delete",
"numpy.linspace",
"os.path.isdir",
"numpy.nanmax",
"pandas.DataFrame",
"numpy.abs",
... | [((613, 639), 'pickle.dump', 'pickle.dump', (['obj', 'savefile'], {}), '(obj, savefile)\n', (624, 639), False, 'import pickle\n'), ((1053, 1093), 'pickle.load', 'pickle.load', (['openfile'], {'encoding': '"""latin1"""'}), "(openfile, encoding='latin1')\n", (1064, 1093), False, 'import pickle\n'), ((3657, 3675), 'matplo... |
"""
This script generates anchor boxes for a custom dataset. It will generate:
+ an anchor text file (depending on number of anchors, default = 5)
Example usage:
-------------
python anchor_boxes.py
--path /path/to/dataset.hdf5
--output_dir ./
--num_anchors 5
"""
import os
import csv
import numpy as np
im... | [
"argparse.ArgumentParser",
"io.BytesIO",
"h5py.File",
"box.Box",
"numpy.array",
"os.path.isdir",
"os.mkdir",
"numpy.expand_dims",
"numpy.concatenate",
"box.box_iou"
] | [((460, 518), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Generate custom anchor boxes"""'}), "(description='Generate custom anchor boxes')\n", (474, 518), False, 'from argparse import ArgumentParser\n'), ((1102, 1133), 'numpy.array', 'np.array', (['image'], {'dtype': 'np.float'}), '(image, dt... |
# -*- coding: utf-8 -*-
"""
@author: "<NAME> and <NAME>"
@license: "MIT"
@version: "1.0"
@email: "<EMAIL> or <EMAIL> "
@created: "26 October 2020"
Description: greedy heuristic algorithm that optimizes data lake jobs
"""
import zmq
import time
import numpy as np
import random as rand
import string
from multiprocessi... | [
"multiprocessing.Process",
"time.sleep",
"numpy.sum",
"time.time",
"zmq.Context",
"random.randint"
] | [((631, 644), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (642, 644), False, 'import zmq\n'), ((2509, 2522), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2519, 2522), False, 'import time\n'), ((1602, 1621), 'random.randint', 'rand.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (1614, 1621), True, 'import ran... |
import numpy as np
#import scipy as sp
import pylab as p
import matplotlib
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import pandas as pd
import hydropy as hp
from matplotlib.colors import Normalize
from matplotlib.transforms import offset_copy
from matplotlib.ticker import MaxNLocator
from... | [
"mpl_toolkits.axes_grid.make_axes_locatable",
"numpy.atleast_2d",
"pylab.rc",
"numpy.where",
"numpy.max",
"matplotlib.ticker.MaxNLocator",
"numpy.vstack",
"numpy.min",
"matplotlib.pyplot.subplots",
"numpy.arange",
"model_evaluation_mc.ObjectiveFunctions"
] | [((520, 555), 'pylab.rc', 'p.rc', (['"""mathtext"""'], {'default': '"""regular"""'}), "('mathtext', default='regular')\n", (524, 555), True, 'import pylab as p\n'), ((995, 1033), 'model_evaluation_mc.ObjectiveFunctions', 'ObjectiveFunctions', (['measured', 'modelled'], {}), '(measured, modelled)\n', (1013, 1033), False... |
import os
import numpy as np
import pylab as pl
dat = np.loadtxt(os.environ['DESIMODEL'] + '/focalplane/platescale.txt')
wdat = dat[:,0]
## Assume MPS == SPS
pscale = dat[:,6]
## Find radius where DESI ratio to centre is 10%.
index = np.where(np.abs(pscale / pscale[0] - 1.1).min() == np.abs(pscale / ps... | [
"numpy.abs",
"pylab.plot",
"pylab.savefig",
"pylab.xlabel",
"numpy.savetxt",
"numpy.loadtxt",
"pylab.ylabel"
] | [((61, 127), 'numpy.loadtxt', 'np.loadtxt', (["(os.environ['DESIMODEL'] + '/focalplane/platescale.txt')"], {}), "(os.environ['DESIMODEL'] + '/focalplane/platescale.txt')\n", (71, 127), True, 'import numpy as np\n'), ((613, 786), 'numpy.savetxt', 'np.savetxt', (["(os.environ['AUX'] + '/platescale-pfs.txt')", 'output'], ... |
import pygame
from pygame.locals import *
import time
import random
import numpy as np
import player
import food
class Agaria:
def __init__(self, rendering = True):
self.agents: [player.Player] = []
self.foods: [food.Food] = []
self.player_lastID = 0
self.rendering = rendering
... | [
"pygame.draw.circle",
"pygame.quit",
"food.Food",
"player.Player",
"pygame.event.get",
"pygame.init",
"pygame.display.set_mode",
"pygame.display.flip",
"numpy.zeros",
"pygame.display.set_caption",
"time.time"
] | [((342, 353), 'time.time', 'time.time', ([], {}), '()\n', (351, 353), False, 'import time\n'), ((487, 517), 'numpy.zeros', 'np.zeros', (['(128)'], {'dtype': 'np.uint32'}), '(128, dtype=np.uint32)\n', (495, 517), True, 'import numpy as np\n'), ((1193, 1211), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (120... |
import cv2
import numpy as np
from matplotlib.pyplot import plt
from .colors import label_color
from .visualization import draw_box, draw_caption, draw_boxes, draw_detections, draw_annotations
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
fr... | [
"keras_retinanet.utils.image.resize_image",
"keras_retinanet.utils.image.read_image_bgr",
"keras_retinanet.utils.visualization.draw_caption",
"keras_retinanet.utils.colors.label_color",
"cv2.cvtColor",
"matplotlib.pyplot.plt.imshow",
"numpy.expand_dims",
"matplotlib.pyplot.plt.show",
"matplotlib.pyp... | [((588, 607), 'keras_retinanet.utils.image.resize_image', 'resize_image', (['image'], {}), '(image)\n', (600, 607), False, 'from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image\n'), ((1310, 1334), 'keras_retinanet.utils.image.read_image_bgr', 'read_image_bgr', (['img_path'], {}), '(img... |
from robot.trajectory import quintic_trajectory_planning
from tools.visualize import plot_joint_trajectory
import numpy as np
if __name__ == "__main__":
q0 = np.array([-2, -1, 0, 1, 2, 3])
qd0 = np.array([0, 0, 0, 0, 0, 0])
qdd0 = np.array([0, 0, 0, 0, 0, 0])
qf = np.array([4, -3, -2, 0, 4, -2])
qd... | [
"numpy.array",
"tools.visualize.plot_joint_trajectory",
"robot.trajectory.quintic_trajectory_planning"
] | [((163, 193), 'numpy.array', 'np.array', (['[-2, -1, 0, 1, 2, 3]'], {}), '([-2, -1, 0, 1, 2, 3])\n', (171, 193), True, 'import numpy as np\n'), ((204, 232), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0, 0])\n', (212, 232), True, 'import numpy as np\n'), ((244, 272), 'numpy.array', 'np.array... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
psyclab/muscle/brown.py
<NAME> 2019
"""
import numpy as np
class BrownMuscleModel:
"""
Muscle model based off the work of Cheng, Brown et al.
[1] <NAME>., <NAME>., & <NAME>. (2000).
Virtual muscle: a computational approach to understanding the effec... | [
"numpy.exp",
"numpy.power",
"numpy.max"
] | [((1520, 1581), 'numpy.max', 'np.max', (['(muscle_length / self.resting_length, self.limits[0])'], {}), '((muscle_length / self.resting_length, self.limits[0]))\n', (1526, 1581), True, 'import numpy as np\n'), ((4033, 4061), 'numpy.exp', 'np.exp', (['(13.8 - 18.7 * length)'], {}), '(13.8 - 18.7 * length)\n', (4039, 406... |
import numpy as np
import os
from matplotlib import ticker, gridspec, style
from matplotlib import pyplot as plt
import pandas
import xlsxwriter
from scipy.interpolate import CubicSpline
from scipy.signal import butter, freqz, savgol_filter
import time
import pytta
from tmm import _h5utils as h5utils
from tmm.database.... | [
"IPython.display.display",
"numpy.sqrt",
"pandas.read_csv",
"matplotlib.style.use",
"matplotlib.ticker.ScalarFormatter",
"numpy.imag",
"tmm._h5utils.save_class_to_hdf5",
"numpy.mean",
"os.path.exists",
"scipy.interpolate.CubicSpline",
"numpy.asarray",
"tmm._h5utils.load_class_from_hdf5",
"pa... | [((386, 417), 'matplotlib.style.use', 'style.use', (['"""seaborn-colorblind"""'], {}), "('seaborn-colorblind')\n", (395, 417), False, 'from matplotlib import ticker, gridspec, style\n'), ((365, 376), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (374, 376), False, 'import os\n'), ((1448, 1489), 'numpy.zeros_like', 'np.ze... |
# -*- coding: utf-8 -*-
import torch
from torch import nn
import numpy as np
import torch.nn.functional as F
class TextRNNAttentionConfig:
sequence_length = 100
vocab_size = 5000 # 词表大小
embedding_dim = 300 # 词向量维度
hidden_size = 128
hidden_size2 = 64
num_layers = 2
dropout... | [
"torch.nn.Tanh",
"torch.nn.LSTM",
"torch.tensor",
"torch.sum",
"torch.matmul",
"torch.nn.functional.relu",
"torch.nn.Linear",
"numpy.load",
"torch.zeros",
"torch.nn.Embedding",
"torch.nn.Embedding.from_pretrained"
] | [((1071, 1205), 'torch.nn.LSTM', 'nn.LSTM', (['config.embedding_dim', 'config.hidden_size', 'config.num_layers'], {'bidirectional': '(True)', 'batch_first': '(True)', 'dropout': 'config.dropout'}), '(config.embedding_dim, config.hidden_size, config.num_layers,\n bidirectional=True, batch_first=True, dropout=config.d... |
import numpy as np
def getOffAxisCorr(confFile,fldr):
#print confFile
c=np.loadtxt(confFile)
ruler = np.sqrt(c[:,0]**2+c[:,1]**2)
# print ruler, fldr, (ruler >= fldr).argmax(), (ruler >= fldr).argmin()
step=ruler[1]-ruler[0]
p2=(ruler >= fldr)
# print "FINE",p2, p2.shape
if (np.count_no... | [
"numpy.count_nonzero",
"numpy.dot",
"numpy.loadtxt",
"numpy.sqrt"
] | [((81, 101), 'numpy.loadtxt', 'np.loadtxt', (['confFile'], {}), '(confFile)\n', (91, 101), True, 'import numpy as np\n'), ((115, 151), 'numpy.sqrt', 'np.sqrt', (['(c[:, 0] ** 2 + c[:, 1] ** 2)'], {}), '(c[:, 0] ** 2 + c[:, 1] ** 2)\n', (122, 151), True, 'import numpy as np\n'), ((309, 329), 'numpy.count_nonzero', 'np.c... |
import os
import pickle
import h5py
import numpy as np
import tensorflow as tf
from scipy.io import loadmat
from lymph.vgg19 import net
def gen_labels(parent_folder: str):
# 生成文件路径
path_1 = os.path.join(parent_folder, "allLabels1.mat")
path_2 = os.path.join(parent_folder, "allLabels2.mat")
out_path ... | [
"tensorflow.placeholder",
"scipy.io.loadmat",
"os.path.join",
"numpy.argmax",
"tensorflow.Session",
"h5py.File",
"numpy.array",
"numpy.stack",
"lymph.vgg19.net",
"numpy.concatenate"
] | [((202, 247), 'os.path.join', 'os.path.join', (['parent_folder', '"""allLabels1.mat"""'], {}), "(parent_folder, 'allLabels1.mat')\n", (214, 247), False, 'import os\n'), ((261, 306), 'os.path.join', 'os.path.join', (['parent_folder', '"""allLabels2.mat"""'], {}), "(parent_folder, 'allLabels2.mat')\n", (273, 306), False,... |
#Linear Regression and plotting using libraries
from __future__ import division
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
df= pd.read_csv('ex1data1.txt', header=None, names=['x','y'])
print(df)
x = np.array(df.x)
y = np.array(df.y)
theta = np.zeros((2,1))
def scatterplot(x,y,... | [
"pandas.read_csv",
"numpy.polyfit",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.array",
"numpy.zeros",
"numpy.polyval",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.show"
] | [((169, 227), 'pandas.read_csv', 'pd.read_csv', (['"""ex1data1.txt"""'], {'header': 'None', 'names': "['x', 'y']"}), "('ex1data1.txt', header=None, names=['x', 'y'])\n", (180, 227), True, 'import pandas as pd\n'), ((241, 255), 'numpy.array', 'np.array', (['df.x'], {}), '(df.x)\n', (249, 255), True, 'import numpy as np\... |
import os, sys
import argparse
import numpy as np
from ipfml import utils
from keras.models import load_model
from sklearn.metrics import roc_auc_score, accuracy_score
'''
Display progress information as progress bar
'''
def write_progress(progress):
barWidth = 180
output_str = "["
pos = barWidth * pro... | [
"os.path.exists",
"os.listdir",
"keras.models.load_model",
"argparse.ArgumentParser",
"os.path.join",
"sklearn.metrics.roc_auc_score",
"numpy.array",
"numpy.expand_dims",
"ipfml.utils.normalize_arr_with_range",
"sklearn.metrics.accuracy_score",
"sys.stdout.write"
] | [((637, 663), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (653, 663), False, 'import os, sys\n'), ((1500, 1570), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compute KPI from ensemble model"""'}), "(description='Compute KPI from ensemble model')\n",... |
__author__ = 'roehrig'
import numpy as np
import pandas as pd
from osgeo import ogr
# from warsa.gis.features.feature import Layers
# from warsa.gis.features.interpolation.idw import idw
def idw_time_series_interpolation(point_lrs_in, field_name_in, df_ts_in, point_lrs_out, field_name_out):
# Extract point coor... | [
"numpy.insert",
"osgeo.ogr.CreateGeometryFromWkb",
"numpy.sum",
"numpy.isnan",
"pandas.DataFrame"
] | [((2202, 2236), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'df_ts_in.index'}), '(index=df_ts_in.index)\n', (2214, 2236), True, 'import pandas as pd\n'), ((2648, 2674), 'numpy.sum', 'np.sum', (['(row[:-1] * weights)'], {}), '(row[:-1] * weights)\n', (2654, 2674), True, 'import numpy as np\n'), ((2597, 2624), 'nu... |
import numpy as np
from pyesg.configuration.validation_configuration import ValidationAnalysis
from pyesg.constants.outputs import DISCOUNT_FACTOR, BOND_INDEX
from pyesg.constants.validation_analyses import DISCOUNTEd_BOND_INDEX
from pyesg.constants.validation_result_types import MARTINGALE
from pyesg.simulation.utils... | [
"numpy.full",
"pyesg.validation.utils.get_confidence_level",
"pyesg.validation.utils.do_sample_mean_and_confidence_interval_calculations"
] | [((969, 1008), 'pyesg.validation.utils.get_confidence_level', 'get_confidence_level', (['analysis_settings'], {}), '(analysis_settings)\n', (989, 1008), False, 'from pyesg.validation.utils import get_confidence_level, do_sample_mean_and_confidence_interval_calculations\n'), ((1753, 1953), 'pyesg.validation.utils.do_sam... |
from __future__ import division
import os
import sys
import cv2
import argparse
import glob
import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import draw, transform
from scipy.optimize import minimize
from PIL import Image
import objs
import utils
#fp is in cam-ceil normal, h... | [
"numpy.uint8",
"numpy.clip",
"numpy.array",
"cv2.approxPolyDP",
"matplotlib.pyplot.imshow",
"numpy.mean",
"argparse.ArgumentParser",
"cv2.threshold",
"cv2.arcLength",
"cv2.line",
"cv2.contourArea",
"numpy.concatenate",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show",
"skimage.draw.pol... | [((792, 804), 'objs.Scene', 'objs.Scene', ([], {}), '()\n', (802, 804), False, 'import objs\n'), ((1258, 1276), 'numpy.zeros', 'np.zeros', (['gt.shape'], {}), '(gt.shape)\n', (1266, 1276), True, 'import numpy as np\n'), ((1283, 1301), 'numpy.zeros', 'np.zeros', (['gt.shape'], {}), '(gt.shape)\n', (1291, 1301), True, 'i... |
import numpy as np
from multilayernetwork import MultiLayerNetWork
from util import load_csv_np
from config import *
def one_shot_prediction(file_name) -> np.ndarray:
"""
this load network and given a one shot predict to data
:param file_name: read from file name
:return one shot encoded in numpy arr... | [
"multilayernetwork.MultiLayerNetWork.load_net_work",
"util.load_csv_np",
"numpy.set_printoptions"
] | [((335, 372), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (354, 372), True, 'import numpy as np\n'), ((384, 411), 'util.load_csv_np', 'load_csv_np', ([], {'path': 'file_name'}), '(path=file_name)\n', (395, 411), False, 'from util import load_csv_np\n'), ((424,... |
#!/usr/bin/env python3
'''
This script either runs inference and visualizes results. Or runs evaluations on the test set.
The following will just run inference and show GT (Green) and predictions (Red).
./infer.py infer
Running the following will visualize results:
infer.py --debug test
Visualization legend:
Blue -... | [
"icecream.ic",
"cv2.imshow",
"numpy.array",
"copy.deepcopy",
"helper.get_centroids",
"bee_dataloader.BeePointDataset",
"helper.calculate_stats",
"argparse.ArgumentParser",
"torch.unsqueeze",
"cv2.addWeighted",
"helper.normalize_uint8",
"model.ResNetUNet",
"pickle.load",
"cv2.cvtColor",
"... | [((789, 823), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'linewidth': '(240)'}), '(linewidth=240)\n', (808, 823), True, 'import numpy as np\n'), ((966, 987), 'model.ResNetUNet', 'ResNetUNet', (['num_class'], {}), '(num_class)\n', (976, 987), False, 'from model import ResNetUNet\n'), ((998, 1018), 'torch.dev... |
import os
import json
import pickle
import numpy as np
import torch
from sklearn.metrics import average_precision_score
import random
def save_pkl(pkl_data, save_path):
with open(save_path, 'wb') as f:
pickle.dump(pkl_data, f)
def load_pkl(load_path):
with open(load_path, 'rb') as f:
pkl_data ... | [
"torch.manual_seed",
"numpy.mean",
"os.path.exists",
"torch.cuda.seed",
"pickle.dump",
"os.makedirs",
"numpy.ones",
"sklearn.metrics.average_precision_score",
"pickle.load",
"random.seed",
"numpy.random.seed",
"torch.save",
"json.load",
"json.dump"
] | [((629, 662), 'torch.save', 'torch.save', (['state_dict', 'save_path'], {}), '(state_dict, save_path)\n', (639, 662), False, 'import torch\n'), ((786, 816), 'torch.manual_seed', 'torch.manual_seed', (['seed_number'], {}), '(seed_number)\n', (803, 816), False, 'import torch\n'), ((821, 848), 'numpy.random.seed', 'np.ran... |
import networkx as nx
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sumy.utils import get_stop_words
import re
import math
import warnings
warnings.simplefilter("ignore", UserWarning)
class... | [
"sklearn.metrics.pairwise.cosine_similarity",
"numpy.asarray",
"networkx.Graph",
"math.log",
"sklearn.feature_extraction.text.TfidfVectorizer",
"numpy.concatenate",
"sumy.utils.get_stop_words",
"warnings.simplefilter",
"re.findall",
"networkx.pagerank"
] | [((268, 312), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'UserWarning'], {}), "('ignore', UserWarning)\n", (289, 312), False, 'import warnings\n'), ((4282, 4310), 'numpy.asarray', 'np.asarray', (['surface_features'], {}), '(surface_features)\n', (4292, 4310), True, 'import numpy as np\n'), ((83... |
"""Handles input args for training models."""
import numpy
from gewittergefahr.gg_utils import error_checking
from generalexam.ge_io import processed_narr_io
TIME_FORMAT = '%Y%m%d%H'
INPUT_MODEL_FILE_ARG_NAME = 'input_model_file_name'
PREDICTOR_NAMES_ARG_NAME = 'narr_predictor_names'
PRESSURE_LEVEL_ARG_NAME = 'pres... | [
"gewittergefahr.gg_utils.error_checking.assert_is_boolean",
"numpy.array"
] | [((5756, 5786), 'numpy.array', 'numpy.array', (['[0.5, 0.25, 0.25]'], {}), '([0.5, 0.25, 0.25])\n', (5767, 5786), False, 'import numpy\n'), ((7327, 7380), 'gewittergefahr.gg_utils.error_checking.assert_is_boolean', 'error_checking.assert_is_boolean', (['use_downsized_files'], {}), '(use_downsized_files)\n', (7359, 7380... |
import librosa #for audio processing
import IPython.display as ipd
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile #for audio processing
import warnings
warnings.filterwarnings("ignore")
import math, random
import torch
import torchaudio
from torchaudio import transforms
from IPython.d... | [
"numpy.hanning",
"matplotlib.pyplot.ylabel",
"torchaudio.load",
"librosa.feature.mfcc",
"librosa.resample",
"soundfile.write",
"librosa.display.waveplot",
"logging.info",
"numpy.arange",
"librosa.load",
"wave.open",
"matplotlib.pyplot.xlabel",
"numpy.fft.rfft",
"IPython.display.Audio",
"... | [((187, 220), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (210, 220), False, 'import warnings\n'), ((581, 732), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""../logs/audio.log"""', 'filemode': '"""w"""', 'format': '"""%(asctime)s - %(name)s - %(lev... |
#!/usr/bin/env python2.7
# Author : <NAME> (<EMAIL>)
#
# Description : Filter data
#
# Acknowledgement : TomRoelandts.com
#
# Last updated
# 2018.12.15 : version 0.10;
import numpy as np
import h5py
import pywt
import matplotlib.pyplot as plt
import stats as st
def nextpow2(i):
n = 1
... | [
"numpy.convolve",
"numpy.sqrt",
"numpy.blackman",
"numpy.log",
"pywt.waverec2",
"numpy.arange",
"numpy.mean",
"pywt.wavedec2",
"numpy.fft.fft",
"numpy.dot",
"stats.ns_entropy",
"numpy.abs",
"numpy.ceil",
"numpy.ones",
"numpy.std",
"numpy.linalg.svd",
"numpy.fft.ifft",
"matplotlib.p... | [((660, 670), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (667, 670), True, 'import numpy as np\n'), ((1032, 1062), 'numpy.convolve', 'np.convolve', (['x', 'self.filt_coef'], {}), '(x, self.filt_coef)\n', (1043, 1062), True, 'import numpy as np\n'), ((1381, 1393), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (... |
#!/usr/bin/env python
"""
Speed-Gauge for matplotlib
See http://nbviewer.ipython.org/gist/nicolasfauchereau/794df533eca594565ab3
Adapted to be more typical ratio display.
"""
from matplotlib import cm
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.patches import Circle, Wedge, Rectangle
def... | [
"numpy.radians",
"matplotlib.cm.get_cmap",
"matplotlib.patches.Rectangle",
"matplotlib.patches.Wedge",
"numpy.linspace",
"matplotlib.pyplot.tight_layout",
"matplotlib.patches.Circle",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((1254, 1276), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['colors', 'N'], {}), '(colors, N)\n', (1265, 1276), False, 'from matplotlib import cm\n'), ((1358, 1372), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1370, 1372), True, 'from matplotlib import pyplot as plt\n'), ((2847, 2865), 'matplotlib.p... |
#-*- coding:utf-8 -*-
import datetime
import cv2
import numpy as np
import h5py
import sys
import shutil
cmd_line = sys.argv[1].split(",")
video_dir = cmd_line[0] #実行時の引数をビデオファイルの引数とする。
print(video_dir)
print(cmd_line)
todaydetail = datetime.datetime.today()
todaydetail = str(todaydetail.year) + str(todaydetail.month... | [
"numpy.reshape",
"shutil.move",
"h5py.File",
"numpy.array",
"cv2.destroyAllWindows",
"numpy.concatenate",
"cv2.cvtColor",
"datetime.datetime.today",
"cv2.waitKey"
] | [((235, 260), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (258, 260), False, 'import datetime\n'), ((2207, 2235), 'h5py.File', 'h5py.File', (['output_file2', '"""w"""'], {}), "(output_file2, 'w')\n", (2216, 2235), False, 'import h5py\n'), ((2457, 2492), 'shutil.move', 'shutil.move', (['outpu... |
import numpy as np
import pickle
import datetime
import matplotlib.pyplot as plt
with open("../data/factor_out_2020.pickle",'rb') as f:
factor_out = pickle.load(f)
with open("../data/factor_in_2020.pickle",'rb') as f:
factor_in = pickle.load(f)
with open("../data/dicOfMatrix.pickle",'rb') as f:
mat... | [
"pickle.load",
"numpy.sum",
"numpy.array",
"datetime.date",
"datetime.timedelta"
] | [((158, 172), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (169, 172), False, 'import pickle\n'), ((245, 259), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (256, 259), False, 'import pickle\n'), ((328, 342), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (339, 342), False, 'import pickle\n'), ((512, ... |
import numpy as np
import tensorflow as tf
from util import xavier_init
class SparseAutoencoder(object):
def __init__(self, num_input, num_hidden, transfer_function=tf.nn.softplus, optimizer=tf.train.AdamOptimizer(),
scale=0.1):
self.num_input = num_input
self.num_hidden = num_hidd... | [
"numpy.random.normal",
"numpy.repeat",
"tensorflow.random_normal",
"util.xavier_init",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.global_variables_initializer",
"tensorflow.matmul",
"tensorflow.subtract",
"tensorflow.train.AdamOptimizer",
"tensorflow.log",
"tensorflow.zeros"
] | [((196, 220), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (218, 220), True, 'import tensorflow as tf\n'), ((386, 412), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (400, 412), True, 'import tensorflow as tf\n'), ((689, 739), 'tensorflow.placeholde... |
# encoding='utf-8'
'''
/**
* This is the solution of No.43 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/multiply-strings
* <p>
* The description of problem is as follow:
* ===================================================================================... | [
"numpy.zeros"
] | [((1745, 1766), 'numpy.zeros', 'np.zeros', (['(len2 + len1)'], {}), '(len2 + len1)\n', (1753, 1766), True, 'import numpy as np\n')] |
from os.path import join, isdir
import glob
from subprocess import call
import numpy as np
from rastervision.common.utils import _makedirs
from rastervision.common.settings import VALIDATION
from rastervision.semseg.tasks.utils import (
make_prediction_img, plot_prediction, predict_x)
from rastervision.semseg.mo... | [
"rastervision.semseg.tasks.utils.predict_x",
"os.path.join",
"rastervision.common.utils._makedirs",
"numpy.squeeze",
"os.path.isdir",
"subprocess.call",
"rastervision.semseg.models.factory.SemsegModelFactory",
"rastervision.semseg.tasks.utils.plot_prediction"
] | [((457, 477), 'rastervision.semseg.models.factory.SemsegModelFactory', 'SemsegModelFactory', ([], {}), '()\n', (475, 477), False, 'from rastervision.semseg.models.factory import SemsegModelFactory\n'), ((496, 520), 'os.path.join', 'join', (['run_path', '"""videos"""'], {}), "(run_path, 'videos')\n", (500, 520), False, ... |
import numpy as np
import cv2 as cv
import argparse
from PIL import Image, ImageEnhance, ImageDraw
import matplotlib.pyplot as plt
import os
def ROI(frame):
#enhancer = ImageEnhance.Contrast(frame)
#img = enhancer.enhance(0.7)
face_classifier = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
... | [
"cv2.rectangle",
"os.path.exists",
"PIL.Image.fromarray",
"PIL.Image.open",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"os.mkdir",
"cv2.CascadeClassifier",
"cv2.waitKey",
"os.walk"
] | [((259, 318), 'cv2.CascadeClassifier', 'cv.CascadeClassifier', (['"""haarcascade_frontalface_default.xml"""'], {}), "('haarcascade_frontalface_default.xml')\n", (279, 318), True, 'import cv2 as cv\n'), ((585, 603), 'cv2.VideoCapture', 'cv.VideoCapture', (['(0)'], {}), '(0)\n', (600, 603), True, 'import cv2 as cv\n'), (... |
"""
implement the qmix algorithm with tensorflow, also thanks to the pymarl repo.
"""
from functools import partial
from time import time
import numpy as np
import tensorflow as tf
from absl import logging
from smac.env import MultiAgentEnv, StarCraft2Env
from xt.algorithm.qmix.episode_buffer_np import EpisodeBatchNP... | [
"numpy.prod",
"tensorflow.tile",
"tensorflow.equal",
"numpy.random.rand",
"tensorflow.transpose",
"tensorflow.boolean_mask",
"tensorflow.nn.elu",
"tensorflow.reduce_sum",
"tensorflow.multiply",
"numpy.array",
"tensorflow.ones_like",
"tensorflow.Graph",
"numpy.mean",
"xt.algorithm.qmix.qmix... | [((1239, 1348), 'xt.algorithm.qmix.qmix_alg.DecayThenFlatSchedule', 'DecayThenFlatSchedule', (['args.epsilon_start', 'args.epsilon_finish', 'args.epsilon_anneal_time'], {'decay': '"""linear"""'}), "(args.epsilon_start, args.epsilon_finish, args.\n epsilon_anneal_time, decay='linear')\n", (1260, 1348), False, 'from x... |
# Copyright 2016, FBPIC contributors
# Authors: <NAME>, <NAME>
# License: 3-Clause-BSD-LBNL
"""
This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC)
It contains a helper function that parses the data file atomic_data.txt
"""
import re, os
import numpy as np
from scipy.constants import e
cached_ioniza... | [
"os.path.dirname",
"re.findall",
"numpy.zeros"
] | [((2774, 2810), 're.findall', 're.findall', (['regex_command', 'text_data'], {}), '(regex_command, text_data)\n', (2784, 2810), False, 'import re, os\n'), ((3091, 3114), 'numpy.zeros', 'np.zeros', (['atomic_number'], {}), '(atomic_number)\n', (3099, 3114), True, 'import numpy as np\n'), ((1889, 1914), 'os.path.dirname'... |
import numpy as np
from sklearn import cluster
from sklearn import metrics
from sklearn.naive_bayes import GaussianNB
from .Common import DWConfig, DWutils
class DWImageClustering:
def __init__(self, bands, bands_keys, invalid_mask, config: DWConfig):
self.config = config
self.data_as_columns =... | [
"sklearn.cluster.KMeans",
"sklearn.metrics.calinski_harabasz_score",
"sklearn.cluster.AgglomerativeClustering",
"numpy.mean",
"skimage.filters.threshold_otsu",
"numpy.where",
"skimage.morphology.square",
"numpy.count_nonzero",
"numpy.zeros",
"skimage.feature.canny",
"numpy.concatenate",
"numpy... | [((11939, 11951), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (11949, 11951), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((16089, 16140), 'skimage.filters.threshold_otsu', 'threshold_otsu', (['img[dilated_edges & (img != -9999)]'], {}), '(img[dilated_edges & (img != -9999)])\n', (1610... |
"""@file audio_feat_processor.py
contains the AudioFeatProcessor class"""
import os
import subprocess
import StringIO
import scipy.io.wavfile as wav
import numpy as np
import processor
import gzip
from nabu.processing.feature_computers import feature_computer_factory
class AudioFeatProcessor(processor.Processor):
... | [
"StringIO.StringIO",
"os.path.exists",
"numpy.mean",
"nabu.processing.feature_computers.feature_computer_factory.factory",
"subprocess.Popen",
"os.path.join",
"numpy.square",
"numpy.sum",
"numpy.zeros",
"scipy.io.wavfile.read",
"numpy.std",
"numpy.shape",
"numpy.load",
"numpy.save"
] | [((6983, 7006), 'os.path.exists', 'os.path.exists', (['wavfile'], {}), '(wavfile)\n', (6997, 7006), False, 'import os\n'), ((5240, 5259), 'numpy.sum', 'np.sum', (['features', '(0)'], {}), '(features, 0)\n', (5246, 5259), True, 'import numpy as np\n'), ((7045, 7062), 'scipy.io.wavfile.read', 'wav.read', (['wavfile'], {}... |
#importing libraries
import numpy
import skimage
import skimage.io
import skimage.color
from matplotlib import pyplot, pyplot as plt
from pathlib import Path
import numpy as np
#declaring global array
index_0_255_array = np.array([x for x in range(256)])
#generic function to plot histograms of any number of images... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.figure",
"numpy.zeros",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((578, 606), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(25, 25)'}), '(figsize=(25, 25))\n', (588, 606), True, 'from matplotlib import pyplot, pyplot as plt\n'), ((1449, 1459), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1457, 1459), True, 'from matplotlib import pyplot, pyplot as plt\n')... |
#
#
# Copyright (c) 2013, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, ... | [
"hrl_lib.util.save_pickle",
"numpy.sqrt",
"numpy.random.rand",
"hrl_lib.util.load_pickle",
"rospy.init_node",
"rospy.ServiceProxy",
"threading.RLock",
"time.sleep",
"numpy.max",
"roslib.load_manifest",
"numpy.array",
"scipy.spatial.Delaunay",
"numpy.min",
"darci_client.DarciClient",
"ros... | [((1738, 1777), 'roslib.load_manifest', 'roslib.load_manifest', (['"""hrl_dynamic_mpc"""'], {}), "('hrl_dynamic_mpc')\n", (1758, 1777), False, 'import roslib\n'), ((15983, 16024), 'hrl_lib.util.load_pickle', 'ut.load_pickle', (['"""./joint_and_ee_data.pkl"""'], {}), "('./joint_and_ee_data.pkl')\n", (15997, 16024), True... |
import numpy as np
def softmax_func(x):
"""
Numerically stable softmax function. For more details
about numerically calculations please refer:
http://www.deeplearningbook.org/slides/04_numerical.pdf
:param x:
:return:
"""
stable_values = x - np.max(x, axis=1, keepdims=True)
return ... | [
"numpy.exp",
"numpy.pad",
"numpy.zeros",
"numpy.max"
] | [((805, 837), 'numpy.max', 'np.max', (['x'], {'axis': '(1)', 'keepdims': '(True)'}), '(x, axis=1, keepdims=True)\n', (811, 837), True, 'import numpy as np\n'), ((1446, 1565), 'numpy.pad', 'np.pad', (['image', '((0, 0), (0, 0), (padding_height, padding_height), (padding_width,\n padding_width))'], {'mode': '"""consta... |
import numpy as np
import matplotlib.pyplot as plt
from os import path
from src.sampler import BTCsampler
from src.emulator import Market
def main():
"""
This function computes the wavelet transform over non-overlapping time windows across the bitcoin dataset to identify
coefficients that can be shrinke... | [
"numpy.mean",
"os.path.join",
"src.emulator.Market",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.std"
] | [((527, 563), 'os.path.join', 'path.join', (['""".."""', '"""data"""', 'db_type', 'db'], {}), "('..', 'data', db_type, db)\n", (536, 563), False, 'from os import path\n'), ((878, 963), 'src.emulator.Market', 'Market', (['sampler', 'window_state', '(0)'], {'time_difference': '(True)', 'wavelet_channels': 'wavChan'}), '(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.