code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 10 11:44:58 2021
@author: zongsing.huang
"""
import numpy as np
def t7():
COST = np.array([6, 6, 4, 4, 4, 3, 3])
M = 3 # 機台數
N = 7 # 工單數
F_ideal = 10
return COST, M, N, F_ideal
def t9():
COST = np.array([9, 7, 12, 15, 8, 10, 11, 13, 7])
... | [
"numpy.zeros",
"numpy.array"
] | [((135, 166), 'numpy.array', 'np.array', (['[6, 6, 4, 4, 4, 3, 3]'], {}), '([6, 6, 4, 4, 4, 3, 3])\n', (143, 166), True, 'import numpy as np\n'), ((274, 316), 'numpy.array', 'np.array', (['[9, 7, 12, 15, 8, 10, 11, 13, 7]'], {}), '([9, 7, 12, 15, 8, 10, 11, 13, 7])\n', (282, 316), True, 'import numpy as np\n'), ((425, ... |
import os
import torch
import numpy as np
import pandas as pd
from stric.datasets.base_dataset import BaseDataset
class YahooDataset(BaseDataset):
# https://yahooresearch.tumblr.com/post/114590420346/a-benchmark-dataset-for-time-series-anomaly
# Need license from Yahoo to be downloaded
name = 'yahoo'
... | [
"numpy.median",
"torch.tensor",
"os.path.join",
"numpy.concatenate"
] | [((3644, 3664), 'numpy.concatenate', 'np.concatenate', (['X', '(1)'], {}), '(X, 1)\n', (3658, 3664), True, 'import numpy as np\n'), ((3681, 3701), 'numpy.concatenate', 'np.concatenate', (['Y', '(1)'], {}), '(Y, 1)\n', (3695, 3701), True, 'import numpy as np\n'), ((3790, 3810), 'numpy.concatenate', 'np.concatenate', (['... |
import ffmpeg
import numpy as np
def extract_frames(video_path, fps, size=None, crop=None, start=None, duration=None):
if start is not None:
cmd = ffmpeg.input(video_path, ss=start, t=duration)
else:
cmd = ffmpeg.input(video_path)
if size is None:
info = [s for s in ffmpeg.probe(v... | [
"numpy.frombuffer",
"ffmpeg.probe",
"ffmpeg.input"
] | [((161, 207), 'ffmpeg.input', 'ffmpeg.input', (['video_path'], {'ss': 'start', 't': 'duration'}), '(video_path, ss=start, t=duration)\n', (173, 207), False, 'import ffmpeg\n'), ((232, 256), 'ffmpeg.input', 'ffmpeg.input', (['video_path'], {}), '(video_path)\n', (244, 256), False, 'import ffmpeg\n'), ((895, 923), 'numpy... |
import tensorflow as tf
# import PIL
from PIL import Image
import numpy as np
import cv2
from PIL import Image
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def read_image(image_name, feature_row, feature_col):
image_bytes = tf.read_file(image_name)
image_tensor = tf.image.decod... | [
"tensorflow.image.resize_images",
"numpy.save",
"cv2.waitKey",
"tensorflow.ConfigProto",
"tensorflow.image.decode_jpeg",
"tensorflow.read_file",
"cv2.imshow",
"tensorflow.image.convert_image_dtype"
] | [((262, 286), 'tensorflow.read_file', 'tf.read_file', (['image_name'], {}), '(image_name)\n', (274, 286), True, 'import tensorflow as tf\n'), ((306, 351), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['image_bytes'], {'channels': '(3)'}), '(image_bytes, channels=3)\n', (326, 351), True, 'import tensorflow a... |
from typing import Callable, Dict, Optional, Sequence, Union
import numpy as np
import pytorch_lightning as pl
import torch
from pandas import DataFrame
from torch import LongTensor, Tensor
from torch.utils.data import DataLoader, Dataset
class TabularDataset(Dataset):
def __init__(
self,
data: D... | [
"torch.Tensor",
"numpy.zeros",
"torch.utils.data.DataLoader",
"torch.LongTensor"
] | [((8011, 8232), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset', '(batch_size if batch_size is not None else self.batch_size)'], {'shuffle': "(True if split == 'train' else False)", 'num_workers': 'self.num_workers', 'sampler': "(self.train_sampler if split == 'train' else None)"}), "(dataset, batch_size if ba... |
import numpy as np
from datetime import datetime
import calendar
import re
import time
from moderatebot import PriceTable
from moderatebot import PRecordFactory
import matplotlib.pyplot as plt
instrument = 'EUR_USD'
granularity = 'M1'
pt = PriceTable(instrument, granularity)
cf = PRecordFactory(pt.granularity)
ask = ... | [
"matplotlib.pyplot.show",
"moderatebot.PriceTable",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"moderatebot.PRecordFactory",
"numpy.array",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.grid"
] | [((242, 277), 'moderatebot.PriceTable', 'PriceTable', (['instrument', 'granularity'], {}), '(instrument, granularity)\n', (252, 277), False, 'from moderatebot import PriceTable\n'), ((283, 313), 'moderatebot.PRecordFactory', 'PRecordFactory', (['pt.granularity'], {}), '(pt.granularity)\n', (297, 313), False, 'from mode... |
import sys
sys.path.extend(['../'])
from config import Config_pku
import os
import glob
import numpy as np
from PIL import Image, ImageChops
import pickle
def read_txt_file(file_path):
lines = []
with open(file_path) as f:
lines.append(f.read().splitlines() )
f.close()
lines = np.hstack(lines... | [
"numpy.load",
"pickle.dump",
"numpy.save",
"sys.path.extend",
"numpy.hstack",
"PIL.Image.open",
"numpy.sort",
"numpy.array",
"glob.glob",
"numpy.random.permutation",
"config.Config_pku",
"numpy.unique"
] | [((11, 35), 'sys.path.extend', 'sys.path.extend', (["['../']"], {}), "(['../'])\n", (26, 35), False, 'import sys\n'), ((305, 321), 'numpy.hstack', 'np.hstack', (['lines'], {}), '(lines)\n', (314, 321), True, 'import numpy as np\n'), ((579, 608), 'numpy.load', 'np.load', (['"""./pku/train_id.npy"""'], {}), "('./pku/trai... |
import streamlit as st
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
def app():
dataset = ['Iris', 'Breast Cancer',... | [
"sklearn.datasets.load_iris",
"streamlit.selectbox",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"matplotlib.pyplot.figure",
"numpy.unique",
"pandas.DataFrame",
"sklearn.datasets.load_wine",
"matplotlib.pyplot.colorbar",
"pandas.concat",
"sklearn.datasets.load_b... | [((351, 390), 'streamlit.selectbox', 'st.selectbox', (['"""Select Dataset"""', 'dataset'], {}), "('Select Dataset', dataset)\n", (363, 390), True, 'import streamlit as st\n'), ((423, 486), 'streamlit.write', 'st.write', (['f"""## {algorithm} Algorithm on {dataset_name} Dataset"""'], {}), "(f'## {algorithm} Algorithm on... |
import numpy as np
def compute_air_density(temperature=20, pressure=101325, relative_humidity=0, dew_temperature=None):
"""Computes air density, following the apprach of "Revised formula for the density of moist air (CIPM-2007)" by <NAME>, <NAME>, <NAME> and <NAME>"""
if relative_humidity is None and dew_tem... | [
"numpy.power"
] | [((1234, 1252), 'numpy.power', 'np.power', (['(p / T)', '(2)'], {}), '(p / T, 2)\n', (1242, 1252), True, 'import numpy as np\n'), ((731, 759), 'numpy.power', 'np.power', (['dew_temperature', '(2)'], {}), '(dew_temperature, 2)\n', (739, 759), True, 'import numpy as np\n'), ((887, 901), 'numpy.power', 'np.power', (['t', ... |
#
# Copyright 2020- IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
#
from typing import Tuple, Optional, Dict, Union
import numpy as np
from collections import defaultdict
from abc import ABC, abstractmethod
class BaseRetailer(ABC):
def __init__(self, seed: Optional[int] = None):
if s... | [
"numpy.random.RandomState"
] | [((539, 571), 'numpy.random.RandomState', 'np.random.RandomState', (['self.seed'], {}), '(self.seed)\n', (560, 571), True, 'import numpy as np\n'), ((609, 636), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (630, 636), True, 'import numpy as np\n')] |
from __future__ import annotations
import math
import random
import statistics
import numpy as np
import tensorflow as tf
from .codeepneat_module_base import CoDeepNEATModuleBase
from tfne.helper_functions import round_with_step
class CoDeepNEATModuleDenseDropout(CoDeepNEATModuleBase):
"""
TFNE CoDeepNEAT ... | [
"random.randint",
"tfne.helper_functions.round_with_step",
"tensorflow.keras.layers.Dense",
"random.uniform",
"math.ceil",
"tensorflow.keras.layers.Dropout",
"random.choice",
"random.random",
"statistics.mean",
"numpy.random.normal"
] | [((3214, 3263), 'random.choice', 'random.choice', (["self.config_params['merge_method']"], {}), "(self.config_params['merge_method'])\n", (3227, 3263), False, 'import random\n'), ((3345, 3436), 'random.randint', 'random.randint', (["self.config_params['units']['min']", "self.config_params['units']['max']"], {}), "(self... |
from numpy import array, pi, sqrt, exp, zeros
T = 1.0
v0 = 0.01
kappa = 2.0 # mean rev
theta = 0.01 # long term
omega = 0.2 # vol
N = 3
def compute_f(r, omega):
return 2*sqrt(r)/omega
def compute_v(R, omega):
if R > 0:
return (R**2) * (omega**2)/4.0
else:
return 0.0
def build_volatility... | [
"numpy.zeros",
"numpy.sqrt"
] | [((394, 415), 'numpy.zeros', 'zeros', (['(N + 1, N + 1)'], {}), '((N + 1, N + 1))\n', (399, 415), False, 'from numpy import array, pi, sqrt, exp, zeros\n'), ((481, 489), 'numpy.sqrt', 'sqrt', (['dt'], {}), '(dt)\n', (485, 489), False, 'from numpy import array, pi, sqrt, exp, zeros\n'), ((498, 519), 'numpy.zeros', 'zero... |
from IPython.display import FileLinks
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def setup_individual_obs_df(obs_df):
"""
Standardizes adults and pediatrics files for clean processing in GrowthViz notebooks
"""
df = obs_df.copy()
df.rename(colum... | [
"pandas.read_csv",
"matplotlib.pyplot.bar",
"numpy.around",
"IPython.display.FileLinks",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"pandas.concat",
"pandas.to_numeric",
"numpy.repeat"
] | [((2892, 3067), 'pandas.read_csv', 'pd.read_csv', (['f"""growthviz-data/ext/{percentiles_file}"""'], {'dtype': "{'Agemos': float, 'P5': float, 'P50': float, 'P95': float, 'L': float, 'M':\n float, 'S': float, 'Sex': int}"}), "(f'growthviz-data/ext/{percentiles_file}', dtype={'Agemos':\n float, 'P5': float, 'P50':... |
import numpy as np
import torch
import torch.distributions as distributions
from scipy.stats import truncnorm
class AdaptiveBaseNet:
def __init__(self, layers, activation, device, torch_type):
self.device = device
self.torch_type = torch_type
self.layers = layers
... | [
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.square",
"torch.nn.functional.dropout",
"torch.nn.Sigmoid",
"torch.normal",
"torch.exp",
"torch.zeros",
"torch.matmul",
"torch.log",
"torch.tensor",
"numpy.sqrt"
] | [((1142, 1240), 'torch.zeros', 'torch.zeros', (['[1, self.base_dim]'], {'dtype': 'self.torch_type', 'device': 'self.device', 'requires_grad': '(True)'}), '([1, self.base_dim], dtype=self.torch_type, device=self.device,\n requires_grad=True)\n', (1153, 1240), False, 'import torch\n'), ((1266, 1379), 'torch.zeros', 't... |
'''
Python functions for creating and analyzing EEG waveforms
How to use:
Each time a new epoch is needed, call generate_data(args) to create an epoch. Then call
generate_spectra() to create fft and power spectrum. All this data is stored internally
in this script.
Call get_data(), get_fft(), or get_power_spec() to ... | [
"numpy.abs",
"numpy.random.randn",
"numpy.fft.fft",
"numpy.sin",
"numpy.arange",
"numpy.linspace"
] | [((1407, 1460), 'numpy.linspace', 'np.linspace', (['(0)', 'args.epochDuration', 'args.samplingRate'], {}), '(0, args.epochDuration, args.samplingRate)\n', (1418, 1460), True, 'import numpy as np\n'), ((6224, 6236), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (6233, 6236), True, 'import numpy as np\n'), ((6386, 6... |
"""Filtering routines."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import numpy as np
from scipy import signal
from kwiklib.utils.six.moves import range
# ---------------------------------... | [
"numpy.zeros_like",
"scipy.signal.filtfilt",
"kwiklib.utils.six.moves.range",
"scipy.signal.lfilter",
"scipy.signal.firwin",
"numpy.cov",
"scipy.signal.butter"
] | [((671, 742), 'scipy.signal.butter', 'signal.butter', (['order', '(low / (rate / 2.0), high / (rate / 2.0))', '"""pass"""'], {}), "(order, (low / (rate / 2.0), high / (rate / 2.0)), 'pass')\n", (684, 742), False, 'from scipy import signal\n'), ((1179, 1226), 'scipy.signal.firwin', 'signal.firwin', (['(n + 1)', '(1.0 / ... |
import pandas as pd
from pathlib import Path
import pickle
import numpy as np
#root_path_setup0 = Path(r"Z:\arminbahl\Behavior Setup 0\free_swimming_4fish_data\dot_motion_coherence8_2")
#root_path_setup1 = Path(r"Z:\arminbahl\Behavior Setup 1\free_swimming_4fish_data\dot_motion_coherence8_2")
root_path_setup0 = Path(... | [
"pandas.DataFrame",
"pathlib.Path",
"pickle.load",
"numpy.sign"
] | [((315, 443), 'pathlib.Path', 'Path', (['"""/n/home10/abahl/engert_lab_storage/arminbahl/Behavior Setup 0/free_swimming_4fish_data/dot_motion_coherence8_2"""'], {}), "(\n '/n/home10/abahl/engert_lab_storage/arminbahl/Behavior Setup 0/free_swimming_4fish_data/dot_motion_coherence8_2'\n )\n", (319, 443), False, 'fr... |
import pyclesperanto_prototype as cle
import numpy as np
def test_subtract_image_from_scalar():
test1 = cle.push(np.asarray([
[0, 0],
[1, 1],
[2, 2]
]))
reference = cle.push(np.asarray([
[5, 5],
[4, 4],
[3, 3]
]))
result = cle.create(test1)
cle... | [
"numpy.array_equal",
"numpy.asarray",
"pyclesperanto_prototype.pull",
"pyclesperanto_prototype.subtract_image_from_scalar",
"pyclesperanto_prototype.create"
] | [((295, 312), 'pyclesperanto_prototype.create', 'cle.create', (['test1'], {}), '(test1)\n', (305, 312), True, 'import pyclesperanto_prototype as cle\n'), ((317, 365), 'pyclesperanto_prototype.subtract_image_from_scalar', 'cle.subtract_image_from_scalar', (['test1', 'result', '(5)'], {}), '(test1, result, 5)\n', (347, 3... |
#!/usr/bin/env python
"""Creates a Torch Dataset and Dataloader objects with custom tokenizer.
Create a simple data set and loader to work with PyTorch Dataset and Dataloader class. Wanted to use these instead of
the torch.text alternatives to keep things simple. In addition, using Dataloader in combination with DDP w... | [
"numpy.sum",
"torch.utils.data.DataLoader",
"numpy.power",
"numpy.random.choice",
"collections.Counter"
] | [((11006, 11027), 'numpy.power', 'np.power', (['probs', '(0.75)'], {}), '(probs, 0.75)\n', (11014, 11027), True, 'import numpy as np\n'), ((11041, 11054), 'numpy.sum', 'np.sum', (['probs'], {}), '(probs)\n', (11047, 11054), True, 'import numpy as np\n'), ((6693, 6780), 'torch.utils.data.DataLoader', 'DataLoader', (['se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: zmq_pull.py
import tensorflow as tf
import struct
import numpy as np
import os
from tensorflow.core.framework.tensor_pb2 import TensorProto
from tensorflow.core.framework import types_pb2 as DT
# have to import like this: https://github.com/tensorflow/tensorflow/c... | [
"tensorflow.load_op_library",
"os.path.abspath",
"numpy.asarray",
"numpy.dtype",
"tensorflow.core.framework.tensor_pb2.TensorProto",
"struct.pack",
"os.path.isfile",
"tensorflow.get_default_graph",
"os.path.join"
] | [((610, 642), 'os.path.join', 'os.path.join', (['file_dir', 'basename'], {}), '(file_dir, basename)\n', (622, 642), False, 'import os\n'), ((834, 861), 'tensorflow.load_op_library', 'tf.load_op_library', (['so_file'], {}), '(so_file)\n', (852, 861), True, 'import tensorflow as tf\n'), ((2007, 2018), 'numpy.dtype', 'np.... |
import unittest
import numpy as np
import mlopt
from mlopt.sampling import uniform_sphere_sample
import pandas as pd
import cvxpy as cp
from mlopt.settings import logger
class TestFilter(unittest.TestCase):
def setUp(self):
"""Setup simple problem"""
np.random.seed(1)
# This needs to work... | [
"mlopt.sampling.uniform_sphere_sample",
"numpy.random.seed",
"mlopt.Optimizer",
"cvxpy.Parameter",
"numpy.random.randn",
"numpy.random.rand",
"cvxpy.sum",
"cvxpy.norm",
"cvxpy.Variable",
"mlopt.settings.logger.info",
"numpy.sqrt",
"cvxpy.quad_form",
"cvxpy.Minimize"
] | [((274, 291), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (288, 291), True, 'import numpy as np\n'), ((378, 399), 'numpy.random.randn', 'np.random.randn', (['n', 'p'], {}), '(n, p)\n', (393, 399), True, 'import numpy as np\n'), ((514, 540), 'cvxpy.Parameter', 'cp.Parameter', (['n'], {'name': '"""mu""... |
# coding=utf-8
# Copyright 2018 Google LLC & <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"numpy.random.uniform",
"tensorflow.random_uniform",
"tensorflow.summary.scalar",
"tensorflow.trainable_variables",
"tensorflow.get_collection",
"compare_gan.src.params.GetDefaultRange",
"tensorflow.concat",
"tensorflow.variable_scope",
"tensorflow.ones_like",
"tensorflow.stack",
"tensorflow.pla... | [((7853, 7887), 'compare_gan.src.params.GetDefaultRange', 'params.GetDefaultRange', (['range_type'], {}), '(range_type)\n', (7875, 7887), False, 'from compare_gan.src import params\n'), ((1615, 1688), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '([batch_size] + image_dims)'], {'name': '"""real_images"""... |
import pandas as pd
import numpy as np
import os
from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA
sia = SIA()
NAME_COL = [1,2]
NUMER_ORD = [3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19]
CAT_ORD = [14,27,29]
BIN_PRES = [20,21,22,23,24]
COMM = [25,26]
REL_COLS = []
REL_COLS.extend(NUMER_ORD)
REL_COLS.... | [
"os.listdir",
"os.remove",
"pandas.DataFrame.from_dict",
"nltk.sentiment.vader.SentimentIntensityAnalyzer",
"pandas.ExcelFile",
"numpy.isnan",
"pandas.read_excel",
"numpy.mean",
"pandas.isna",
"pandas.concat"
] | [((127, 132), 'nltk.sentiment.vader.SentimentIntensityAnalyzer', 'SIA', ([], {}), '()\n', (130, 132), True, 'from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA\n'), ((427, 456), 'pandas.ExcelFile', 'pd.ExcelFile', (['"""BaseData.xlsx"""'], {}), "('BaseData.xlsx')\n", (439, 456), True, 'import pandas as ... |
from SharedProcessors.const import SUB_NAMES, LINE_WIDTH, FONT_DICT_SMALL, EPOCH_NUM
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from Drawer import save_fig
from matplotlib import rc
def draw_f7(training_mean, training_std, test_mean, test_std):
def format_axis(line_width=LINE_WIDTH):
... | [
"matplotlib.rc",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.std",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"Drawer.save_fig",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.tight_layout",
"numpy.sqrt"
... | [((1822, 1848), 'matplotlib.rc', 'rc', (['"""font"""'], {'family': '"""Arial"""'}), "('font', family='Arial')\n", (1824, 1848), False, 'from matplotlib import rc\n'), ((1853, 1884), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(3.54, 2.8)'}), '(figsize=(3.54, 2.8))\n', (1863, 1884), True, 'import matplot... |
#!/usr/bin/env python
'''
CUDA-accelerated Computer Vision functions
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
from tests_common import NewOpenCVTests
class cuda_test(NewOpenCVTests):
def setUp(self):
if not cv.cuda.getCudaEnabledDeviceCoun... | [
"tests_common.NewOpenCVTests.bootstrap",
"cv2.cuda_GpuMat",
"cv2.cvtColor",
"cv2.cuda.createLaplacianFilter",
"numpy.random.random",
"cv2.cuda.cvtColor",
"cv2.Laplacian",
"cv2.cuda.getCudaEnabledDeviceCount"
] | [((1364, 1390), 'tests_common.NewOpenCVTests.bootstrap', 'NewOpenCVTests.bootstrap', ([], {}), '()\n', (1388, 1390), False, 'from tests_common import NewOpenCVTests\n'), ((521, 537), 'cv2.cuda_GpuMat', 'cv.cuda_GpuMat', ([], {}), '()\n', (535, 537), True, 'import cv2 as cv\n'), ((764, 780), 'cv2.cuda_GpuMat', 'cv.cuda_... |
import numpy as np
class RandomActor:
def __init__(self, n_actions):
self.n_actions = n_actions
def get(self, state):
return np.random.randint(self.n_actions)
| [
"numpy.random.randint"
] | [((150, 183), 'numpy.random.randint', 'np.random.randint', (['self.n_actions'], {}), '(self.n_actions)\n', (167, 183), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 30 17:02:54 2020
@author: rpear
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.neural_network import MLPClassifier
np.random.seed(1)
""" Example based on sklearn's docs """
mnist = fetch_openml('mnist_784')... | [
"numpy.random.seed",
"matplotlib.pyplot.show",
"sklearn.neural_network.MLPClassifier",
"numpy.random.permutation",
"sklearn.datasets.fetch_openml",
"matplotlib.pyplot.subplots",
"numpy.unique"
] | [((228, 245), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (242, 245), True, 'import numpy as np\n'), ((295, 320), 'sklearn.datasets.fetch_openml', 'fetch_openml', (['"""mnist_784"""'], {}), "('mnist_784')\n", (307, 320), False, 'from sklearn.datasets import fetch_openml\n'), ((498, 644), 'sklearn.neu... |
##############################################################################################################################
# Importing necessary libraries
##############################################################################################################################
import argparse
import torch
impo... | [
"torch.nn.Dropout",
"numpy.set_printoptions",
"torch.nn.ReLU",
"argparse.ArgumentParser",
"json.load",
"torch.nn.LogSoftmax",
"torch.load",
"PIL.Image.open",
"torch.exp",
"numpy.array",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.no_grad",
"torch.tensor"
] | [((795, 820), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (818, 820), False, 'import argparse\n'), ((2788, 2810), 'torch.load', 'torch.load', (['checkpoint'], {}), '(checkpoint)\n', (2798, 2810), False, 'import torch\n'), ((4157, 4179), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '... |
from __future__ import print_function
from __future__ import division
from skimage.measure import block_reduce
import matplotlib.pyplot as pl
import scipy as sp
from tqdm import trange
import numpy as np
import argparse
import cv2
import os
# argv[1] -> source directory containing cuts
# argv[2] -> destination dire... | [
"os.mkdir",
"numpy.random.seed",
"argparse.ArgumentParser",
"cv2.cvtColor",
"os.path.exists",
"cv2.imread",
"numpy.random.randint",
"os.path.splitext",
"shutil.rmtree",
"matplotlib.pyplot.imread",
"os.path.join",
"os.listdir"
] | [((453, 471), 'os.listdir', 'os.listdir', (['source'], {}), '(source)\n', (463, 471), False, 'import os\n'), ((2061, 2103), 'cv2.cvtColor', 'cv2.cvtColor', (['label_im', 'cv2.COLOR_RGB2GRAY'], {}), '(label_im, cv2.COLOR_RGB2GRAY)\n', (2073, 2103), False, 'import cv2\n'), ((2264, 2282), 'os.listdir', 'os.listdir', (['so... |
from cuteSV_Description import Generation_VCF_header
from math import log10
import numpy as np
from Bio import SeqIO
err = 0.1
prior = float(1/3)
Genotype = ["0/0", "0/1", "1/1"]
def log10sumexp(log10_probs):
# Normalization of Genotype likelihoods
m = max(log10_probs)
return m + log10(sum(pow(10.0, x-m... | [
"numpy.minimum",
"Bio.SeqIO.parse",
"math.log10",
"numpy.array",
"cuteSV_Description.Generation_VCF_header"
] | [((443, 464), 'numpy.array', 'np.array', (['log10_probs'], {}), '(log10_probs)\n', (451, 464), True, 'import numpy as np\n'), ((511, 545), 'numpy.minimum', 'np.minimum', (['(log10_probs - lse)', '(0.0)'], {}), '(log10_probs - lse, 0.0)\n', (521, 545), True, 'import numpy as np\n'), ((3473, 3531), 'cuteSV_Description.Ge... |
from adaline_gd import *
from plot_decision_regions import *
import matplotlib.pyplot as plt
import numpy as np
# ### Reading-in the Iris data
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/'
'machine-learning-databases/iris/iris.data', header=None)
df.tail()
# select setosa and versico... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.copy",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"numpy.where",
"numpy.linalg.solve",
"numpy.dot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tight_layout"
] | [((170, 279), 'pandas.read_csv', 'pd.read_csv', (['"""https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"""'], {'header': 'None'}), "(\n 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',\n header=None)\n", (181, 279), True, 'import pandas as pd\n'), ((357, 392), 'nu... |
'''
Take the .mol2 files and generate 48 images for each of them.
'''
import argparse
from bionoi import Bionoi
import os
import skimage
from skimage.io import imshow
from skimage.transform import rotate
import numpy as np
import shutil
from os import listdir
from os.path import isfile, join
from shutil im... | [
"os.makedirs",
"argparse.ArgumentParser",
"os.path.basename",
"skimage.io.imsave",
"os.path.exists",
"numpy.flipud",
"os.path.splitext",
"bionoi.Bionoi",
"skimage.transform.rotate",
"shutil.rmtree",
"os.path.join",
"os.listdir"
] | [((368, 401), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""python"""'], {}), "('python')\n", (391, 401), False, 'import argparse\n'), ((4187, 4208), 'os.path.basename', 'os.path.basename', (['mol'], {}), '(mol)\n', (4203, 4208), False, 'import os\n'), ((7604, 7632), 'os.path.exists', 'os.path.exists', ([... |
import argparse, glob, os, cv2, sys, pickle, random
import numpy as np
import tensorflow as tf
import config as cfg
from models.stgru import STGRU
from models.lrr import LRR
from models.dilation import dilation10network
from models.flownet2 import Flownet2
from models.flownet1 import Flownet1
from tensorflow.python.fra... | [
"argparse.ArgumentParser",
"tensorflow.trainable_variables",
"random.shuffle",
"models.lrr.LRR",
"pickle.load",
"numpy.random.randint",
"numpy.mean",
"cv2.calcOpticalFlowFarneback",
"os.path.join",
"models.flownet1.Flownet1",
"models.stgru.STGRU",
"cv2.cvtColor",
"cv2.copyMakeBorder",
"ten... | [((365, 413), 'tensorflow.load_op_library', 'tf.load_op_library', (['"""./misc/bilinear_warping.so"""'], {}), "('./misc/bilinear_warping.so')\n", (383, 413), True, 'import tensorflow as tf\n'), ((415, 454), 'tensorflow.python.framework.ops.RegisterGradient', 'ops.RegisterGradient', (['"""BilinearWarping"""'], {}), "('B... |
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
import math
import matplotlib as mpl
#-------------------------------------------------------------------------------
def stress_divergence_hist():
# grid
fileGrid = Dataset("grid.40962.nc","r")
nVertices = len(fileGrid.dimen... | [
"netCDF4.Dataset",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.yscale",
"matplotlib.rc",
"numpy.amin",
"matplotlib.pyplot.hist",
"math.fabs",
"math.radians",
"matplotlib.pyplot.legend",
"numpy.amax",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matp... | [((256, 285), 'netCDF4.Dataset', 'Dataset', (['"""grid.40962.nc"""', '"""r"""'], {}), "('grid.40962.nc', 'r')\n", (263, 285), False, 'from netCDF4 import Dataset\n'), ((438, 465), 'netCDF4.Dataset', 'Dataset', (['"""ic_40962.nc"""', '"""r"""'], {}), "('ic_40962.nc', 'r')\n", (445, 465), False, 'from netCDF4 import Data... |
# <NAME> <<EMAIL>>
import tensorflow as tf
import numpy as np
class trainload:
def __init__(self,bsz,scales=[256,512]):
self.names = []
# Create placeholders
for i in range(bsz):
self.names.append(tf.placeholder(tf.string))
batch = []
sizes = tf.constant(np.flo... | [
"tensorflow.reshape",
"tensorflow.image.decode_png",
"tensorflow.decode_raw",
"tensorflow.assign",
"tensorflow.concat",
"tensorflow.minimum",
"tensorflow.placeholder",
"tensorflow.to_int32",
"tensorflow.to_float",
"tensorflow.random_crop",
"tensorflow.equal",
"tensorflow.image.resize_images",
... | [((1955, 1983), 'tensorflow.minimum', 'tf.minimum', (['in_s[0]', 'in_s[1]'], {}), '(in_s[0], in_s[1])\n', (1965, 1983), True, 'import tensorflow as tf\n'), ((1999, 2031), 'tensorflow.to_int32', 'tf.to_int32', (['(size / min_s * in_s)'], {}), '(size / min_s * in_s)\n', (2010, 2031), True, 'import tensorflow as tf\n'), (... |
import numpy as np
import tensorflow as tf
from .base import SaliencyMap
class VanillaGradients(SaliencyMap):
def get_mask(self, image):
"""Constructs a Vanilla Gradient Map by computing dy/dx.
Args:
image: input image in NHWC format.
"""
mask = self.get_gradients(ima... | [
"numpy.max",
"numpy.zeros_like",
"numpy.min",
"numpy.random.normal"
] | [((656, 676), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (669, 676), True, 'import numpy as np\n'), ((725, 764), 'numpy.random.normal', 'np.random.normal', (['(0)', 'stdev', 'image.shape'], {}), '(0, stdev, image.shape)\n', (741, 764), True, 'import numpy as np\n'), ((599, 612), 'numpy.max', 'np... |
import numpy as np
import pyarrow as pa
import pytest
from meerkat.block.abstract import BlockView
from meerkat.block.arrow_block import ArrowBlock
from meerkat.block.ref import BlockRef
from meerkat.columns.arrow_column import ArrowArrayColumn
from meerkat.errors import ConsolidationError
def test_signature_hash():... | [
"pyarrow.Table.from_pydict",
"meerkat.block.arrow_block.ArrowBlock.consolidate",
"meerkat.block.abstract.BlockView",
"pytest.raises",
"numpy.arange",
"pytest.mark.parametrize",
"meerkat.block.ref.BlockRef"
] | [((821, 869), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""num_blocks"""', '[1, 2, 3]'], {}), "('num_blocks', [1, 2, 3])\n", (844, 869), False, 'import pytest\n'), ((1563, 1608), 'meerkat.block.arrow_block.ArrowBlock.consolidate', 'ArrowBlock.consolidate', ([], {'block_refs': 'block_refs'}), '(block_refs... |
from gailtf.baselines.common.mpi_running_mean_std import RunningMeanStd
import tensorflow as tf
import tensorflow.contrib.layers as layers
from gailtf.baselines.common import tf_util as U
from gailtf.common.tf_util import *
import numpy as np
import ipdb
L2_REG = 1e-4
class TrajectoryClassifier(object):
def __ini... | [
"tensorflow.contrib.rnn.GRUCell",
"tensorflow.reduce_sum",
"tensorflow.contrib.rnn.BasicRNNCell",
"argparse.ArgumentParser",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.get_collection",
"tensorflow.get_variable_scope",
"tensorflow.zeros_like",
"numpy.shape",
"tensorflow.multiply",
"g... | [((7347, 7376), 'gailtf.dataset.mujoco_traj.Mujoco_Traj_Dset', 'Mujoco_Traj_Dset', (['expert_path'], {}), '(expert_path)\n', (7363, 7376), False, 'from gailtf.dataset.mujoco_traj import Mujoco_Traj_Dset\n'), ((7387, 7403), 'gym.make', 'gym.make', (['env_id'], {}), '(env_id)\n', (7395, 7403), False, 'import gym\n'), ((7... |
import matplotlib.pyplot as plt
import random
import numpy as np
(fig, ax) = plt.subplots(1, 1)
x = []
y = []
cnts = []
data = []
for i in range(250):
x.append(i)
data.append(random.randint(0, 100))
std = np.std(data)
avg = np.average(data)
y.append(avg)
cnt = np.sum(np.where(data > (avg + std... | [
"numpy.average",
"random.randint",
"numpy.std",
"numpy.where",
"matplotlib.pyplot.subplots"
] | [((78, 96), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (90, 96), True, 'import matplotlib.pyplot as plt\n'), ((219, 231), 'numpy.std', 'np.std', (['data'], {}), '(data)\n', (225, 231), True, 'import numpy as np\n'), ((242, 258), 'numpy.average', 'np.average', (['data'], {}), '(data)... |
import numpy as np
def read_obj_file(path: str):
with open(path) as f:
vertexArray = np.zeros((1,3))
meshArray = np.zeros((1,3))
for line in f:
data = line.split() # white space
if data[0] == "v":
vertexArray = np.appe... | [
"numpy.shape",
"numpy.linalg.det",
"numpy.zeros"
] | [((110, 126), 'numpy.zeros', 'np.zeros', (['(1, 3)'], {}), '((1, 3))\n', (118, 126), True, 'import numpy as np\n'), ((147, 163), 'numpy.zeros', 'np.zeros', (['(1, 3)'], {}), '((1, 3))\n', (155, 163), True, 'import numpy as np\n'), ((1018, 1034), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (1026, 1034), T... |
#-------------------------------------------------------------------------------
# Calculate urban areas from gridded population data
# <NAME>, April 2019
# Purpose is to create high density urban clusters and urban cluster above minimum
# density and total population thresholds
#-----------------------------------... | [
"pandas.DataFrame",
"rasterio.open",
"numpy.nansum",
"shapely.geometry.Polygon",
"scipy.stats.mode",
"time.strftime",
"json.dumps",
"geopandas.GeoDataFrame",
"scipy.sparse.csgraph.connected_components",
"rasterio.features.rasterize",
"rasterio.features.shapes",
"shapely.geometry.shape"
] | [((3461, 3518), 'rasterio.features.shapes', 'features.shapes', (['urbanData'], {'transform': 'popRaster.transform'}), '(urbanData, transform=popRaster.transform)\n', (3476, 3518), False, 'from rasterio import features\n'), ((5256, 5316), 'pandas.DataFrame', 'pd.DataFrame', (['allFeatures'], {'columns': "['ID', 'Pop', '... |
from typing import Union, Optional, List, Tuple, Text, BinaryIO
import numpy as np
import math
irange = range
def make_grid(
tensor: Union[np.ndarray, List[np.ndarray]],
nrow: int = 8,
padding: int = 2,
normalize: bool = False,
range: Optional[Tuple[int, int]] = None,
sc... | [
"numpy.stack",
"numpy.ones",
"numpy.expand_dims",
"numpy.clip",
"numpy.concatenate"
] | [((1977, 2001), 'numpy.stack', 'np.stack', (['tensor'], {'axis': '(0)'}), '(tensor, axis=0)\n', (1985, 2001), True, 'import numpy as np\n'), ((2067, 2097), 'numpy.expand_dims', 'np.expand_dims', (['tensor'], {'axis': '(0)'}), '(tensor, axis=0)\n', (2081, 2097), True, 'import numpy as np\n'), ((2302, 2332), 'numpy.expan... |
from pytest import fixture, mark
import os
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import Pipeline
from agape.ml.classifier import Classifier, SVClassifier, RFClassifi... | [
"numpy.logspace",
"agape.ml.classifier.SVClassifier",
"pytest.fixture",
"sklearn.datasets.make_classification",
"sklearn.linear_model.LogisticRegression",
"pytest.mark.skipif",
"numpy.array",
"agape.ml.classifier.RFClassifier"
] | [((349, 423), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(10)', 'n_features': '(5)', 'random_state': 'random_state'}), '(n_samples=10, n_features=5, random_state=random_state)\n', (368, 423), False, 'from sklearn.datasets import make_classification\n'), ((454, 477), 'pytest.fixtu... |
""" Unit Tests for Py-ART's retrieve/vad_michelson.py module. """
from __future__ import print_function
from numpy.testing import assert_almost_equal
import pyart
def test_velocity_azimuth_display():
test_radar = pyart.io.read(pyart.testing.NEXRAD_ARCHIVE_MSG1_FILE)
velocity = 'velocity'
height = ([50.... | [
"numpy.testing.assert_almost_equal",
"pyart.retrieve.velocity_azimuth_display",
"pyart.io.read"
] | [((222, 275), 'pyart.io.read', 'pyart.io.read', (['pyart.testing.NEXRAD_ARCHIVE_MSG1_FILE'], {}), '(pyart.testing.NEXRAD_ARCHIVE_MSG1_FILE)\n', (235, 275), False, 'import pyart\n'), ((977, 1093), 'pyart.retrieve.velocity_azimuth_display', 'pyart.retrieve.velocity_azimuth_display', (['test_radar', 'velocity', 'height', ... |
import math
import os
from typing import Tuple, List
import albumentations as A
import cv2
import numpy as np
import pandas as pd
from pytorch_toolbelt.utils import fs
from pytorch_toolbelt.utils.fs import id_from_fname
from pytorch_toolbelt.utils.torch_utils import tensor_from_rgb_image
from sklearn.model_selection i... | [
"numpy.sum",
"boto3.client",
"sklearn.model_selection.train_test_split",
"torch.utils.data.WeightedRandomSampler",
"numpy.mean",
"os.path.join",
"numpy.unique",
"torch.utils.data.DataLoader",
"retinopathy.augmentations.get_test_transform",
"cv2.cvtColor",
"retinopathy.augmentations.get_train_tra... | [((5331, 5348), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (5339, 5348), True, 'import numpy as np\n'), ((7007, 7050), 'boto3.client', 'boto3.client', (['"""s3"""'], {'region_name': 'region_name'}), "('s3', region_name=region_name)\n", (7019, 7050), False, 'import boto3\n'), ((8103, 8152), 'numpy.arra... |
import sys
from multiprocessing import cpu_count
from typing import Callable, Tuple
import numpy as np
import sharedmem
from fastdist import fastdist
from ripser import ripser
from sklearn.metrics import euclidean_distances
from tqdm.auto import tqdm
sys.path.append("..")
from approx_nn import ApproxNN # noqa: E402
... | [
"sys.path.append",
"fastdist.fastdist.vector_to_matrix_distance",
"numpy.argmax",
"topological_data_analysis.ripser_utils.run_ripser_plus_plus",
"numpy.argsort",
"tqdm.auto.tqdm",
"numpy.max",
"sklearn.metrics.euclidean_distances",
"numpy.linspace",
"utils.batch_list_gen",
"sharedmem.MapReduce",... | [((253, 274), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (268, 274), False, 'import sys\n'), ((7973, 8030), 'tqdm.auto.tqdm', 'tqdm', (['data_point_indices'], {'disable': '(not progressbar_enabled)'}), '(data_point_indices, disable=not progressbar_enabled)\n', (7977, 8030), False, 'from tqdm.... |
#!/usr/bin/env python
import numpy as np
import pandas as pd
import config as cfg
import tensorflow as tf
from embedder import network_config, network_maker, network_utility, network_visualization
from embedder import preprocessor
SAVE_MODEL = True
def main():
csv_file = tf.keras.utils.get_file('titanic.csv', cfg.... | [
"embedder.network_maker.EmbeddingNetwork",
"embedder.network_visualization.make_visualizations_from_config",
"numpy.log",
"embedder.preprocessor.get_class_weights",
"pandas.read_csv",
"embedder.network_utility.get_numerical_cols",
"embedder.network_utility.get_categorial_cols",
"embedder.preprocessor.... | [((277, 332), 'tensorflow.keras.utils.get_file', 'tf.keras.utils.get_file', (['"""titanic.csv"""', 'cfg.TITANIC_URL'], {}), "('titanic.csv', cfg.TITANIC_URL)\n", (300, 332), True, 'import tensorflow as tf\n'), ((342, 363), 'pandas.read_csv', 'pd.read_csv', (['csv_file'], {}), '(csv_file)\n', (353, 363), True, 'import p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import numpy as np
def random_noise_dithering(image, palette, order=128):
"""Render the image using the random noise d... | [
"numpy.ndindex",
"numpy.zeros",
"numpy.expand_dims",
"numpy.array",
"numpy.random.normal"
] | [((747, 762), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (755, 762), True, 'import numpy as np\n'), ((775, 811), 'numpy.random.normal', 'np.random.normal', (['(0)', 'order', 'ni.shape'], {}), '(0, order, ni.shape)\n', (791, 811), True, 'import numpy as np\n'), ((1439, 1454), 'numpy.array', 'np.array', (['... |
"""Return the indices of the elements that are non-zero."""
from __future__ import annotations
from typing import Any, Tuple
import numpy
import numpoly
from ..baseclass import PolyLike
from ..dispatch import implements
@implements(numpy.nonzero)
def nonzero(x: PolyLike, **kwargs: Any) -> Tuple[numpy.ndarray, ...]:... | [
"numpy.asarray",
"numpoly.aspolynomial"
] | [((1033, 1056), 'numpoly.aspolynomial', 'numpoly.aspolynomial', (['x'], {}), '(x)\n', (1053, 1056), False, 'import numpoly\n'), ((1092, 1121), 'numpy.asarray', 'numpy.asarray', (['x.coefficients'], {}), '(x.coefficients)\n', (1105, 1121), False, 'import numpy\n')] |
'''
Returns the two nodes with the highest in-degree and out-degree, respectively,
that are also connected. The highest out-degree should be able to reach the highest in-degree.
'''
from collections import deque
import numpy as np
import sys
def int_tuple(list):
return tuple([int(item) for item in list])
if __na... | [
"numpy.argsort",
"sys.exit",
"collections.deque"
] | [((1202, 1224), 'numpy.argsort', 'np.argsort', (['in_degrees'], {}), '(in_degrees)\n', (1212, 1224), True, 'import numpy as np\n'), ((1235, 1258), 'numpy.argsort', 'np.argsort', (['out_degrees'], {}), '(out_degrees)\n', (1245, 1258), True, 'import numpy as np\n'), ((1389, 1396), 'collections.deque', 'deque', ([], {}), ... |
import torchvision.models as models
import torch
import torch.nn as nn
import utils
import torch.optim as optim
from torchvision import transforms
import dataset
import numpy as np
import cv2
from utils import Extract
import time
from argparse import ArgumentParser, ArgumentTypeError
class Model(nn.Module):
def ... | [
"torch.flatten",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"torch.nn.MaxPool2d",
"torchvision.models.densenet121",
"torch.nn.Conv2d",
"torch.load",
"torch.cat",
"time.time",
"numpy.mean",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LeakyReLU",
"torch.nn.TripletMarginLoss",
... | [((4062, 4078), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (4076, 4078), False, 'from argparse import ArgumentParser, ArgumentTypeError\n'), ((2151, 2178), 'dataset.DRDataset', 'dataset.DRDataset', ([], {'root': 'dir'}), '(root=dir)\n', (2168, 2178), False, 'import dataset\n'), ((2196, 2308), 'torch... |
import os
import numpy as np
import torch
import torch.nn as nn
from sklearn.feature_extraction.text import TfidfVectorizer
from torch.optim import Adam
from torch.utils.data import DataLoader
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def read_dataset(file_path):
"""
File_path sh... | [
"torch.from_numpy",
"torch.nn.BCELoss",
"torch.utils.data.DataLoader",
"sklearn.feature_extraction.text.TfidfVectorizer",
"os.walk",
"torch.nn.init.xavier_normal_",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.no_grad",
"os.path.join",
"numpy.concatenate",
"torch.nn.Sigmoid"
] | [((541, 568), 'os.walk', 'os.walk', (["(file_path + '/neg')"], {}), "(file_path + '/neg')\n", (548, 568), False, 'import os\n'), ((759, 786), 'os.walk', 'os.walk', (["(file_path + '/pos')"], {}), "(file_path + '/pos')\n", (766, 786), False, 'import os\n'), ((1051, 1091), 'numpy.concatenate', 'np.concatenate', (['[neg_l... |
import numpy as np
import pandas as pd
from os import path
def g(inpu):
return (1/(1+np.exp(-inpu)))
def cost(inpu, actual):
return (actual*np.log(inpu)) + ((1-actual)*(np.log(1-inpu)))
class LogisticRegressor():
def __init__(self, lr=0.05):
# store learning rate and weights
self.lr = lr
... | [
"numpy.log",
"numpy.zeros",
"numpy.ones",
"numpy.exp",
"numpy.dot"
] | [((549, 575), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m, n + 1)'}), '(shape=(m, n + 1))\n', (557, 575), True, 'import numpy as np\n'), ((845, 859), 'numpy.ones', 'np.ones', (['(n + 1)'], {}), '(n + 1)\n', (852, 859), True, 'import numpy as np\n'), ((2215, 2241), 'numpy.zeros', 'np.zeros', ([], {'shape': '(m, n + 1)... |
# -*- coding: utf-8 -*-
"""
Author: <NAME> <<EMAIL>>
License: MIT
"""
import numpy as np
__all__ = [ "QuantityError" ]
class QuantityError:
"""
Uncertainty information for a physical quantity.
Parameters
----------
uncertainty : scalar or None, default None
Uncertainty as the absol... | [
"numpy.array"
] | [((3256, 3364), 'numpy.array', 'np.array', (['[self._uncertainty, self._lower_uncertainty, self._upper_uncertainty, self.\n _confidence_level]'], {}), '([self._uncertainty, self._lower_uncertainty, self.\n _upper_uncertainty, self._confidence_level])\n', (3264, 3364), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
from keras import Sequential, optimizers
from keras.layers import Dense, Conv1D, MaxPool1D, Flatten, Dropout, LSTM, Bidirectional
from keras.models import load_model, save_model
import matplotlib.pyplot as plt
''' Load and put data into time series format
'''
raw_data = ... | [
"keras.models.load_model",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.plot",
"numpy.copy",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"numpy.asarray",
"numpy.where",
"numpy.squeeze",
"numpy.concatenate"
] | [((320, 392), 'pandas.read_csv', 'pd.read_csv', (['"""./data/preprocessed_6hr_data_lastYear_standardized_BB.csv"""'], {}), "('./data/preprocessed_6hr_data_lastYear_standardized_BB.csv')\n", (331, 392), True, 'import pandas as pd\n'), ((3039, 3057), 'numpy.squeeze', 'np.squeeze', (['Y_test'], {}), '(Y_test)\n', (3049, 3... |
import bezier
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
from color_gradient import ColorGradient
class Vine:
""" Vine class which uses bezier curves to draw itself on an image
"""
def __init__(
self,
start_pos: tuple[float, float],
length: floa... | [
"PIL.ImageFilter.GaussianBlur",
"PIL.Image.new",
"numpy.arctan2",
"numpy.copy",
"numpy.clip",
"color_gradient.ColorGradient",
"numpy.apply_along_axis",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.linalg.norm",
"numpy.cos",
"PIL.ImageDraw.Draw"
] | [((4779, 4812), 'PIL.Image.new', 'Image.new', (['"""RGB"""', 'size', '(0, 0, 0)'], {}), "('RGB', size, (0, 0, 0))\n", (4788, 4812), False, 'from PIL import Image, ImageDraw, ImageFilter\n'), ((735, 799), 'numpy.array', 'np.array', (['[[0.0, 1.5, 1.5, 0.6, 0.5], [0.0, 0.0, 0.9, 1.0, 0.6]]'], {}), '([[0.0, 1.5, 1.5, 0.6,... |
import os
import sys
import bokeh.plotting as bkp
import numpy as np
from bokeh.io import export_svgs
import cairosvg
# make it so we can import models/etc from parent folder
sys.path.insert(1, os.path.join(sys.path[0], '../common'))
from plotting import *
plot_reverse_kl = True
trials = [1]
nms = [('GIGAOE', 'GIGA'... | [
"numpy.load",
"bokeh.plotting.figure",
"numpy.concatenate",
"numpy.ones",
"bokeh.plotting.show",
"numpy.linalg.norm",
"os.path.join",
"bokeh.io.export_svgs"
] | [((434, 587), 'bokeh.plotting.figure', 'bkp.figure', ([], {'y_axis_type': '"""log"""', 'plot_width': '(1000)', 'plot_height': '(1000)', 'x_axis_label': '"""iteration"""', 'y_axis_label': "('f' if plot_reverse_kl else 'Forward KL')"}), "(y_axis_type='log', plot_width=1000, plot_height=1000,\n x_axis_label='iteration'... |
import numpy as np
import pandas as pd
lt = 'f:/lt/'
region = pd.read_csv(lt + 'region.csv',sep='\t', index_col=0)
# 排除内蒙古和西藏
# prvs = ['北京', '天津', '河北', '山东', '辽宁', '江苏', '上海', '浙江', '福建', '广东', '海南', '吉林',
# '黑龙江', '山西', '河南', '安徽', '江西', '湖北', '湖南', '广西', '重庆', '四川', '贵州', '云南',
# '陕西', '甘肃', '青海', '... | [
"pandas.DataFrame",
"pandas.read_csv",
"numpy.std",
"pandas.Series.rank",
"numpy.array"
] | [((64, 117), 'pandas.read_csv', 'pd.read_csv', (["(lt + 'region.csv')"], {'sep': '"""\t"""', 'index_col': '(0)'}), "(lt + 'region.csv', sep='\\t', index_col=0)\n", (75, 117), True, 'import pandas as pd\n'), ((2114, 2126), 'numpy.array', 'np.array', (['ll'], {}), '(ll)\n', (2122, 2126), True, 'import numpy as np\n'), ((... |
import sys
from typing import Dict, List, Literal, Type, Union
from torch._C import TensorType
sys.path.append(".")
sys.path.append("../../")
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
from yacs.config import CfgNode
from lib.datasets.dataset_catalog import DatasetCatalog
from lib.d... | [
"sys.path.append",
"lib.datasets.samplers.IterationBasedBatchSampler",
"torch.utils.data.sampler.BatchSampler",
"torch.utils.data.DataLoader",
"numpy.random.get_state",
"torch.utils.data.sampler.SequentialSampler",
"lib.datasets.samplers.ImageSizeBatchSampler",
"yacs.config.CfgNode",
"lib.datasets.t... | [((96, 116), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (111, 116), False, 'import sys\n'), ((117, 142), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (132, 142), False, 'import sys\n'), ((1825, 1857), 'lib.datasets.dataset_catalog.DatasetCatalog.get', 'DatasetCa... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from pyoneer.rl.wrappers.process_impl import Process
class Batch(object):
"""
Wraps multiple `gym.Env` into a batch of environments to support
vectorization. Uses an external p... | [
"numpy.stack",
"pyoneer.rl.wrappers.process_impl.Process",
"numpy.zeros"
] | [((2614, 2638), 'numpy.stack', 'np.stack', (['states'], {'axis': '(0)'}), '(states, axis=0)\n', (2622, 2638), True, 'import numpy as np\n'), ((2715, 2800), 'numpy.zeros', 'np.zeros', ([], {'shape': 'self.observation_space.shape', 'dtype': 'self.observation_space.dtype'}), '(shape=self.observation_space.shape, dtype=sel... |
from __future__ import annotations
from typeguard import typechecked
from typing import Union
import numpy as np
@typechecked
class ImagePoint:
"""
Represents a point in image coordinates aka. pixel coordinates.
"""
def __init__(self, x: Union[int, float], y: Union[int, float]) -> None:
"""
... | [
"numpy.append",
"numpy.rint",
"numpy.mean",
"numpy.array"
] | [((1205, 1249), 'numpy.mean', 'np.mean', (['(self._point, other._point)'], {'axis': '(0)'}), '((self._point, other._point), axis=0)\n', (1212, 1249), True, 'import numpy as np\n'), ((1872, 1897), 'numpy.append', 'np.append', (['self._point', 'z'], {}), '(self._point, z)\n', (1881, 1897), True, 'import numpy as np\n'), ... |
import numpy as np
from copy import deepcopy
from scipy.stats import norm
from scipy.optimize import fminbound
# EVOLUTIONARY OPERATORS
def sbx_crossover(p1, p2, sbxdi):
D = p1.shape[0]
cf = np.empty([D])
u = np.random.rand(D)
cf[u <= 0.5] = np.power((2 * u[u <= 0.5]), (1 / (sbxdi + 1)))
cf[u > 0.5]... | [
"numpy.random.uniform",
"copy.deepcopy",
"numpy.sum",
"numpy.copy",
"numpy.argmax",
"numpy.random.randn",
"numpy.empty",
"numpy.power",
"numpy.floor",
"numpy.ones",
"numpy.clip",
"scipy.stats.norm.pdf",
"numpy.argsort",
"numpy.where",
"numpy.random.rand",
"numpy.eye",
"numpy.concaten... | [((196, 209), 'numpy.empty', 'np.empty', (['[D]'], {}), '([D])\n', (204, 209), True, 'import numpy as np\n'), ((216, 233), 'numpy.random.rand', 'np.random.rand', (['D'], {}), '(D)\n', (230, 233), True, 'import numpy as np\n'), ((260, 302), 'numpy.power', 'np.power', (['(2 * u[u <= 0.5])', '(1 / (sbxdi + 1))'], {}), '(2... |
#!/usr/bin/env python
"""
Utilities for Fling
"""
# common modules
import numpy as np
import matplotlib.pyplot as plt
# extra modules needed
from pynga.utils import *
def FaultGeom(IDs, Dims, Mech, HypoLoc, ProjDict, VisualDict=None):
"""
from Fling source files to get the fault geometry
"""
Scenario... | [
"numpy.meshgrid",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.arange",
"numpy.cos"
] | [((791, 818), 'numpy.arange', 'np.arange', (['(0)', '(Fw + dfw)', 'dfw'], {}), '(0, Fw + dfw, dfw)\n', (800, 818), True, 'import numpy as np\n'), ((966, 985), 'numpy.meshgrid', 'np.meshgrid', (['fx', 'fy'], {}), '(fx, fy)\n', (977, 985), True, 'import numpy as np\n'), ((1208, 1228), 'numpy.meshgrid', 'np.meshgrid', (['... |
__author__ = 'Orthocenter'
import cv2
import numpy as np
import Utility.constants as constants
import methods
from layer_plot_method import Layer_Plot_Method
from Utility.color import Color
class Opaque(Layer_Plot_Method):
def __init__(self, params, layer_config):
Layer_Plot_Method.__init__(self, params, ... | [
"cv2.Canny",
"layer_plot_method.Layer_Plot_Method.__init__",
"Utility.color.Color",
"numpy.zeros",
"methods.get_plot_class",
"cv2.drawContours",
"cv2.findContours"
] | [((279, 333), 'layer_plot_method.Layer_Plot_Method.__init__', 'Layer_Plot_Method.__init__', (['self', 'params', 'layer_config'], {}), '(self, params, layer_config)\n', (305, 333), False, 'from layer_plot_method import Layer_Plot_Method\n'), ((404, 431), 'cv2.Canny', 'cv2.Canny', (['black_bg', '(0)', '(100)'], {}), '(bl... |
import numpy as np
import tensorflow as tf
import os
import scipy.io as sio
import matplotlib.pyplot as plt
print("--> Loading parameters...")
global par
par = {
# Setup parameters
'save_dir' : './savedir/',
'analyze_model' : True,
# Network shape
'n_recurrent' :... | [
"numpy.random.uniform",
"scipy.io.loadmat",
"numpy.float32",
"numpy.zeros",
"numpy.ones",
"numpy.mean",
"numpy.random.permutation",
"numpy.nanmean"
] | [((1762, 1804), 'scipy.io.loadmat', 'sio.loadmat', (["(data_dir + 'spike_trains.mat')"], {}), "(data_dir + 'spike_trains.mat')\n", (1773, 1804), True, 'import scipy.io as sio\n'), ((3449, 3500), 'numpy.zeros', 'np.zeros', (["(par['n_recurrent'], 1)"], {'dtype': 'np.float32'}), "((par['n_recurrent'], 1), dtype=np.float3... |
#!/usr/bin/env python
# coding:utf-8
import numpy as np
import rospy
from common import functions
class RobotKeeper(object):
def __init__(self, kick):
# type: (robot_kick.RobotKick) -> None
self.robot_id = kick.pid.robot_id
self.ctrld_robot = kick.pid.ctrld_robot
self.friend = ki... | [
"numpy.sqrt",
"rospy.Time.now",
"numpy.ravel"
] | [((715, 731), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (729, 731), False, 'import rospy\n'), ((19366, 19382), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (19380, 19382), False, 'import rospy\n'), ((16366, 16380), 'numpy.ravel', 'np.ravel', (['shel'], {}), '(shel)\n', (16374, 16380), True, 'import... |
import networkx as nx
import argparse
import numpy as np
from measures import F1
import sys
sys.setrecursionlimit(5500000)
def dfs_visit_recursively(g,node,nodes_color,edges_to_be_removed):
nodes_color[node] = 1
nodes_order = list(g.successors_iter(node))
nodes_order = np.random.permutation(nodes_order)
for chi... | [
"argparse.ArgumentParser",
"file_io.write_pairs_to_file",
"measures.report_performance",
"numpy.random.permutation",
"networkx.DiGraph",
"sys.setrecursionlimit"
] | [((94, 124), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(5500000)'], {}), '(5500000)\n', (115, 124), False, 'import sys\n'), ((277, 311), 'numpy.random.permutation', 'np.random.permutation', (['nodes_order'], {}), '(nodes_order)\n', (298, 311), True, 'import numpy as np\n'), ((908, 942), 'numpy.random.permuta... |
import random as rnd
import matplotlib.pyplot as plt
import numpy as np
import math as mth
class Cards:
def __init__(self, number_of_cards):
self.number_of_cards = number_of_cards
self.deck_order = self.generate_cards()
self.shuffle_deck()
self.card_index = 0
def generate_card... | [
"matplotlib.pyplot.show",
"random.randint",
"random.shuffle",
"numpy.zeros",
"matplotlib.pyplot.axis",
"math.log",
"matplotlib.pyplot.subplots"
] | [((426, 454), 'random.shuffle', 'rnd.shuffle', (['self.deck_order'], {}), '(self.deck_order)\n', (437, 454), True, 'import random as rnd\n'), ((1868, 1886), 'numpy.zeros', 'np.zeros', (['(11, 11)'], {}), '((11, 11))\n', (1876, 1886), True, 'import numpy as np\n'), ((2113, 2134), 'random.randint', 'rnd.randint', (['(1)'... |
"""Numerical utilities
These numerical utilities include the Clock
time-keeping class and the base solution vector
classes for both hydro and mhd.
"""
import time
from tqdm import tqdm
import numpy as np
class Clock:
"""Timing utility for simulations
This clock timer keeps track of the simulation run time... | [
"tqdm.tqdm",
"numpy.minimum",
"numpy.maximum",
"numpy.abs",
"numpy.roll",
"time.process_time",
"numpy.ix_",
"numpy.zeros",
"numpy.arange",
"numpy.array",
"numpy.sqrt"
] | [((985, 1017), 'tqdm.tqdm', 'tqdm', ([], {'total': '(self.end_time + 0.01)'}), '(total=self.end_time + 0.01)\n', (989, 1017), False, 'from tqdm import tqdm\n'), ((1049, 1068), 'time.process_time', 'time.process_time', ([], {}), '()\n', (1066, 1068), False, 'import time\n'), ((1799, 1818), 'time.process_time', 'time.pro... |
from __future__ import division
import wx
import os
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
from matplotlib import ticker as mticker
from matplotlib import transforms as mtransforms
import numpy as n
from time import sleep, time
import threading
from collec... | [
"wx.Menu",
"wx.CheckBox",
"numpy.sin",
"matplotlib.backends.backend_wxagg.FigureCanvasWxAgg",
"collections.deque",
"threading.Thread.__init__",
"numpy.random.randn",
"matplotlib.figure.Figure",
"wx.MenuBar",
"wx.Panel.__init__",
"numpy.save",
"wx.BoxSizer",
"wx.SpinCtrlDouble",
"wx.StaticB... | [((1066, 1092), 'wx.lib.newevent.NewEvent', 'wx.lib.newevent.NewEvent', ([], {}), '()\n', (1090, 1092), False, 'import wx\n'), ((1150, 1176), 'wx.lib.newevent.NewEvent', 'wx.lib.newevent.NewEvent', ([], {}), '()\n', (1174, 1176), False, 'import wx\n'), ((8049, 8062), 'wx.App', 'wx.App', (['(False)'], {}), '(False)\n', ... |
import numpy as np
import matplotlib as mpl
# For headless environments
mpl.use('Agg') # NOQA
import matplotlib.pyplot as plt
from rastervision.common.utils import (
expand_dims, compute_ndvi, plot_img_row, download_dataset)
from rastervision.common.data.generators import Batch, FileGenerator
ISPRS = 'isprs'
cl... | [
"matplotlib.pyplot.savefig",
"numpy.argmax",
"matplotlib.pyplot.close",
"numpy.zeros",
"numpy.bitwise_not",
"numpy.expand_dims",
"matplotlib.pyplot.figure",
"matplotlib.use",
"rastervision.common.utils.download_dataset",
"rastervision.common.utils.plot_img_row",
"numpy.squeeze",
"matplotlib.gr... | [((72, 86), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (79, 86), True, 'import matplotlib as mpl\n'), ((2866, 2886), 'numpy.bitwise_not', 'np.bitwise_not', (['mask'], {}), '(mask)\n', (2880, 2886), True, 'import numpy as np\n'), ((2902, 2930), 'numpy.expand_dims', 'np.expand_dims', (['mask'], {'axis... |
import numpy as np
import rowan as rn
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
from mpl_toolkits import mplot3d
import matplotlib.animation as animation
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.gridspec import SubplotSpec, GridSpec
from uavDy import uav
def crea... | [
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.radians",
"numpy.meshgrid",
"numpy.zeros_like",
"matplotlib.animation.FuncAnimation",
"rowan.to_matrix",
"matplotlib.pyplot.figure",
"numpy.linalg.norm",
"numpy.sin",
"numpy.linspace",
"matplotlib.pyplot.GridSpec",
"numpy.cos",
"numpy.array"... | [((1674, 1718), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'sharex': '(True)', 'sharey': '(True)'}), '(3, 1, sharex=True, sharey=True)\n', (1686, 1718), True, 'import matplotlib.pyplot as plt\n'), ((1765, 1809), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {'sharex': '(True)', 'sh... |
import math
import itertools
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def Embedding(num_embeddings, embedding_dim, padding_idx=None):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.... | [
"torch.log_softmax",
"torch.nn.AdaptiveLogSoftmaxWithLoss",
"math.sqrt",
"numpy.power",
"torch.nn.Embedding",
"torch.nn.functional.dropout",
"torch.nn.functional.cross_entropy",
"itertools.count",
"torch.cat",
"torch.nn.init.normal_",
"torch.nn.init.constant_",
"torch.arange",
"numpy.sin",
... | [((189, 257), 'torch.nn.Embedding', 'nn.Embedding', (['num_embeddings', 'embedding_dim'], {'padding_idx': 'padding_idx'}), '(num_embeddings, embedding_dim, padding_idx=padding_idx)\n', (201, 257), True, 'import torch.nn as nn\n'), ((262, 322), 'torch.nn.init.normal_', 'nn.init.normal_', (['m.weight'], {'mean': '(0)', '... |
from statistics import mean
import numpy as np
from tqdm import tqdm
#credits to http://www2.stat.duke.edu/~ar182/rr/examples-gallery/PermutationTest.html
def compute_permutation_stat(z, y):
def run_permutation_test(pooled,sizeZ,sizeY,delta):
np.random.shuffle(pooled)
starZ = pooled[:sizeZ]
... | [
"numpy.hstack",
"numpy.where",
"numpy.array",
"statistics.mean",
"numpy.random.shuffle"
] | [((403, 420), 'numpy.hstack', 'np.hstack', (['[z, y]'], {}), '([z, y])\n', (412, 420), True, 'import numpy as np\n'), ((623, 642), 'numpy.array', 'np.array', (['estimates'], {}), '(estimates)\n', (631, 642), True, 'import numpy as np\n'), ((912, 931), 'numpy.array', 'np.array', (['loss_list'], {}), '(loss_list)\n', (92... |
import numpy as np
from TaichiGAME.dynamics.body import Body
from TaichiGAME.dynamics.joint.joint import JointType
from TaichiGAME.dynamics.joint.rotation import OrientationJointPrimitive, RotationJoint
from TaichiGAME.dynamics.joint.rotation import RotationJointPrimitive
from TaichiGAME.math.matrix import Matrix
cl... | [
"TaichiGAME.math.matrix.Matrix",
"numpy.isclose",
"TaichiGAME.dynamics.joint.rotation.RotationJoint",
"TaichiGAME.dynamics.joint.rotation.RotationJointPrimitive",
"TaichiGAME.dynamics.joint.rotation.OrientationJointPrimitive"
] | [((420, 444), 'TaichiGAME.dynamics.joint.rotation.RotationJointPrimitive', 'RotationJointPrimitive', ([], {}), '()\n', (442, 444), False, 'from TaichiGAME.dynamics.joint.rotation import RotationJointPrimitive\n'), ((549, 576), 'numpy.isclose', 'np.isclose', (['dut._ref_rot', '(0)'], {}), '(dut._ref_rot, 0)\n', (559, 57... |
from typing import Union
import numpy as np
import scipy
import scipy.stats
# Every function takes and return arrays of same dimensions or scalars
DEFAULT_RETURN = np.float(0)
def add(
x: Union[int, float, np.ndarray], y: Union[int, float, np.ndarray]
) -> Union[int, float, np.ndarray]:
return np.nan_to_nu... | [
"numpy.abs",
"numpy.nan_to_num",
"numpy.sum",
"numpy.floor",
"numpy.sin",
"numpy.mean",
"numpy.exp",
"numpy.round",
"numpy.std",
"numpy.power",
"numpy.append",
"numpy.max",
"numpy.int",
"numpy.ceil",
"numpy.float",
"numpy.min",
"numpy.cos",
"numpy.zeros",
"scipy.stats.skew",
"n... | [((167, 178), 'numpy.float', 'np.float', (['(0)'], {}), '(0)\n', (175, 178), True, 'import numpy as np\n'), ((1089, 1107), 'numpy.nan_to_num', 'np.nan_to_num', (['res'], {}), '(res)\n', (1102, 1107), True, 'import numpy as np\n'), ((1488, 1506), 'numpy.nan_to_num', 'np.nan_to_num', (['res'], {}), '(res)\n', (1501, 1506... |
# jbase
from ctypes import CDLL, byref, c_char_p, c_longlong, c_void_p, string_at
import numpy as np
import os
import subprocess
jt = 0
def init(basedir, uname):
global libj, jt
os.chdir(basedir)
bindir = basedir + "/j"
darwin = uname == "darwin"
win32 = uname == "win32"
jc = "/jconsole.exe" if win32 else "/j... | [
"ctypes.byref",
"ctypes.string_at",
"subprocess.check_output",
"ctypes.c_longlong",
"ctypes.c_void_p",
"ctypes.CDLL",
"os.chdir",
"numpy.prod"
] | [((184, 201), 'os.chdir', 'os.chdir', (['basedir'], {}), '(basedir)\n', (192, 201), False, 'import os\n'), ((427, 533), 'subprocess.check_output', 'subprocess.check_output', (["[bindir + jc, '-jprofile', 'avx.ijs']"], {'cwd': 'bindir', 'encoding': '"""utf8"""', 'text': '(True)'}), "([bindir + jc, '-jprofile', 'avx.ijs'... |
import h5py
import numpy as np
import cv2
import os
def get_data(filename, dataset_ID):
data_path_main = "./datasets/us2mr/"
data_path_train = data_path_main + "train" + dataset_ID + "/"
data_path_test = data_path_main + "test" + dataset_ID + "/"
if not os.path.exists(data_path_main):
os.mkd... | [
"os.mkdir",
"h5py.File",
"numpy.ptp",
"os.path.exists",
"numpy.min",
"numpy.rot90",
"numpy.array"
] | [((508, 537), 'h5py.File', 'h5py.File', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (517, 537), False, 'import h5py\n'), ((274, 304), 'os.path.exists', 'os.path.exists', (['data_path_main'], {}), '(data_path_main)\n', (288, 304), False, 'import os\n'), ((314, 338), 'os.mkdir', 'os.mkdir', (['data_pat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files... | [
"wavestate.bunch.Bunch",
"numpy.eye",
"numpy.linalg.inv"
] | [((5288, 5386), 'wavestate.bunch.Bunch', 'Bunch', ([], {'ol': 'oLp_path[0]', 'oLp_path': 'oLp_path', 'oltrans': 'trans', 'qX': 'qX', 'qY': 'qY', 'Wk': 'Wk', 'type': '"""specified"""'}), "(ol=oLp_path[0], oLp_path=oLp_path, oltrans=trans, qX=qX, qY=qY, Wk=Wk,\n type='specified')\n", (5293, 5386), False, 'from wavesta... |
import numpy as np
from math import log2, sqrt
def entropy(class_y):
"""
Input:
- class_y: list of class labels (0's and 1's)
Output:
- entropy: a scalar, the value of entropy.
TODO: [3 points]
Compute the entropy for a list of classes
Example: entropy([0,0,0,1,1,1,1,1]) =... | [
"numpy.isin",
"numpy.copy",
"numpy.log2",
"numpy.isnan",
"numpy.mean",
"numpy.array",
"numpy.where"
] | [((344, 360), 'numpy.mean', 'np.mean', (['class_y'], {}), '(class_y)\n', (351, 360), True, 'import numpy as np\n'), ((3363, 3388), 'numpy.array', 'np.array', (['X'], {'dtype': 'object'}), '(X, dtype=object)\n', (3371, 3388), True, 'import numpy as np\n'), ((3397, 3408), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', ... |
import itertools
from collections import OrderedDict, namedtuple
import numpy as np
from sympy import Indexed
from devito.ir.support import Stencil
from devito.exceptions import DSEException
from devito.symbolics import retrieve_indexed, q_indirect
__all__ = ['collect']
def collect(exprs):
"""
Determine gr... | [
"devito.ir.support.Stencil",
"devito.ir.support.Stencil.union",
"devito.symbolics.retrieve_indexed",
"numpy.mean",
"collections.namedtuple",
"collections.OrderedDict",
"devito.symbolics.q_indirect"
] | [((1305, 1349), 'collections.namedtuple', 'namedtuple', (['"""ExprData"""', '"""dimensions offsets"""'], {}), "('ExprData', 'dimensions offsets')\n", (1315, 1349), False, 'from collections import OrderedDict, namedtuple\n'), ((1467, 1480), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1478, 1480), False,... |
import torch
import os
import numpy as np
from torchvision.datasets import MNIST, FashionMNIST, CIFAR10, CIFAR100, SVHN, ImageFolder
from torchvision.transforms import transforms as T, InterpolationMode
from torch.utils.data import random_split, DataLoader
from kme.data.cub import Cub2011
from kme.data.risk_datasets im... | [
"torchvision.transforms.transforms.ColorJitter",
"kme.data.text_classification.get_text_dataset",
"torchvision.datasets.CIFAR10",
"kme.data.risk_datasets.RiskDataset",
"kme.data.benchmark_datasets.HeartDataset",
"torchvision.datasets.SVHN",
"os.path.join",
"torch.utils.data.DataLoader",
"torchvision... | [((9738, 9787), 'torch.utils.data.random_split', 'random_split', (['train_set', '[train_size, valid_size]'], {}), '(train_set, [train_size, valid_size])\n', (9750, 9787), False, 'from torch.utils.data import random_split, DataLoader\n'), ((9808, 9913), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batc... |
"""
Preparing data: Vectorize data
Pad your lists so that they all have the same length, turn them into an integer tensor of shape (samples, word_indices), and then use as the first layer in your network a layer capable of handling such integer tensors (the Embedding layer, which we’ll cover in detail later in the boo... | [
"numpy.asarray",
"keras.datasets.imdb.load_data"
] | [((1121, 1152), 'keras.datasets.imdb.load_data', 'imdb.load_data', ([], {'num_words': '(10000)'}), '(num_words=10000)\n', (1135, 1152), False, 'from keras.datasets import imdb\n'), ((1289, 1313), 'numpy.asarray', 'np.asarray', (['train_labels'], {}), '(train_labels)\n', (1299, 1313), True, 'import numpy as np\n'), ((13... |
# -*- coding: utf-8 -*-
# vim :set ft=py:
from __future__ import print_function
import blosc
import pytest
from unittest.mock import patch
import numpy as np
from bloscpack.args import (BloscArgs,
BloscpackArgs,
MetadataArgs,
calcu... | [
"bloscpack.file_io.CompressedFPSource",
"bloscpack.testutil.create_tmp_files",
"bloscpack.testutil.cmp_fp",
"bloscpack.file_io.PlainFPSource",
"bloscpack.file_io.CompressedFPSink",
"bloscpack.compat_util.StringIO",
"bloscpack.file_io.pack_bytes_to_file",
"bloscpack.file_io._read_beginning",
"bloscpa... | [((5795, 5856), 'unittest.mock.patch', 'patch', (['"""bloscpack.file_io.FORMAT_VERSION"""', 'MAX_FORMAT_VERSION'], {}), "('bloscpack.file_io.FORMAT_VERSION', MAX_FORMAT_VERSION)\n", (5800, 5856), False, 'from unittest.mock import patch\n'), ((3476, 3504), 'bloscpack.testutil.create_array_fp', 'create_array_fp', (['(1)'... |
import numpy as np
from argparse import ArgumentParser
from scipy.misc import imsave
import os.path as osp
from utils import *
def _load(cuhk03_dir):
try:
from scipy.io import loadmat
matdata = loadmat(osp.join(cuhk03_dir, 'cuhk-03.mat'))
except:
from hdf5storage import loadmat
... | [
"numpy.cumsum",
"os.path.join",
"argparse.ArgumentParser"
] | [((3345, 3431), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Convert the CUHK-03 dataset into the uniform format"""'}), "(description=\n 'Convert the CUHK-03 dataset into the uniform format')\n", (3359, 3431), False, 'from argparse import ArgumentParser\n'), ((584, 618), 'os.path.join', 'osp... |
import json
import argparse
import numpy as np
from terminaltables import AsciiTable
from core.config import config, update_config
def iou(pred, gt): # require pred and gt is numpy
assert isinstance(pred, list) and isinstance(gt,list)
pred_is_list = isinstance(pred[0],list)
gt_is_list = isinstance(gt[0],l... | [
"numpy.minimum",
"numpy.maximum",
"argparse.ArgumentParser",
"core.config.update_config",
"terminaltables.AsciiTable",
"core.config.config.TEST.TIOU.split",
"core.config.config.TEST.RECALL.split",
"numpy.sort",
"numpy.mean",
"numpy.array",
"numpy.where"
] | [((458, 502), 'numpy.maximum', 'np.maximum', (['pred[:, 0, None]', 'gt[None, :, 0]'], {}), '(pred[:, 0, None], gt[None, :, 0])\n', (468, 502), True, 'import numpy as np\n'), ((517, 561), 'numpy.minimum', 'np.minimum', (['pred[:, 1, None]', 'gt[None, :, 1]'], {}), '(pred[:, 1, None], gt[None, :, 1])\n', (527, 561), True... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@description: Workflow for the semantic segmentation example
@author: <NAME>
@contact: <EMAIL>
@version: 2022.03.15
'''
#%% HEADER
# Modules
import itertools
import numpy as np
import tensorflow
from arthisto1960_utilities import *
from numpy import random
from os i... | [
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"numpy.random.seed",
"tensorflow.keras.layers.MaxPooling2D",
"numpy.invert",
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.layers.concatenate",
"numpy.tile",
"tensorflow.keras.callbacks.EarlyStopping",
"numpy.pad",
"numpy... | [((10916, 10979), 'tensorflow.keras.models.save_model', 'models.save_model', (['unet', '"""../data_1960/models/unet_baseline.h5"""'], {}), "(unet, '../data_1960/models/unet_baseline.h5')\n", (10933, 10979), False, 'from tensorflow.keras import callbacks, layers, models, preprocessing\n'), ((11639, 11696), 'tensorflow.k... |
import numpy as np
import pytest
from .coordinates_for_tests import COORDINATES
from podpac.datalib.terraintiles import TerrainTiles, get_tile_urls
from podpac import Coordinates, clinspace
@pytest.mark.integration
class TestTerrainTiles(object):
def test_common_coordinates(self):
node = TerrainTiles()
... | [
"podpac.datalib.terraintiles.TerrainTiles",
"podpac.datalib.terraintiles.get_tile_urls",
"numpy.isfinite",
"podpac.clinspace"
] | [((304, 318), 'podpac.datalib.terraintiles.TerrainTiles', 'TerrainTiles', ([], {}), '()\n', (316, 318), False, 'from podpac.datalib.terraintiles import TerrainTiles, get_tile_urls\n'), ((798, 841), 'podpac.datalib.terraintiles.TerrainTiles', 'TerrainTiles', ([], {'tile_format': '"""geotiff"""', 'zoom': '(8)'}), "(tile_... |
import itertools
import numpy as np
import pytest
from dnnv.nn.converters.tensorflow import *
from dnnv.nn.operations import *
def test_Transpose():
shape = (2, 3, 4)
data = np.random.random_sample(shape).astype(np.float32)
z = np.transpose(data)
op = Transpose(data)
tf_op = TensorflowConverter(... | [
"numpy.random.random_sample",
"numpy.asarray",
"numpy.allclose",
"numpy.dtype",
"numpy.transpose"
] | [((243, 261), 'numpy.transpose', 'np.transpose', (['data'], {}), '(data)\n', (255, 261), True, 'import numpy as np\n'), ((372, 394), 'numpy.allclose', 'np.allclose', (['result', 'z'], {}), '(result, z)\n', (383, 394), True, 'import numpy as np\n'), ((554, 576), 'numpy.allclose', 'np.allclose', (['result', 'z'], {}), '(... |
from __future__ import absolute_import, division, print_function
import bcolz
from bcolz import carray, ctable
import numpy as np
from pandas import DataFrame
from collections import Iterator
from toolz import partition_all, keyfilter
import os
from datashape import to_numpy_dtype
from toolz import keyfilter
from tool... | [
"bcolz.ctable",
"bcolz.carray",
"datashape.to_numpy_dtype",
"numpy.empty",
"os.path.exists",
"toolz.curried.partial",
"toolz.partition_all",
"numpy.ndarray"
] | [((1137, 1156), 'bcolz.ctable', 'ctable', (['b'], {}), '(b, **kwargs)\n', (1143, 1156), False, 'from bcolz import carray, ctable\n'), ((1288, 1307), 'bcolz.carray', 'carray', (['b'], {}), '(b, **kwargs)\n', (1294, 1307), False, 'from bcolz import carray, ctable\n'), ((2343, 2365), 'toolz.partition_all', 'partition_all'... |
import re
import numpy as np
import collections
def getText(end=10000):
f = open('coopertext.txt','r')
text = ''
i = 0
while i<end:
line = f.readline()
if not line:
break
line = re.sub(' +',' ',line)
line = re.sub('\n',' ',line)
text = text + line
i+=1
text = list(text)
for i in range(len(text)):... | [
"numpy.zeros",
"collections.Counter",
"numpy.asarray",
"re.sub"
] | [((193, 216), 're.sub', 're.sub', (['""" +"""', '""" """', 'line'], {}), "(' +', ' ', line)\n", (199, 216), False, 'import re\n'), ((224, 247), 're.sub', 're.sub', (['"""\n"""', '""" """', 'line'], {}), "('\\n', ' ', line)\n", (230, 247), False, 'import re\n'), ((530, 553), 're.sub', 're.sub', (['""" +"""', '""" """', ... |
""" This module extracts lexical features. """
import collections
import logging
import re
import sys
import math
import subprocess
import numpy as np
import scipy.stats
import scipy.spatial.distance
import nltk.probability
from nltk.corpus import wordnet as wn
from nltk.tokenize import sent_tokenize
import requests
i... | [
"subprocess.Popen",
"math.isnan",
"numpy.std",
"utils.logger.get_logger",
"nltk.corpus.wordnet.synsets",
"re.match",
"collections.defaultdict",
"nltk.tokenize.sent_tokenize",
"numpy.mean",
"numpy.array",
"numpy.reshape",
"numpy.linalg.norm",
"sys.exc_info",
"utils.lexicosyntactic.functions... | [((10065, 10093), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (10088, 10093), False, 'import collections\n'), ((13682, 13710), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (13705, 13710), False, 'import collections\n'), ((19121, 19170), 'requests.po... |
import tensorflow as tf
import numpy as np
import time
import cv2
import csv
import os
from utils import label_map_util
from utils import visualization_utils as vis_util
NUM_REC = 4
PATH_TO_RECORDING = 'C:/Users/Dario/rec_'+str(NUM_REC)+'.mp4'
PATH_TO_GROUNDTRUTH = 'C:/Users/Dario/object_tracking/groundtruth/GT_rec_'+... | [
"cv2.TrackerBoosting_create",
"csv.reader",
"cv2.rectangle",
"cv2.TrackerMOSSE_create",
"cv2.imshow",
"cv2.TrackerGOTURN_create",
"numpy.copy",
"cv2.TrackerKCF_create",
"utils.label_map_util.convert_label_map_to_categories",
"cv2.TrackerMIL_create",
"tensorflow.GraphDef",
"cv2.destroyAllWindow... | [((1571, 1606), 'cv2.VideoCapture', 'cv2.VideoCapture', (['PATH_TO_RECORDING'], {}), '(PATH_TO_RECORDING)\n', (1587, 1606), False, 'import cv2\n'), ((2322, 2332), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2330, 2332), True, 'import tensorflow as tf\n'), ((2618, 2665), 'utils.label_map_util.load_labelmap', 'lab... |
import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
import argparse
import time
#https://matplotlib.org/examples/color/colormaps_reference.html
def getProbDisplay(contextlist, probabilitylist, file):
contextlist=np.array(contextlist)
probabilitylist=np.array(probabilitylist)
retur... | [
"argparse.ArgumentParser",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.colorbar",
"time.time",
"numpy.array",
"matplotlib.pyplot.xticks"
] | [((243, 264), 'numpy.array', 'np.array', (['contextlist'], {}), '(contextlist)\n', (251, 264), True, 'import numpy as np\n'), ((285, 310), 'numpy.array', 'np.array', (['probabilitylist'], {}), '(probabilitylist)\n', (293, 310), True, 'import numpy as np\n'), ((550, 626), 'matplotlib.pyplot.scatter', 'plt.scatter', (['y... |
import streamlit as st
import pickle
import numpy as np
# import the model
pipe = pickle.load(open('pipe.pkl', 'rb'))
mobile_df = pickle.load(open('mobile_df.pkl', 'rb'))
st.title("Mobile Price Predictor")
brand = st.selectbox('Brand', mobile_df['brand'].unique())
ram = st.selectbox('RAM(in GB)', [1, 2, 3... | [
"streamlit.title",
"streamlit.button",
"numpy.array",
"streamlit.selectbox",
"streamlit.number_input"
] | [((181, 215), 'streamlit.title', 'st.title', (['"""Mobile Price Predictor"""'], {}), "('Mobile Price Predictor')\n", (189, 215), True, 'import streamlit as st\n'), ((285, 335), 'streamlit.selectbox', 'st.selectbox', (['"""RAM(in GB)"""', '[1, 2, 3, 4, 6, 8, 12]'], {}), "('RAM(in GB)', [1, 2, 3, 4, 6, 8, 12])\n", (297, ... |
import os
import argparse
import json
import pickle
import numpy as np
import pandas as pd
from tensorflow import keras
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import confusion_matrix
import bert # https://github.com/kpe/bert-for-tf2/
from langdetect import detect
from conversion import... | [
"bert.BertModelLayer.from_params",
"bert.bert_tokenization.validate_case_matches_checkpoint",
"argparse.ArgumentParser",
"numpy.argmax",
"pandas.read_csv",
"tensorflow.keras.layers.Dense",
"conversion.convert_examples_to_features",
"os.path.isfile",
"numpy.arange",
"bert.bert_tokenization.FullToke... | [((439, 461), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (452, 461), False, 'import nltk\n'), ((471, 496), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (494, 496), False, 'import argparse\n'), ((1381, 1419), 'os.path.join', 'os.path.join', (['log_dir', 'experiment... |
use_cuda = True
from scvi.dataset.dataset import GeneExpressionDataset
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
from scvi.harmonization.utils_chenling import trainSCANVI,trainVAE
from scvi.models import SCANVI
from scvi.inference.annotation import AlternateSemiS... | [
"scvi.inference.annotation.SemiSupervisedTrainer",
"scvi.harmonization.classification.CORAL.CORAL",
"numpy.log",
"scvi.models.SCANVI",
"scvi.inference.annotation.AlternateSemiSupervisedTrainer",
"scvi.harmonization.classification.scmap.SCMAP",
"numpy.unique",
"scvi.dataset.muris_tabula.TabulaMuris",
... | [((5051, 5126), 'scvi.dataset.muris_tabula.TabulaMuris', 'TabulaMuris', (['"""facs"""'], {'save_path': '"""/data/yosef2/scratch/chenling/scanvi_data/"""'}), "('facs', save_path='/data/yosef2/scratch/chenling/scanvi_data/')\n", (5062, 5126), False, 'from scvi.dataset.muris_tabula import TabulaMuris\n'), ((5138, 5216), '... |
"""
Python versions of functions for testing purposes etc.
"""
import numpy as np
def python_mvnpdf(data, means, covs):
from pymc import mv_normal_cov_like as pdf_func
results = []
for i, datum in enumerate(data):
for j, cov in enumerate(covs):
mean = means[j]
results.appen... | [
"numpy.random.randn",
"numpy.empty",
"numpy.array",
"numpy.random.rand",
"pymc.mv_normal_cov_like"
] | [((504, 531), 'numpy.empty', 'np.empty', (['T'], {'dtype': 'np.int32'}), '(T, dtype=np.int32)\n', (512, 531), True, 'import numpy as np\n'), ((913, 935), 'numpy.random.randn', 'np.random.randn', (['(20)', '(5)'], {}), '(20, 5)\n', (928, 935), True, 'import numpy as np\n'), ((570, 587), 'numpy.random.rand', 'np.random.r... |
"""Beam search decoder for Seq2Seq model
Python version decoder which treat Seq2Seq models(attention, transformer, CTC)
as acoustic model. Record inner states of Seq2Seq models in token and execute beam
search or argmax decoding algorithm.
"""
import numpy as np
from absl import logging
class Token:
"""Token used... | [
"numpy.argmax",
"absl.logging.warning",
"numpy.argpartition",
"numpy.min",
"numpy.array"
] | [((5703, 5749), 'numpy.array', 'np.array', (['[tok.cost for tok in self.prev_toks]'], {}), '([tok.cost for tok in self.prev_toks])\n', (5711, 5749), True, 'import numpy as np\n'), ((5770, 5783), 'numpy.min', 'np.min', (['costs'], {}), '(costs)\n', (5776, 5783), True, 'import numpy as np\n'), ((7050, 7142), 'absl.loggin... |
# Authors: <NAME> <<EMAIL>>
# License: MIT
import pytest
import numpy as np
from ..rls import RLS
def test_rls_start():
# Test RLS start parameters
rls = RLS(filter_order=5, forgetting_factor=0.999, wscm_factor=1e3)
params = rls.get_params()
assert params[:3] == (5, 0.999, 1e3)
assert (params[3] ... | [
"numpy.zeros",
"numpy.eye",
"pytest.raises",
"numpy.array"
] | [((488, 512), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (501, 512), False, 'import pytest\n'), ((675, 699), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (688, 699), False, 'import pytest\n'), ((864, 888), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.