code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import pandas as pd
import scipy.spatial as sp
import scipy.cluster.hierarchy as hc
from sklearn.metrics import silhouette_score
import numpy as np
from common import genome_pdist as gd
def automatic_cluster_species(Dist,seed_tresholds= [0.92,0.97],linkage_method='average'):
linkage = hc.linkage(sp.distance... | [
"common.genome_pdist.load_mummer",
"common.genome_pdist.evaluate_clusters_tresholds",
"scipy.spatial.distance.squareform",
"numpy.isnan",
"common.genome_pdist.load_quality",
"pandas.DataFrame",
"common.genome_pdist.best_genome_from_table",
"common.genome_pdist.pairewise2matrix",
"scipy.cluster.hiera... | [((1362, 1418), 'scipy.cluster.hierarchy.fcluster', 'hc.fcluster', (['linkage', '(1 - treshold)'], {'criterion': '"""distance"""'}), "(linkage, 1 - treshold, criterion='distance')\n", (1373, 1418), True, 'import scipy.cluster.hierarchy as hc\n'), ((1429, 1508), 'common.genome_pdist.evaluate_clusters_tresholds', 'gd.eva... |
#-------------------------------------------------------------------------------------------------------------------
# Packages & Settings
#-------------------------------------------------------------------------------------------------------------------
# General packages
import time
import sys
import os
import date... | [
"scipy.optimize.curve_fit",
"numpy.mean",
"matplotlib.pyplot.hist",
"os.makedirs",
"os.path.isdir",
"numpy.std",
"sys.path.append",
"matplotlib.pyplot.show"
] | [((935, 974), 'sys.path.append', 'sys.path.append', (['"""/home/rettenls/code/"""'], {}), "('/home/rettenls/code/')\n", (950, 974), False, 'import sys\n'), ((1929, 1950), 'numpy.mean', 'np.mean', (['displacement'], {}), '(displacement)\n', (1936, 1950), True, 'import numpy as np\n'), ((2219, 2263), 'matplotlib.pyplot.h... |
# //utils for periodic boundary conditions
# // Author: <NAME>
# // Date: 6.8.2021
# // Group: Rappel Group, UCSD
from numba import njit
import numpy as np
@njit
def pbc(x, L):
if(x<0):
X = x+L
return X
if(x>=L):
X = x-L
return X
return x
@njit
def sqdiff(x1, x2):
return... | [
"numpy.sqrt"
] | [((1036, 1054), 'numpy.sqrt', 'np.sqrt', (['(xsq + ysq)'], {}), '(xsq + ysq)\n', (1043, 1054), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# Created on Thu Dec 5 16:49:20 2019
# @author: arthurd
"""
FoRoute Module.
Visualize Map Matching routes on HTML maps.
"""
from matplotlib import collections as mc
import matplotlib.pyplot as plt
import osmnx as ox
import webbrowser
import folium
import numpy as np
import noiseplanet.matc... | [
"osmnx.plot_graph",
"folium.Element",
"osmnx.plot_graph_folium",
"folium.TileLayer",
"webbrowser.open",
"folium.Map",
"matplotlib.collections.LineCollection",
"numpy.array",
"noiseplanet.matcher.graph_from_track",
"matplotlib.pyplot.scatter",
"folium.PolyLine",
"matplotlib.pyplot.title",
"fo... | [((1160, 1184), 'numpy.array', 'np.array', (['[[None, None]]'], {}), '([[None, None]])\n', (1168, 1184), True, 'import numpy as np\n'), ((3143, 3269), 'osmnx.plot_graph', 'ox.plot_graph', (['graph'], {'node_color': '"""skyblue"""', 'node_alpha': '(0.5)', 'node_size': '(20)', 'annotate': '(True)', 'margin': '(0)', 'show... |
#!/usr/bin/env python
# modules
# ROS stuff and multithreading
import rospy
from geometry_msgs.msg import Twist, Pose2D, PoseStamped
from sensor_msgs.msg import JointState
from nav_msgs.msg import Odometry, Path
from std_msgs.msg import Float32MultiArray
import tf
import numpy as np
import sys
from dynamic_reconfigure... | [
"rospy.init_node",
"rospy.Rate",
"numpy.arctan2",
"numpy.linalg.norm",
"numpy.sin",
"dynamic_reconfigure.server.Server",
"numpy.linspace",
"rospy.Subscriber",
"geometry_msgs.msg.Twist",
"rospy.Time.now",
"numpy.cos",
"rospy.Publisher",
"nav_msgs.msg.Path",
"rospy.is_shutdown",
"std_msgs.... | [((6547, 6573), 'rospy.init_node', 'rospy.init_node', (['"""control"""'], {}), "('control')\n", (6562, 6573), False, 'import rospy\n'), ((6671, 6677), 'nav_msgs.msg.Path', 'Path', ([], {}), '()\n', (6675, 6677), False, 'from nav_msgs.msg import Odometry, Path\n'), ((6728, 6786), 'numpy.linspace', 'np.linspace', (['(-np... |
""" Contains classes and methods to obtain various regression based metrics to evaluate"""
from sklearn import metrics
import numpy as np
import pandas as pd
import math
import sys
sys.path.append("../config")
class MetricsEval:
"""MetricsEval Class
Evaluate metrics to evaluate model performance
"""
def metr... | [
"numpy.sqrt",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.r2_score",
"sys.path.append",
"numpy.mean",
"numpy.where",
"pandas.DataFrame.from_dict",
"numpy.exp",
"numpy.stack",
"pandas.DataFrame",
"sklearn.metrics.mean_ab... | [((181, 209), 'sys.path.append', 'sys.path.append', (['"""../config"""'], {}), "('../config')\n", (196, 209), False, 'import sys\n'), ((1268, 1285), 'numpy.zeros', 'np.zeros', (['kcc_dim'], {}), '(kcc_dim)\n', (1276, 1285), True, 'import numpy as np\n'), ((1299, 1316), 'numpy.zeros', 'np.zeros', (['kcc_dim'], {}), '(kc... |
import cv2
import matplotlib
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from PIL import ImageFilter, Image
def find_circle_coords(imagefile, radmin=80, radmax=110, houghaccumulator=0.6, searchrad=190):
''' Pass a raw image, and it will return a list of the identified circl... | [
"cv2.rectangle",
"numpy.hstack",
"cv2.HoughCircles",
"cv2.circle",
"cv2.destroyAllWindows",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imread"
] | [((672, 693), 'cv2.imread', 'cv2.imread', (['imagefile'], {}), '(imagefile)\n', (682, 693), False, 'import cv2\n'), ((761, 801), 'cv2.cvtColor', 'cv2.cvtColor', (['output', 'cv2.COLOR_BGR2GRAY'], {}), '(output, cv2.COLOR_BGR2GRAY)\n', (773, 801), False, 'import cv2\n'), ((1593, 1614), 'cv2.imread', 'cv2.imread', (['ima... |
"""
This file is test file for agent 6,7 and 8.
"""
# Necessary imports
import time
import numpy as np
import multiprocessing
from datetime import datetime
import pickle
from constants import STARTING_POSITION_OF_AGENT, INF, PROBABILITY_OF_GRID, NUM_ROWS, NUM_COLS, NUM_ITERATIONS
from helpers.helper import generate_g... | [
"pickle.dump",
"helpers.helper.compute_explored_cells_from_path",
"numpy.average",
"helpers.helper.generate_grid_with_probability_p",
"multiprocessing.cpu_count",
"src.Agent6.Agent6",
"datetime.datetime.now",
"multiprocessing.Pool",
"helpers.helper.examine_and_propagate_probability",
"helpers.help... | [((543, 551), 'src.Agent6.Agent6', 'Agent6', ([], {}), '()\n', (549, 551), False, 'from src.Agent6 import Agent6\n'), ((3698, 3709), 'time.time', 'time.time', ([], {}), '()\n', (3707, 3709), False, 'import time\n'), ((3856, 3895), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': 'n_cores'}), '(process... |
from datetime import datetime
from queue import deque
from time import time
import numpy as np
from comet_ml import Experiment
class Logger:
def __init__(self, opts=None, exp=None, n_train=None, n_val=None, n_test=None):
self.opts = opts
self.exp: Experiment = exp
self.n_train = n_train
... | [
"numpy.mean",
"time.time",
"datetime.datetime.now",
"queue.deque"
] | [((1131, 1137), 'time.time', 'time', ([], {}), '()\n', (1135, 1137), False, 'from time import time\n'), ((1255, 1277), 'numpy.mean', 'np.mean', (['self.qs[mode]'], {}), '(self.qs[mode])\n', (1262, 1277), True, 'import numpy as np\n'), ((548, 568), 'queue.deque', 'deque', (['[]'], {'maxlen': '(25)'}), '([], maxlen=25)\n... |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3, 2), ()],
'dtype': [numpy.float16, numpy.float32, numpy.flo... | [
"chainer.Variable",
"chainer.testing.fix_random",
"chainer.testing.run_module",
"chainer.functions.softplus",
"chainer.functions.Softplus",
"chainer.cuda.to_cpu",
"chainer.testing.product",
"numpy.exp",
"numpy.random.uniform",
"chainer.testing.assert_allclose",
"chainer.cuda.to_gpu"
] | [((332, 352), 'chainer.testing.fix_random', 'testing.fix_random', ([], {}), '()\n', (350, 352), False, 'from chainer import testing\n'), ((1835, 1873), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (1853, 1873), False, 'from chainer import testing\n'), ((5... |
"""
Module for testing the model_selection.search module.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import numpy as np
import pytest
from surprise import Dataset
from surprise import Reader
from surprise import SVD
from surprise.model_s... | [
"surprise.model_selection.GridSearchCV",
"numpy.mean",
"surprise.model_selection.PredefinedKFold",
"os.path.dirname",
"pytest.raises",
"numpy.std",
"numpy.argmin",
"surprise.Reader",
"surprise.model_selection.KFold"
] | [((1134, 1163), 'surprise.model_selection.GridSearchCV', 'GridSearchCV', (['SVD', 'param_grid'], {}), '(SVD, param_grid)\n', (1146, 1163), False, 'from surprise.model_selection import GridSearchCV\n'), ((2541, 2579), 'surprise.model_selection.KFold', 'KFold', (['(3)'], {'shuffle': '(True)', 'random_state': '(4)'}), '(3... |
import os
from TB2J.myTB import MyTB, merge_tbmodels_spin
import numpy as np
from TB2J.exchange import ExchangeCL, ExchangeNCL
from TB2J.exchangeCL2 import ExchangeCL2
from TB2J.utils import read_basis, auto_assign_basis_name
from ase.io import read
from TB2J.sisl_wrapper import SislWrapper
from TB2J.gpaw_wrapper impor... | [
"os.path.exists",
"TB2J.exchangeCL2.ExchangeCL2",
"TB2J.myTB.merge_tbmodels_spin",
"TB2J.exchange.ExchangeNCL",
"TB2J.gpaw_wrapper.GPAWWrapper",
"TB2J.sisl_wrapper.SislWrapper",
"os.path.join",
"TB2J.utils.read_basis",
"sisl.get_sile",
"numpy.vstack",
"TB2J.utils.auto_assign_basis_name",
"TB2J... | [((1130, 1161), 'os.path.join', 'os.path.join', (['path', '"""basis.txt"""'], {}), "(path, 'basis.txt')\n", (1142, 1161), False, 'import os\n'), ((5483, 5507), 'sisl.get_sile', 'sisl.get_sile', (['fdf_fname'], {}), '(fdf_fname)\n', (5496, 5507), False, 'import sisl\n'), ((8615, 8647), 'TB2J.gpaw_wrapper.GPAWWrapper', '... |
import io
import cv2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from estimation.coordinates import get_coordinates
from estimation.connections import get_connections
from estimation.estimators import estimate
from estimation.renderers import draw
from train_config import *
# find connec... | [
"matplotlib.pyplot.grid",
"io.BytesIO",
"estimation.coordinates.get_coordinates",
"matplotlib.pyplot.imshow",
"estimation.estimators.estimate",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"numpy.concatenate",
"tensorflow.convert_to_tensor",
"numpy.tile",
"matplotlib.pyplot.savefig",
... | [((1411, 1423), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (1421, 1423), False, 'import io\n'), ((1428, 1458), 'matplotlib.pyplot.savefig', 'plt.savefig', (['buf'], {'format': '"""png"""'}), "(buf, format='png')\n", (1439, 1458), True, 'import matplotlib.pyplot as plt\n'), ((1557, 1574), 'matplotlib.pyplot.close', '... |
import json
from multiprocessing import Pool
from random import randint
from typing import List, Dict, Callable, Any
import numpy as np
import os
from tqdm import tqdm
from pietoolbelt.datasets.common import BasicDataset
from pietoolbelt.pipeline.abstract_step import AbstractStep, DatasetInPipeline, AbstractStepDirR... | [
"os.path.exists",
"os.path.join",
"numpy.argmax",
"numpy.array",
"numpy.linspace",
"pietoolbelt.pipeline.abstract_step.AbstractStep.__init__",
"multiprocessing.Pool",
"json.load",
"numpy.load",
"json.dump"
] | [((471, 502), 'os.path.join', 'os.path.join', (['path', '"""meta.json"""'], {}), "(path, 'meta.json')\n", (483, 502), False, 'import os\n'), ((515, 546), 'os.path.exists', 'os.path.exists', (['self._meta_file'], {}), '(self._meta_file)\n', (529, 546), False, 'import os\n'), ((1558, 1576), 'numpy.load', 'np.load', (['fi... |
"""
Programmer: <NAME>
Date of Development: 28/10/2020
"""
# set the directory path
import os,sys
import os.path as path
abs_path_pkg = path.abspath(path.join(__file__ ,"../../../"))
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, abs_path_pkg)
# import other libraries
import numpy as np
f... | [
"numpy.mean",
"sys.path.insert",
"Py_FS.filter._utilities.normalize",
"os.path.join",
"numpy.square",
"os.path.realpath",
"numpy.sum",
"numpy.zeros",
"numpy.argsort",
"sklearn.datasets.load_wine"
] | [((241, 273), 'sys.path.insert', 'sys.path.insert', (['(0)', 'abs_path_pkg'], {}), '(0, abs_path_pkg)\n', (256, 273), False, 'import os, sys\n'), ((152, 184), 'os.path.join', 'path.join', (['__file__', '"""../../../"""'], {}), "(__file__, '../../../')\n", (161, 184), True, 'import os.path as path\n'), ((213, 239), 'os.... |
import numpy as np
from scipy import signal
from scipy.spatial.transform import Rotation as R
class Resize:
def __init__(self, size=125):
"""
Initiates transform with a target number for resize
:param size: int
"""
self.size = size
def __call__(self, x):
"""
... | [
"numpy.random.choice",
"scipy.signal.resample",
"numpy.zeros",
"scipy.spatial.transform.Rotation.from_euler"
] | [((2319, 2354), 'numpy.random.choice', 'np.random.choice', (['self.choices_list'], {}), '(self.choices_list)\n', (2335, 2354), True, 'import numpy as np\n'), ((2374, 2430), 'scipy.spatial.transform.Rotation.from_euler', 'R.from_euler', (['"""xy"""', '(rotate_to, rotate_to)'], {'degrees': '(True)'}), "('xy', (rotate_to,... |
#!/usr/bin/python3
import numpy as np
from matrixll import matrixll
class MLNTopology():
INDEX_INT_TYPE = int
def __init__(self):
# alt: tuple(int), xor, np.array(int), xor: simply an int !
self.layers_shape = [] # : List[int]
# nominal coord system dimensions: e.g. (x,y,ch) (theta,... | [
"matrixll.matrixll.create_matrixll",
"numpy.prod",
"matrixll.matrixll.check",
"matrixll.matrixll.shape"
] | [((7014, 7046), 'matrixll.matrixll.shape', 'matrixll.shape', (['matrix', '"""derive"""'], {}), "(matrix, 'derive')\n", (7028, 7046), False, 'from matrixll import matrixll\n'), ((2613, 2637), 'matrixll.matrixll.check', 'matrixll.check', (['m', '(-1)', 'h'], {}), '(m, -1, h)\n', (2627, 2637), False, 'from matrixll import... |
# -*- coding: utf-8 -*-
"""
contains main loop for training
"""
import torch
import utils
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
from torch.utils.data.sampler import SubsetRandomSampler
from model.dataset_class import AffectiveMonitorDataset
from model.net_valence import myLSTM_valen... | [
"torch.utils.data.sampler.SubsetRandomSampler",
"numpy.random.shuffle",
"torch.nn.CrossEntropyLoss",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.floor",
"torch.max",
"model.net_valence.myLSTM_valence",
"torch.cuda.is_available",
"model.net_arousal.myL... | [((854, 884), 'utils.load_object', 'utils.load_object', (['pickle_file'], {}), '(pickle_file)\n', (871, 884), False, 'import utils\n'), ((1325, 1359), 'torch.utils.data.sampler.SubsetRandomSampler', 'SubsetRandomSampler', (['train_indices'], {}), '(train_indices)\n', (1344, 1359), False, 'from torch.utils.data.sampler ... |
import time
import numpy as np
import random
import sys
import os
import argparse
import cv2
import zipfile
import itertools
import pybullet
import json
import time
import numpy as np
import imageio
import pybullet as p
from collect_pose_data import PoseDataCollector
sys.path.insert(1, '../utils/')
from coord_helper i... | [
"numpy.flip",
"sys.path.insert",
"argparse.ArgumentParser",
"numpy.searchsorted",
"os.path.join",
"os.path.isfile",
"numpy.array",
"numpy.argsort",
"os.path.isdir",
"os.mkdir",
"numpy.linalg.norm",
"json.load",
"numpy.load",
"numpy.save"
] | [((269, 300), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""../utils/"""'], {}), "(1, '../utils/')\n", (284, 300), False, 'import sys\n'), ((2681, 2703), 'numpy.array', 'np.array', (['filtered_idx'], {}), '(filtered_idx)\n', (2689, 2703), True, 'import numpy as np\n'), ((3202, 3227), 'argparse.ArgumentParser', 'ar... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["simplexy"]
import numpy as np
from ._simplexy import simplexy as run_simplexy
_dtype = np.dtype([("x", np.float32), ("y", np.float32),
("flux", np.float32), ("bkg", np.float32)])
def simplexy(img, **kwargs):
... | [
"numpy.dtype",
"numpy.ascontiguousarray"
] | [((177, 273), 'numpy.dtype', 'np.dtype', (["[('x', np.float32), ('y', np.float32), ('flux', np.float32), ('bkg', np.\n float32)]"], {}), "([('x', np.float32), ('y', np.float32), ('flux', np.float32), (\n 'bkg', np.float32)])\n", (185, 273), True, 'import numpy as np\n'), ((340, 385), 'numpy.ascontiguousarray', 'n... |
import pytest
import numpy as np
from mindspore import ops, Tensor, context
from mindspore.common.parameter import Parameter
from mindspore.nn import Cell
class AssignNet(Cell):
def __init__(self, input_variable):
super(AssignNet, self).__init__()
self.op = ops.Assign()
self.input_data = i... | [
"mindspore.context.set_context",
"numpy.random.seed",
"mindspore.Tensor",
"mindspore.ops.Assign",
"numpy.random.randn"
] | [((774, 791), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (788, 791), True, 'import numpy as np\n'), ((856, 903), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.PYNATIVE_MODE'}), '(mode=context.PYNATIVE_MODE)\n', (875, 903), False, 'from mindspore import ops, Tensor, c... |
"""
Template matching
Template matching is a technique for finding areas of an image that are similar to
a patch (template).
A patch is a small image with certain features. The goal of template matching is
to find the patch/template in an image.
To find it, the user has to give two input images... | [
"cv2.rectangle",
"numpy.where",
"cv2.imshow",
"cv2.cvtColor",
"cv2.matchTemplate",
"cv2.imread"
] | [((1881, 1911), 'cv2.imread', 'cv2.imread', (['"""../images/1.jpeg"""'], {}), "('../images/1.jpeg')\n", (1891, 1911), False, 'import cv2\n'), ((1950, 1991), 'cv2.cvtColor', 'cv2.cvtColor', (['img_rgb', 'cv2.COLOR_BGR2GRAY'], {}), '(img_rgb, cv2.COLOR_BGR2GRAY)\n', (1962, 1991), False, 'import cv2\n'), ((2024, 2049), 'c... |
#!/usr/bin/env ipython
# -*- coding: utf-8 -*-
import random as ran
import math
import numpy as np
"""Define auxiliary functions for Corona Testing Simulation."""
def _make_test(testlist, current_success_rate, false_posivite_rate, prob_sick,
tests_repetitions=1, test_result_decision_strategy='max'):
... | [
"numpy.ceil",
"numpy.ones",
"numpy.random.rand",
"numpy.max",
"random.random",
"numpy.random.shuffle"
] | [((3063, 3083), 'numpy.ones', 'np.ones', (['sample_size'], {}), '(sample_size)\n', (3070, 3083), True, 'import numpy as np\n'), ((3121, 3143), 'numpy.random.shuffle', 'np.random.shuffle', (['arr'], {}), '(arr)\n', (3138, 3143), True, 'import numpy as np\n'), ((1127, 1139), 'random.random', 'ran.random', ([], {}), '()\n... |
"""
相比于原始的plot.py文件,增加了如下的功能:
1.可以直接在pycharm或者vscode执行,也可以用命令行传参;
2.按exp_name排序,而不是按时间排序;
3.固定好每个exp_name的颜色;
4.可以调节曲线的线宽,便于观察;
5.保存图片到本地,便于远程ssh画图~
6.自动显示全屏
7.图片自适应
8.针对颜色不敏感的人群,可以在每条legend上注明性能值,和性能序号
9.对图例legend根据性能从高到低排序,便于分析比较
10.提供clip_xaxis值,对训练程度进行统一截断,图看起来更整洁。
seaborn版本0.8.1
"""
import seaborn as sns
import p... | [
"numpy.convolve",
"numpy.array",
"os.walk",
"seaborn.set",
"os.listdir",
"argparse.ArgumentParser",
"numpy.asarray",
"os.path.isdir",
"numpy.round",
"numpy.ones",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.gca",
"os.path.dirname",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
... | [((3104, 3146), 'seaborn.set', 'sns.set', ([], {'style': '"""darkgrid"""', 'font_scale': '(1.75)'}), "(style='darkgrid', font_scale=1.75)\n", (3111, 3146), True, 'import seaborn as sns\n'), ((5142, 5285), 'matplotlib.pyplot.legend', 'plt.legend', (['sorted_handles', 'sorted_labels'], {'loc': '"""upper center"""', 'labe... |
import argparse
import os
import numpy as np
from rsgd.common.dat import load_dat
from rsgd.common.logistic import logistic_grad
from rsgd.common.logistic import logistic_loss
from rsgd.common.logistic import logistic_test
from rsgd.common.utils import get_batch_index
from sklearn.utils import shuffle
def sgd_restart... | [
"numpy.abs",
"numpy.mean",
"argparse.ArgumentParser",
"rsgd.common.dat.load_dat",
"rsgd.common.utils.get_batch_index",
"os.path.join",
"numpy.zeros",
"rsgd.common.logistic.logistic_test",
"numpy.linalg.norm"
] | [((530, 560), 'rsgd.common.utils.get_batch_index', 'get_batch_index', (['N', 'batch_size'], {}), '(N, batch_size)\n', (545, 560), False, 'from rsgd.common.utils import get_batch_index\n'), ((675, 697), 'numpy.zeros', 'np.zeros', (['(niter, dim)'], {}), '((niter, dim))\n', (683, 697), True, 'import numpy as np\n'), ((70... |
import numpy as np
from urllib import request
import gzip
import os
import boto3
import json
dirname = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(dirname, "config.json"), "r") as f:
CONFIG = json.load(f)
def mnist_to_numpy(data_dir='/tmp/data', train=True):
"""Download MNIST dataset a... | [
"numpy.mean",
"os.path.exists",
"boto3.client",
"os.makedirs",
"numpy.std",
"os.path.join",
"json.load",
"numpy.expand_dims",
"numpy.finfo",
"os.path.abspath",
"numpy.transpose"
] | [((121, 146), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (136, 146), False, 'import os\n'), ((221, 233), 'json.load', 'json.load', (['f'], {}), '(f)\n', (230, 233), False, 'import json\n'), ((877, 895), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (889, 895), False, 'im... |
# Search function
# Prior to running this, a model must first be loaded and vectors must first be built for documents
import pandas as pd
import re
import spacy
from rank_bm25 import BM25Okapi
from tqdm import tqdm
import pickle
import numpy as np
from gensim.models.fasttext import FastText
import os
import nmslib
imp... | [
"pandas.DataFrame",
"numpy.mean",
"pandas.merge",
"time.time"
] | [((615, 637), 'numpy.mean', 'np.mean', (['query'], {'axis': '(0)'}), '(query, axis=0)\n', (622, 637), True, 'import numpy as np\n'), ((644, 655), 'time.time', 'time.time', ([], {}), '()\n', (653, 655), False, 'import time\n'), ((732, 743), 'time.time', 'time.time', ([], {}), '()\n', (741, 743), False, 'import time\n'),... |
"""
Specify times for synchronic image download.
Query available images and download best matches.
"""
import os
import numpy as np
import pandas as pd
from astropy.time import Time
import astropy.units as u
from chmap.settings.app import App
import chmap.database.db_classes as DBClass
from chmap.database.db_funs imp... | [
"chmap.database.db_funs.init_db_conn_old",
"os.path.join",
"astropy.time.Time",
"pandas.DataFrame",
"chmap.data.download.image_download.synchronic_euv_download",
"numpy.arange"
] | [((467, 511), 'astropy.time.Time', 'Time', (['"""2021-01-02T00:00:00.000"""'], {'scale': '"""utc"""'}), "('2021-01-02T00:00:00.000', scale='utc')\n", (471, 511), False, 'from astropy.time import Time\n'), ((525, 569), 'astropy.time.Time', 'Time', (['"""2021-01-03T00:00:00.000"""'], {'scale': '"""utc"""'}), "('2021-01-0... |
#!/usr/bin/env python
"""
Calculates fractional amplitude of low-frequency fluctuations (fALFF)
Usage:
falff_nifti.py <func.nii.gz> <output.nii.gz> [options]
Arguments:
<func.nii.gz> The functional 4D nifti files
<mask.nii.gz> A brainmask for the functional file
<output.nii.gz> Output filename
O... | [
"nibabel.load",
"numpy.where",
"numpy.arange",
"numpy.fft.fftfreq",
"numpy.std",
"numpy.sum",
"numpy.zeros",
"scipy.fftpack.fft",
"nibabel.Nifti1Image",
"docopt.docopt",
"numpy.divide"
] | [((868, 883), 'docopt.docopt', 'docopt', (['__doc__'], {}), '(__doc__)\n', (874, 883), False, 'from docopt import docopt\n'), ((2456, 2474), 'nibabel.load', 'nib.load', (['funcfile'], {}), '(funcfile)\n', (2464, 2474), True, 'import nibabel as nib\n'), ((2977, 2996), 'numpy.where', 'np.where', (['(mask != 0)'], {}), '(... |
import math
import numpy as np
from random import randint, seed
from copy import deepcopy
from typing import List
from EvaluationUtils.vision_metrics import CVMetrics
from Animator.consolidation_api import CharacterBoundingBox
from Animator.utils import serialize_pickle, deserialize_pickle
seed(1234567)
class Tripl... | [
"EvaluationUtils.vision_metrics.CVMetrics.bb_intersection_over_union",
"numpy.random.choice",
"random.seed",
"copy.deepcopy",
"Animator.utils.serialize_pickle",
"Animator.utils.deserialize_pickle"
] | [((293, 306), 'random.seed', 'seed', (['(1234567)'], {}), '(1234567)\n', (297, 306), False, 'from random import randint, seed\n'), ((1546, 1581), 'Animator.utils.serialize_pickle', 'serialize_pickle', (['self', 'output_path'], {}), '(self, output_path)\n', (1562, 1581), False, 'from Animator.utils import serialize_pick... |
from tensorflow.keras.layers import ZeroPadding2D, Convolution2D, MaxPooling2D
from tensorflow.keras.layers import Dense, Dropout, Softmax, Flatten, Activation, BatchNormalization
import numpy as np
from matplotlib import pyplot
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.preprocessing.i... | [
"tensorflow.keras.layers.Convolution2D",
"keras.layers.experimental.preprocessing.RandomFlip",
"matplotlib.pyplot.imshow",
"tensorflow.keras.models.Model",
"tensorflow.keras.preprocessing.image.img_to_array",
"keras.layers.experimental.preprocessing.RandomRotation",
"tensorflow.keras.models.Sequential",... | [((1029, 1119), 'keras_vggface.vggface.VGGFace', 'VGGFace', ([], {'model': '"""resnet50"""', 'include_top': '(False)', 'input_shape': '(224, 224, 3)', 'pooling': '"""avg"""'}), "(model='resnet50', include_top=False, input_shape=(224, 224, 3),\n pooling='avg')\n", (1036, 1119), False, 'from keras_vggface.vggface impo... |
from create_allele_counts import get_primer_intervals
def pair_counts(sam_fname, paired=False, qual_min=30, max_reads=-1,
max_isize = 700, VERBOSE = 0,
fwd_primer_regions = None, rev_primer_regions = None):
'''
'''
import numpy as np
import pysam
from collections imp... | [
"numpy.abs",
"numpy.ones_like",
"pickle.dump",
"argparse.ArgumentParser",
"gzip.open",
"create_allele_counts.get_primer_intervals",
"numpy.where",
"itertools.combinations",
"numpy.array",
"numpy.zeros",
"pysam.Samfile",
"numpy.fromstring"
] | [((505, 547), 'numpy.array', 'np.array', (["['A', 'C', 'G', 'T']"], {'dtype': '"""S1"""'}), "(['A', 'C', 'G', 'T'], dtype='S1')\n", (513, 547), True, 'import numpy as np\n'), ((7551, 7669), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""create pair counts"""', 'formatter_class': 'argpars... |
# Copyright 2021 The Distla Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | [
"distla_core.linalg.utils.testutils.eps",
"distla_core.utils.initializers.ones",
"jax.random.PRNGKey",
"jax.random.uniform",
"jax.local_device_count",
"numpy.testing.assert_allclose",
"jax.random.normal",
"pytest.mark.parametrize",
"distla_core.utils.initializers.normal",
"distla_core.utils.pops.u... | [((1283, 1337), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""matrix_shape"""', 'matrix_shapes'], {}), "('matrix_shape', matrix_shapes)\n", (1306, 1337), False, 'import pytest\n'), ((1563, 1617), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""matrix_shape"""', 'matrix_shapes'], {}), "('matrix... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 28 16:23:37 2016
@author: <NAME> (<EMAIL>)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
import sys
import time
import numpy as np
from six.moves import xrange # pylint: disable=r... | [
"data_utils.initialize_vocabulary",
"tensorflow.gfile.GFile",
"math.exp",
"tensorflow.app.run",
"tensorflow.gfile.Exists",
"subprocess.Popen",
"tensorflow.Session",
"os.chmod",
"os.path.isdir",
"subprocess.call",
"tensorflow.app.flags.DEFINE_boolean",
"sys.stdout.flush",
"tensorflow.initiali... | [((631, 718), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""max_gradient_norm"""', '(5.0)', '"""Clip gradients to this norm."""'], {}), "('max_gradient_norm', 5.0,\n 'Clip gradients to this norm.')\n", (656, 718), True, 'import tensorflow as tf\n'), ((741, 828), 'tensorflow.app.flags.DEFINE... |
"""
Plots fig S2:
Specifically, zonal-mean root-mean-square of stationary wave meridional wind
at 850 hPa for both reanalysis and aquaplanet simulation data for ANNUAL and NDJFM.
NOTE: since the reviewer asked for a measure of interannual variability in
stationary wave amplitude, here we calculate stationary waves as... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylim",
"xarray.open_dataset",
"matplotlib.pyplot.... | [((1283, 1309), 'xarray.open_dataset', 'xr.open_dataset', (['filename1'], {}), '(filename1)\n', (1298, 1309), True, 'import xarray as xr\n'), ((1327, 1353), 'xarray.open_dataset', 'xr.open_dataset', (['filename2'], {}), '(filename2)\n', (1342, 1353), True, 'import xarray as xr\n'), ((1371, 1397), 'xarray.open_dataset',... |
import copy
from joblib import Parallel
import numpy as np
import time
import numbers
from itertools import product
from collections import defaultdict
from sklearn import clone
from sklearn.pipeline import Pipeline
from sklearn.model_selection import check_cv, GridSearchCV, RandomizedSearchCV
from sklearn.model_select... | [
"sklearn.model_selection._validation._translate_train_sizes",
"sklearn.utils.validation._check_fit_params",
"sklearn.model_selection._validation._insert_error_scores",
"sklearn.model_selection._validation._aggregate_score_dicts",
"sklearn.clone",
"copy.deepcopy",
"sklearn.base.is_classifier",
"sklearn... | [((1285, 1314), 'copy.deepcopy', 'copy.deepcopy', (['src_fit_params'], {}), '(src_fit_params)\n', (1298, 1314), False, 'import copy\n'), ((2942, 2967), 'copy.deepcopy', 'copy.deepcopy', (['fit_params'], {}), '(fit_params)\n', (2955, 2967), False, 'import copy\n'), ((5142, 5537), 'sklearn.model_selection._validation._fi... |
import numpy as np
from pysc2.lib import actions
import tensorflow as tf
def compute_trajectory_loss ( y_true, y_pred ):
combinedLoss = tf.reduce_mean(y_true) - 0 * tf.reduce_mean(y_pred[-1])
return combinedLoss
class Agent():
def __init__(self, envParams ):
self.welcomeStr = 'PLACEHOLDER-AGENT'
... | [
"numpy.reshape",
"pysc2.lib.actions.FunctionCall",
"numpy.random.random",
"numpy.argmax",
"numpy.square",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.isfinite",
"numpy.unravel_index",
"numpy.ma.log",
"tensorflow.reduce_mean"
] | [((142, 164), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['y_true'], {}), '(y_true)\n', (156, 164), True, 'import tensorflow as tf\n'), ((1189, 1236), 'numpy.zeros', 'np.zeros', (['(nEnvs, nSteps + 1)'], {'dtype': 'np.float32'}), '((nEnvs, nSteps + 1), dtype=np.float32)\n', (1197, 1236), True, 'import numpy as np\n')... |
from .prs import PRS, SubStream_Container
import random
import torch
import numpy as np
from collections import deque
class DelayBuffer(PRS):
"""
Delayed Buffer for new data samples that need to be learned in chunks.
and used to made the decision later whether to enter the buffer or not.
"""
def r... | [
"torch.manual_seed",
"numpy.random.seed",
"random.seed"
] | [((564, 606), 'numpy.random.seed', 'np.random.seed', (["self.config['random_seed']"], {}), "(self.config['random_seed'])\n", (578, 606), True, 'import numpy as np\n'), ((615, 654), 'random.seed', 'random.seed', (["self.config['random_seed']"], {}), "(self.config['random_seed'])\n", (626, 654), False, 'import random\n')... |
#!/usr/bin/env python
"""
Created on March 1, 2016
@author: <NAME>, <EMAIL>, <NAME>, University of Chicago
Use ./CalcP.py -h to see usage
Credit for the arbfit code goes to Nablaquabla
"""
import numpy as np
import matplotlib.pylab as plt
from mpfit import mpfit
VERSION="0.9"
from scipy.stats import kendalltau
from... | [
"numpy.sqrt",
"argparse.ArgumentParser",
"statsmodels.stats.multitest.multipletests",
"scipy.stats.gamma.fit",
"scipy.stats.gamma",
"numpy.array",
"numpy.sum",
"pandas.read_table",
"numpy.cumsum",
"numpy.vectorize",
"mpfit.mpfit"
] | [((922, 959), 'pandas.read_table', 'pd.read_table', (['fn_jtk'], {'index_col': '"""ID"""'}), "(fn_jtk, index_col='ID')\n", (935, 959), True, 'import pandas as pd\n'), ((1632, 1673), 'scipy.stats.gamma', 'ss.gamma', (['params[0]', 'params[1]', 'params[2]'], {}), '(params[0], params[1], params[2])\n', (1640, 1673), True,... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
import tensorflow as tf
from src import utils
box_size = 368
hm_factor = 8
joints_num = 21
scales = [1.0, 0.7]
limb_parents = [1, 15, 1, 2, 3, 1, 5, 6, 14, 8, 9, 14, 11, 12, 14, 14, 1, 4, 7, 10, 13]
with tf.Session() as sess:
saver = ... | [
"numpy.hstack",
"tensorflow.Session",
"src.utils.extract_2d_joints_from_heatmaps",
"cv2.imshow",
"cv2.waitKey",
"tensorflow.train.import_meta_graph",
"src.utils.draw_limbs_2d",
"src.utils.img_scale_squarify",
"numpy.vstack",
"cv2.destroyAllWindows",
"tensorflow.train.latest_checkpoint",
"cv2.i... | [((286, 298), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (296, 298), True, 'import tensorflow as tf\n'), ((320, 381), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (['"""./models/tf_model/vnect_tf.meta"""'], {}), "('./models/tf_model/vnect_tf.meta')\n", (346, 381), True, 'import tensorf... |
"""
Example of defining a custom (image) transform using FFCV.
For tutorial, see https://docs.ffcv.io/ffcv_examples/custom_transforms.html.
"""
import time
import numpy as np
import torchvision
from ffcv.fields import IntField, RGBImageField
from ffcv.fields.decoders import SimpleRGBImageDecoder
from ffcv.loader impo... | [
"ffcv.fields.RGBImageField",
"ffcv.transforms.ToTensor",
"numpy.random.rand",
"ffcv.fields.IntField",
"ffcv.pipeline.compiler.Compiler.get_iterator",
"ffcv.loader.Loader",
"dataclasses.replace",
"torchvision.datasets.CIFAR10",
"ffcv.fields.decoders.SimpleRGBImageDecoder",
"time.time",
"ffcv.pipe... | [((1513, 1576), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', (['"""/tmp"""'], {'train': '(True)', 'download': '(True)'}), "('/tmp', train=True, download=True)\n", (1541, 1576), False, 'import torchvision\n'), ((1978, 2122), 'ffcv.loader.Loader', 'Loader', (['f"""/tmp/cifar.beton"""'], {'batch_size': ... |
#%% Import modules
import numpy as np
import torch
def train(A, ss, epoch, single_model, single_optim, loss_MSE):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
FR_ORDER_TRAIN = A["FR_ORDER_TRAIN"]
POS_NOR_ORDER_TRAIN = A["POS_NOR_ORDER_TRAIN"]
VEL_NOR_ORDER_TRAIN = A["VEL_NOR_OR... | [
"torch.utils.data.DataLoader",
"torch.utils.data.TensorDataset",
"torch.from_numpy",
"torch.cuda.is_available",
"torch.save",
"numpy.concatenate",
"torch.no_grad"
] | [((501, 604), 'numpy.concatenate', 'np.concatenate', (['(POS_NOR_ORDER_TRAIN[ss], VEL_NOR_ORDER_TRAIN[ss], ACC_NOR_ORDER_TRAIN[ss])'], {'axis': '(2)'}), '((POS_NOR_ORDER_TRAIN[ss], VEL_NOR_ORDER_TRAIN[ss],\n ACC_NOR_ORDER_TRAIN[ss]), axis=2)\n', (515, 604), True, 'import numpy as np\n'), ((706, 768), 'torch.utils.da... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from __future__ import division
import csv
import numpy as np
import random
import pickle
import datetime
from NonSpatialFns import *
# <codecell>
#Script
#Number of state transitions to observe
M = int(2e7)
# time vector
time = np.zeros(M)
#Define par... | [
"numpy.random.random",
"datetime.datetime.now",
"numpy.zeros",
"numpy.log10"
] | [((296, 307), 'numpy.zeros', 'np.zeros', (['M'], {}), '(M)\n', (304, 307), True, 'import numpy as np\n'), ((1373, 1395), 'numpy.zeros', 'np.zeros', (['[6, changes]'], {}), '([6, changes])\n', (1381, 1395), True, 'import numpy as np\n'), ((2794, 2805), 'numpy.zeros', 'np.zeros', (['M'], {}), '(M)\n', (2802, 2805), True,... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.appearance.hunt` module.
"""
import numpy as np
from itertools import permutations
from colour.appearance import (VIEWING_CONDITIONS_HUNT, InductionFactors_Hunt,
XYZ_to_Hunt)
from colour.appea... | [
"colour.utilities.domain_range_scale",
"colour.utilities.as_float_array",
"numpy.array",
"colour.appearance.XYZ_to_Hunt",
"itertools.permutations",
"colour.appearance.InductionFactors_Hunt",
"colour.utilities.tstack"
] | [((1584, 1625), 'colour.utilities.tstack', 'tstack', (["[data['X'], data['Y'], data['Z']]"], {}), "([data['X'], data['Y'], data['Z']])\n", (1590, 1625), False, 'from colour.utilities import as_float_array, domain_range_scale, ignore_numpy_errors, tstack\n'), ((1642, 1689), 'colour.utilities.tstack', 'tstack', (["[data[... |
# ######################################################################
# Copyright (c) 2014, Brookhaven Science Associates, Brookhaven #
# National Laboratory. All rights reserved. #
# #
# Redistribution and use in ... | [
"logging.getLogger",
"vttools.scrape._extract_default_vals",
"vttools.scrape._truncate_description",
"vttools.scrape.obj_src",
"numpy.testing.assert_equal",
"vttools.scrape._type_optional",
"vttools.scrape.scrape_function",
"itertools.product",
"numpy.testing.assert_raises",
"vttools.scrape._norma... | [((2657, 2684), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2674, 2684), False, 'import logging\n'), ((2939, 2997), 'vttools.scrape.scrape_function', 'scrape.scrape_function', (['"""porridge_for_the_bears"""', '__name__'], {}), "('porridge_for_the_bears', __name__)\n", (2961, 2997), F... |
import os
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import tqdm
from test import test
import torchvision
class TrainLoop(object):
def __init__(self, model, optimizer, source_loader, test_source_loader, target_loader, patience, l2, penalty_weight, penalty_anneal_epochs, checkpoint_pat... | [
"numpy.argmax",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.CrossEntropyLoss",
"torch.load",
"os.path.join",
"torch.optim.lr_scheduler.StepLR",
"test.test",
"os.getcwd",
"os.path.isfile",
"numpy.max",
"torch.tensor",
"os.path.isdir",
"torch.sum",
"torch.autograd.grad",
"os.mkdir"
... | [((634, 683), 'os.path.join', 'os.path.join', (['self.checkpoint_path', '"""IRM_{}ep.pt"""'], {}), "(self.checkpoint_path, 'IRM_{}ep.pt')\n", (646, 683), False, 'import os\n'), ((831, 898), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['self.optimizer'], {'step_size': 'patience'}), '(self.opti... |
import pandas as pd
from rdkit import Chem
import numpy as np
import json
from gensim.models import Word2Vec
from gensim.test.utils import get_tmpfile
from gensim.models import KeyedVectors
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import seaborn as sns
import networkx as nx
import re
""" Load ... | [
"networkx.bipartite.projected_graph",
"networkx.all_pairs_shortest_path_length",
"seaborn.color_palette",
"pandas.read_csv",
"rdkit.Chem.MolFromSmiles",
"networkx.Graph",
"sklearn.manifold.TSNE",
"gensim.models.KeyedVectors.load",
"json.load",
"networkx.connected_components",
"matplotlib.pyplot.... | [((447, 500), 'gensim.models.KeyedVectors.load', 'KeyedVectors.load', (['"""../vectors_fullKEGG.kv"""'], {'mmap': '"""r"""'}), "('../vectors_fullKEGG.kv', mmap='r')\n", (464, 500), False, 'from gensim.models import KeyedVectors\n'), ((3701, 3759), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'verbose':... |
#!/usr/bin/python3
import collections
import contextlib
import itertools
import logging
import math
import os.path
import re
import json
import sys
import types
from typing import Iterable, List, Tuple
import matplotlib
import numpy as np
from absl import app, flags
import scipy.stats
FLAGS = flags.FLAGS
flags.DEFIN... | [
"re.compile",
"matplotlib.pyplot.ylabel",
"absl.flags.register_validator",
"matplotlib.pyplot.errorbar",
"logging.info",
"numpy.arange",
"absl.flags.DEFINE_list",
"matplotlib.pyplot.xlabel",
"absl.app.run",
"numpy.max",
"matplotlib.pyplot.close",
"itertools.chain.from_iterable",
"matplotlib.... | [((309, 387), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""pdf_dir"""', '""""""', '"""directory to which PDF files are written"""'], {}), "('pdf_dir', '', 'directory to which PDF files are written')\n", (328, 387), False, 'from absl import app, flags\n'), ((388, 466), 'absl.flags.DEFINE_string', 'flags.DEFI... |
# -*- coding: UTF-8 -*-
"""
此脚本用于展示spectral embedding的效果
"""
import numpy as np
import matplotlib.pyplot as plt
from spectral_embedding_ import spectral_embedding
def generate_data():
"""
生成邻接矩阵
"""
data = np.array([
[0, 1, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 1, 0, 0],
[1, 1, 0, 1, ... | [
"spectral_embedding_.spectral_embedding",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
] | [((226, 406), 'numpy.array', 'np.array', (['[[0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 0, 0], [1, 1, 0, 1, 0, 0, 0], [1, 1,\n 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 0, 1], [0, 0, 0,\n 0, 1, 1, 0]]'], {}), '([[0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 0, 0], [1, 1, 0, 1, 0, 0, \n 0], [1, 1, 1, 0, 0, 0,... |
"""
clustering.py
2018.06.11
"""
import sys
import os
import argparse
import tensorflow as tf
import numpy as np
import facenet
from scipy import misc
from sklearn.cluster import KMeans
class FaceNet:
def __init__(self, sess, args):
self.session = sess
facenet.load_model(args.model)
... | [
"sklearn.cluster.KMeans",
"os.path.exists",
"tensorflow.ConfigProto",
"facenet.get_image_paths",
"argparse.ArgumentParser",
"os.mkdir",
"facenet.prewhiten",
"numpy.concatenate",
"tensorflow.GPUOptions",
"facenet.to_rgb",
"facenet.load_model",
"tensorflow.get_default_graph"
] | [((1630, 1701), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'args.gpu_memory_fraction'}), '(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n', (1643, 1701), True, 'import tensorflow as tf\n'), ((2952, 2977), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {})... |
import cv2
import numpy as np
import pafy
"""
url = 'https://youtu.be/u68EWmtKZw0?list=TLPQMDkwMzIwMjCcOgKmuF00yg'
vPafy = pafy.new(url)
play = vPafy.getbest(preftype="mp4")
cap = cv2.VideoCapture(play.url)
"""
cap = cv2.VideoCapture(0)
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottl... | [
"cv2.rectangle",
"cv2.dnn.readNetFromCaffe",
"cv2.imshow",
"cv2.putText",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.resize",
"cv2.waitKey",
"numpy.arange"
] | [((217, 236), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (233, 236), False, 'import cv2\n'), ((1711, 1734), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1732, 1734), False, 'import cv2\n'), ((601, 630), 'cv2.resize', 'cv2.resize', (['image', '(640, 640)'], {}), '(image, (640... |
"""
Vectorize() with support for decorating methods; for example::
from scipy.stats import rv_continuous
from scipy_ext import vectorize
class dist(rv_continuous):
@vectorize(excluded=('n',), otypes=(float,))
def _cdf(self, x, n):
if n < 5:
return f(x) # One ex... | [
"numpy.arange"
] | [((1635, 1665), 'numpy.arange', 'arange', (['starts', '(starts + count)'], {}), '(starts, starts + count)\n', (1641, 1665), False, 'from numpy import arange, stack, vectorize as numpy_vectorize\n'), ((1560, 1580), 'numpy.arange', 'arange', (['s', '(s + count)'], {}), '(s, s + count)\n', (1566, 1580), False, 'from numpy... |
# @title: pbt_trainer.py
# @author: <NAME>
# @date: 02.09.2021
############################################################
# Imports
import torch
import time
import numpy as np
import random
from torch.utils.tensorboard import SummaryWriter
from src.utility.container import (
ModelContainer,
UtilityC... | [
"src.gridworld_trainer.reinforce.model.ReinforceNetwork3D",
"src.gridworld_trainer.reinforce.memory.MemoryReinforce",
"torch.cuda.is_available",
"torchvision.utils.make_grid",
"copy.copy",
"logging.info",
"torch.utils.tensorboard.SummaryWriter",
"os.path.exists",
"src.utility.container.StatisticCont... | [((3125, 3153), 'torch.manual_seed', 'torch.manual_seed', (['self.seed'], {}), '(self.seed)\n', (3142, 3153), False, 'import torch\n'), ((3162, 3187), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (3176, 3187), True, 'import numpy as np\n'), ((3196, 3218), 'random.seed', 'random.seed', ([... |
""" Batched Render file. """
import dirt
import numpy as np
import tensorflow as tf
from dirt import matrices
import dirt.lighting as lighting
from tensorflow.python.framework import ops
def orthgraphic_projection(w, h, near=0.1, far=10., name=None):
"""Constructs a orthographic projection matrix.
This func... | [
"dirt.rasterise_batch",
"tensorflow.shape",
"numpy.zeros",
"tensorflow.ones_like",
"tensorflow.convert_to_tensor",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.cast"
] | [((2464, 2493), 'numpy.zeros', 'np.zeros', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (2472, 2493), True, 'import numpy as np\n'), ((2545, 2574), 'numpy.zeros', 'np.zeros', (['(3)'], {'dtype': 'np.float32'}), '(3, dtype=np.float32)\n', (2553, 2574), True, 'import numpy as np\n'), ((2611, 2640), 'num... |
# -*- coding: utf-8
import unicodedata
import math
import logging
import pickle
import numpy as np
import h5py
from .alignment import Alignment, Edits
GAP = '\a' # reserved character that does not get mapped (for gap repairs)
class Sequence2Sequence(object):
'''Sequence to sequence (character-level) error correc... | [
"logging.getLogger",
"numpy.nanargmax",
"numpy.log",
"keras.callbacks.TerminateOnNaN",
"keras.layers.TimeDistributed",
"keras.backend.slice",
"math.sqrt",
"numpy.argsort",
"numpy.array",
"numpy.count_nonzero",
"keras.layers.Dense",
"tensorflow.compat.v1.get_default_graph",
"math.exp",
"ten... | [((10507, 10533), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (10531, 10533), True, 'import tensorflow as tf\n'), ((12030, 12086), 'keras.layers.Input', 'Input', ([], {'shape': '(None, self.voc_size)', 'name': '"""encoder_input"""'}), "(shape=(None, self.voc_size), name='encoder_in... |
import numpy as np
import tensorflow as tf
import torch
from groupy.gconv.tensorflow_gconv.transform_filter import transform_filter_2d_nchw, transform_filter_2d_nhwc
from groupy.gconv.make_gconv_indices import make_c4_z2_indices, make_c4_p4_indices,\
make_d4_z2_indices, make_d4_p4m_indices, flatten_indices
from gr... | [
"numpy.abs",
"groupy.gconv.pytorch_gconv.splitgconv2d.trans_filter",
"groupy.gconv.make_gconv_indices.make_c4_z2_indices",
"tensorflow.Session",
"groupy.gconv.tensorflow_gconv.transform_filter.transform_filter_2d_nhwc",
"tensorflow.constant",
"groupy.gconv.make_gconv_indices.flatten_indices",
"groupy.... | [((493, 520), 'groupy.gconv.make_gconv_indices.make_c4_z2_indices', 'make_c4_z2_indices', ([], {'ksize': '(3)'}), '(ksize=3)\n', (511, 520), False, 'from groupy.gconv.make_gconv_indices import make_c4_z2_indices, make_c4_p4_indices, make_d4_z2_indices, make_d4_p4m_indices, flatten_indices\n'), ((529, 559), 'numpy.rando... |
import numpy as np
import nanocut.common as nc
from nanocut.output import error, printstatus
__all__ = [ "Periodicity", ]
def gcd(numbers):
"""Calculates greatest common divisor of a list of numbers."""
aa = numbers[0]
for bb in numbers[1:]:
while bb:
aa, bb = bb, aa % bb
re... | [
"nanocut.output.printstatus",
"numpy.prod",
"numpy.equal",
"numpy.not_equal",
"numpy.array",
"numpy.linalg.norm",
"numpy.sin",
"nanocut.output.error",
"numpy.arange",
"numpy.greater",
"numpy.less",
"numpy.cross",
"numpy.dot",
"numpy.abs",
"numpy.eye",
"numpy.ones",
"numpy.cos",
"nu... | [((945, 968), 'numpy.prod', 'np.prod', (['miller_nonzero'], {}), '(miller_nonzero)\n', (952, 968), True, 'import numpy as np\n'), ((1061, 1088), 'numpy.zeros', 'np.zeros', (['(2, 3)'], {'dtype': 'int'}), '((2, 3), dtype=int)\n', (1069, 1088), True, 'import numpy as np\n'), ((3785, 3812), 'numpy.zeros', 'np.zeros', (['(... |
#! /usr/bin/env python3
import numpy as np
from sklearn.neighbors import NearestNeighbors
from computeNeighborWeights import computeNeighborWeights
from computeWeightedMRecons import computeWeightedMRecons
from computeFeatures import computeFeatures
def computeFullERD(MeasuredValues,MeasuredIdxs,UnMeasuredIdxs,Theta,S... | [
"numpy.sqrt",
"numpy.logical_and",
"numpy.where",
"numpy.delete",
"computeNeighborWeights.computeNeighborWeights",
"computeFeatures.computeFeatures",
"numpy.max",
"numpy.zeros",
"computeWeightedMRecons.computeWeightedMRecons",
"sklearn.neighbors.NearestNeighbors",
"numpy.min"
] | [((690, 884), 'computeFeatures.computeFeatures', 'computeFeatures', (['MeasuredValues', 'MeasuredIdxs', 'UnMeasuredIdxs', 'SizeImage', 'NeighborValues', 'NeighborWeights', 'NeighborDistances', 'TrainingInfo', 'ReconValues', 'ReconImage', 'Resolution', 'ImageType'], {}), '(MeasuredValues, MeasuredIdxs, UnMeasuredIdxs, S... |
from keras.models import Sequential
from keras.layers import Dense
from sklearn.cross_validation import StratifiedKFold
import numpy as np
# init seed
seed = 7
np.random.seed(seed)
# load data (CSV)
dataset = np.loadtxt('pima-indians-diabetes.data', delimiter=',')
# split in put and output
X = dataset[:, 0:8]
Y = da... | [
"numpy.mean",
"keras.models.Sequential",
"sklearn.cross_validation.StratifiedKFold",
"numpy.random.seed",
"numpy.std",
"keras.layers.Dense",
"numpy.loadtxt"
] | [((161, 181), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (175, 181), True, 'import numpy as np\n'), ((211, 266), 'numpy.loadtxt', 'np.loadtxt', (['"""pima-indians-diabetes.data"""'], {'delimiter': '""","""'}), "('pima-indians-diabetes.data', delimiter=',')\n", (221, 266), True, 'import numpy as ... |
import numpy as np
import tensorflow as tf
from PIL import Image
import os
from crawl_HHU.cfg import MAX_CAPTCHA, CHAR_SET_LEN, model_path
from crawl_HHU.cnn_sys import crack_captcha_cnn, X, keep_prob
from crawl_HHU.utils import vec2text, get_clear_bin_image
def hack_function(sess, predict, captcha_image):
"""
... | [
"tensorflow.Session",
"tensorflow.train.Saver",
"crawl_HHU.utils.vec2text",
"numpy.array",
"numpy.zeros",
"crawl_HHU.cnn_sys.crack_captcha_cnn",
"tensorflow.reshape",
"tensorflow.train.latest_checkpoint",
"crawl_HHU.utils.get_clear_bin_image"
] | [((566, 602), 'numpy.zeros', 'np.zeros', (['(MAX_CAPTCHA * CHAR_SET_LEN)'], {}), '(MAX_CAPTCHA * CHAR_SET_LEN)\n', (574, 602), True, 'import numpy as np\n'), ((699, 715), 'crawl_HHU.utils.vec2text', 'vec2text', (['vector'], {}), '(vector)\n', (707, 715), False, 'from crawl_HHU.utils import vec2text, get_clear_bin_image... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.linear_model import ... | [
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.show",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.balanced_accuracy_score",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.ensemble.RandomForestClassifier",
"sklearn... | [((2282, 2336), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)', 'random_state': '(42)'}), '(X, y, test_size=0.3, random_state=42)\n', (2298, 2336), False, 'from sklearn.model_selection import train_test_split\n'), ((2408, 2443), 'sklearn.neighbors.KNeighborsClassifier... |
import random
import gym
from gym import Env, logger, spaces
import numpy as np
np.random.seed(0)
class MultiArmedBanditEnv(Env):
def __init__(self, n=3, info={}):
"""
n - number of arms in the bandit
"""
self.num_bandits = n
self.action_space = spaces.Discrete(self.num_ba... | [
"numpy.random.random",
"gym.spaces.Discrete",
"numpy.random.seed",
"numpy.random.uniform"
] | [((81, 98), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (95, 98), True, 'import numpy as np\n'), ((293, 326), 'gym.spaces.Discrete', 'spaces.Discrete', (['self.num_bandits'], {}), '(self.num_bandits)\n', (308, 326), False, 'from gym import Env, logger, spaces\n'), ((360, 378), 'gym.spaces.Discrete', ... |
# -*- coding: utf-8 -*-
from autograd.blocks.trigo import sin
from autograd.blocks.trigo import cos
from autograd.blocks.trigo import tan
from autograd.blocks.trigo import arcsin
from autograd.blocks.trigo import arccos
from autograd.blocks.trigo import arctan
from autograd.variable import Variable
import numpy as np
i... | [
"autograd.blocks.trigo.arcsin",
"numpy.tan",
"numpy.arccos",
"numpy.sqrt",
"numpy.random.random",
"autograd.blocks.trigo.cos",
"numpy.arcsin",
"autograd.blocks.trigo.arccos",
"numpy.diag",
"autograd.blocks.trigo.sin",
"autograd.set_mode",
"autograd.blocks.trigo.tan",
"numpy.equal",
"numpy.... | [((370, 392), 'autograd.set_mode', 'ad.set_mode', (['"""forward"""'], {}), "('forward')\n", (381, 392), True, 'import autograd as ad\n'), ((592, 611), 'numpy.random.random', 'np.random.random', (['(5)'], {}), '(5)\n', (608, 611), True, 'import numpy as np\n'), ((618, 632), 'autograd.variable.Variable', 'Variable', (['d... |
#!/usr/bin/env python
"""
Converts the 3D simulation data from carpet output (for every Node, that for every
variable name creates a list of .h5 files) into a single profile.h5 for a given iteration using `scidata`.
options:
-i : str : path to the simulation dir that contains `output-xxxx` directo... | [
"numpy.log10",
"scidata.units.conv_dens",
"numpy.array",
"scidata.utils.locate",
"scidata.units.conv_press",
"argparse.ArgumentParser",
"scipy.interpolate.RegularGridInterpolator",
"numpy.delete",
"config.get_eos_fname_from_curr_dir",
"os.path.isdir",
"numpy.vstack",
"os.mkdir",
"glob.glob",... | [((24415, 24432), 'numpy.array', 'np.array', (['it_time'], {}), '(it_time)\n', (24423, 24432), True, 'import numpy as np\n'), ((25294, 25314), 'scidata.carpet.hdf5.dataset', 'h5.dataset', (['files[0]'], {}), '(files[0])\n', (25304, 25314), True, 'import scidata.carpet.hdf5 as h5\n'), ((26901, 26922), 'os.path.isdir', '... |
'''
Plotting tools relevant for illustrating and comparing clustering results
can be found in this module.
'''
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def scatter_plot_two_dim_group_data(
two_dim_data,
labels,
markers=None,
colors=None,
figsize=(1... | [
"pandas.Series",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure",
"numpy.linspace",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.... | [((3189, 3216), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (3199, 3216), True, 'import matplotlib.pyplot as plt\n'), ((3226, 3242), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (3237, 3242), True, 'import matplotlib.pyplot as plt\n'), ((4052... |
#! /usr/bin/env python
import numpy as np
import pandas as pd
from math import log, exp
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
if __name__ == '__main__':
data = pd.read_csv("laurent_coeffs_2_511.csv", sep=',\s+')
odd_numerators = data['numerator'][1::2]
even_numer... | [
"math.exp",
"numpy.reshape",
"sklearn.linear_model.LinearRegression",
"pandas.read_csv"
] | [((209, 261), 'pandas.read_csv', 'pd.read_csv', (['"""laurent_coeffs_2_511.csv"""'], {'sep': '""",\\\\s+"""'}), "('laurent_coeffs_2_511.csv', sep=',\\\\s+')\n", (220, 261), True, 'import pandas as pd\n'), ((368, 386), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (384, 386), False, 'fro... |
# -*- coding: utf-8 -*-
# TODO Licence:
#
# TODO: move library intensive functions to vtool
from __future__ import absolute_import, division, print_function, unicode_literals
import operator
import six
from six.moves import zip, range, reduce
from utool import util_type
from utool import util_inject
from utool import ... | [
"numpy.prod",
"six.moves.range",
"pgmpy.factors.TabularCPD",
"pgmpy.inference.VariableElimination",
"networkx.pydot_layout",
"six.moves.zip",
"plottool.gca",
"networkx.DiGraph",
"numpy.random.randint",
"numpy.linspace",
"pgmpy.models.BayesianModel",
"pandas.DataFrame",
"utool.util_inject.inj... | [((593, 622), 'utool.util_inject.inject2', 'util_inject.inject2', (['__name__'], {}), '(__name__)\n', (612, 622), False, 'from utool import util_inject\n'), ((8392, 8418), 'pgmpy.models.BayesianModel', 'BayesianModel', (['input_graph'], {}), '(input_graph)\n', (8405, 8418), False, 'from pgmpy.models import BayesianMode... |
from projects.fa.transform import Transform
from config import cfg
import numpy as np
import cv2
from xvision.utils.draw import draw_bbox, draw_points
from transform import *
from xvision.datasets.wflw import WFLW
label = '/Users/jimmy/Documents/data/WFLW/WFLW_annotations/list_98pt_rect_attr_train_test/list_98pt_re... | [
"xvision.utils.draw.draw_points",
"numpy.ones",
"projects.fa.transform.Transform",
"cv2.line",
"xvision.utils.draw.draw_bbox",
"cv2.imshow",
"numpy.array",
"cv2.waitKey",
"xvision.datasets.wflw.WFLW"
] | [((402, 420), 'xvision.datasets.wflw.WFLW', 'WFLW', (['label', 'image'], {}), '(label, image)\n', (406, 420), False, 'from xvision.datasets.wflw import WFLW\n'), ((426, 498), 'projects.fa.transform.Transform', 'Transform', (['cfg.dsize', 'cfg.padding', 'cfg.data.meanshape', 'cfg.data.meanbbox'], {}), '(cfg.dsize, cfg.p... |
from Node import Node
from Factor import Factor
from FactorGeneric import FactorGeneric
from TraitPrior import TraitPrior
import utils
import numpy as np
import settings
###############
# #
# [F] #
# / \ #
# (A)...(A) #
# #
###############
def pbpdf(probin):
c = FactorPri... | [
"numpy.fft.fft",
"numpy.exp",
"numpy.array",
"numpy.dot",
"numpy.outer",
"numpy.full",
"numpy.log1p",
"numpy.arange"
] | [((339, 362), 'numpy.outer', 'np.outer', (['probin', '(c - 1)'], {}), '(probin, c - 1)\n', (347, 362), True, 'import numpy as np\n'), ((409, 422), 'numpy.exp', 'np.exp', (['p_log'], {}), '(p_log)\n', (415, 422), True, 'import numpy as np\n'), ((380, 391), 'numpy.log1p', 'np.log1p', (['p'], {}), '(p)\n', (388, 391), Tru... |
from __future__ import print_function
import argparse
import os
import random
import sys
sys.path.append(os.getcwd())
import pdb
import time
import numpy as np
import json
import progressbar
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudn... | [
"misc.utils.adjust_learning_rate",
"torch.LongTensor",
"misc.dataLoader.validate",
"numpy.array",
"torch.cuda.is_available",
"misc.dataLoader.train",
"misc.netG._netG",
"argparse.ArgumentParser",
"misc.utils.repackage_hidden",
"misc.model._netW",
"torch.autograd.Variable",
"random.randint",
... | [((773, 798), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (796, 798), False, 'import argparse\n'), ((3622, 3646), 'random.randint', 'random.randint', (['(1)', '(10000)'], {}), '(1, 10000)\n', (3636, 3646), False, 'import random\n'), ((3698, 3725), 'random.seed', 'random.seed', (['opt.manualS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Package: mesxr.calibration
Module: utilities
Author: <NAME>, <NAME>
Affiliation: Department of Physics, University of Wisconsin-Madison
Last Updated: November 2018
Description:
This module contains a number of auxilary functions for the main timscan.py module to
... | [
"os.path.join",
"numpy.array",
"numpy.empty",
"tifffile.imread"
] | [((1970, 2012), 'numpy.empty', 'np.empty', (['[M_SIZE_X, M_SIZE_Y, M_NUM_TRIM]'], {}), '([M_SIZE_X, M_SIZE_Y, M_NUM_TRIM])\n', (1978, 2012), True, 'import numpy as np\n'), ((4560, 4607), 'numpy.array', 'np.array', (['[energies[elem] for elem in elements]'], {}), '([energies[elem] for elem in elements])\n', (4568, 4607)... |
#!/usr/bin/env python
import numpy as np
from tqdm import tqdm
from astropy.constants import G as Ggrav
from .low_level_utils import fast_dist
G = Ggrav.to('kpc Msun**-1 km**2 s**-2').value
def all_profiles(bins, positions, velocities, masses, two_dimensional=False, zcut=None,
ages=None, pbar_msg=... | [
"numpy.sqrt",
"numpy.arccos",
"numpy.linalg.norm",
"numpy.sin",
"numpy.cross",
"numpy.isscalar",
"numpy.sort",
"numpy.empty",
"utilities.particle.parse_species",
"numpy.vstack",
"numpy.logspace",
"numpy.abs",
"astropy.constants.G.to",
"numpy.average",
"utilities.particle.parse_property",... | [((150, 186), 'astropy.constants.G.to', 'Ggrav.to', (['"""kpc Msun**-1 km**2 s**-2"""'], {}), "('kpc Msun**-1 km**2 s**-2')\n", (158, 186), True, 'from astropy.constants import G as Ggrav\n'), ((1697, 1716), 'numpy.empty', 'np.empty', (['bins.size'], {}), '(bins.size)\n', (1705, 1716), True, 'import numpy as np\n'), ((... |
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np
import seaborn as sns
from msax.msax import paa
from mpl_toolkits.mplot3d import Axes3D
def ts_with_hist(x, fig=None, bins=50):
"""
Visualizes the input x time series with its histogram.
:param x: Input array
:param fi... | [
"numpy.repeat",
"matplotlib.tri.Triangulation",
"seaborn.heatmap",
"msax.msax.paa",
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.figure",
"numpy.nanmin",
"numpy.nanmax",
"numpy.ravel",
"matplotlib.pyplot.subplot2grid"
] | [((511, 576), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['gridsize', '(0, 0)'], {'colspan': '(2)', 'rowspan': '(1)', 'fig': 'fig'}), '(gridsize, (0, 0), colspan=2, rowspan=1, fig=fig)\n', (527, 576), True, 'import matplotlib.pyplot as plt\n'), ((587, 630), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2gri... |
#!/usr/bin/env python
# encoding: utf-8
r"""
One-dimensional advection
=========================
Solve the linear advection equation on a nonuniform grid:
.. math::
q_t + u q_x = 0.
Here q is the density of some conserved quantity and u is the velocity.
Here we have a nonuniform grid, given by the transformatio... | [
"clawpack.petclaw.Dimension",
"clawpack.petclaw.ClawSolver1D",
"clawpack.pyclaw.util.run_app_from_main",
"clawpack.petclaw.State",
"numpy.diff",
"clawpack.petclaw.Domain",
"numpy.exp",
"numpy.zeros",
"clawpack.petclaw.Solution",
"numpy.cos",
"clawpack.petclaw.Controller"
] | [((2094, 2135), 'clawpack.petclaw.Dimension', 'pyclaw.Dimension', (['(-0.5)', '(0.5)', 'nx'], {'name': '"""x"""'}), "(-0.5, 0.5, nx, name='x')\n", (2110, 2135), True, 'import clawpack.petclaw as pyclaw\n'), ((2146, 2162), 'clawpack.petclaw.Domain', 'pyclaw.Domain', (['x'], {}), '(x)\n', (2159, 2162), True, 'import claw... |
import math
import array
import random
import numpy as np
from deap import base
from deap import creator
from deap import tools
from deap.benchmarks.tools import diversity, convergence, hypervolume
class PSO():
def __init__(self, dim, boundary, population=5, gen=1000, minimization=True, func=None):
# POT... | [
"deap.creator.Particle",
"deap.benchmarks.tools.hypervolume",
"deap.creator.create",
"deap.tools.Logbook",
"math.copysign",
"numpy.array",
"numpy.random.uniform",
"random.random",
"deap.tools.Statistics",
"deap.base.Toolbox"
] | [((794, 829), 'numpy.random.uniform', 'np.random.uniform', (['smin', 'smax', 'size'], {}), '(smin, smax, size)\n', (811, 829), True, 'import numpy as np\n'), ((2284, 2298), 'deap.base.Toolbox', 'base.Toolbox', ([], {}), '()\n', (2296, 2298), False, 'from deap import base\n'), ((2729, 2777), 'deap.tools.Statistics', 'to... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = 'Justin'
__mtime__ = '2018-06-02'
"""
import numpy as np
from skimage import color, morphology
from skimage.morphology import square
import os
import pandas as pd
def get_seeds(MaskLow, lowScale, highScale, patch_size_high, spacingHigh, margin = -8):
... | [
"os.listdir",
"skimage.morphology.square",
"os.path.splitext",
"os.getcwd",
"numpy.rint",
"pandas.DataFrame",
"os.remove"
] | [((2675, 2697), 'os.listdir', 'os.listdir', (['search_dir'], {}), '(search_dir)\n', (2685, 2697), False, 'import os\n'), ((3113, 3182), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['filename', 'epoch', 'loss', 'accuracy']"}), "(data, columns=['filename', 'epoch', 'loss', 'accuracy'])\n", (3125, 3182), T... |
import os
import gym
from brl_gym.envs.mujoco.model_updater import MujocoUpdater
from gym import error
from gym.utils import seeding
import numpy as np
from os import path
import gym
import six
import time as timer
from gym import spaces
try:
import mujoco_py
from mujoco_py import load_model_from_path, load_... | [
"numpy.clip",
"mujoco_py.MjViewer",
"mujoco_py.MjRenderContextOffscreen",
"gym.utils.seeding.np_random",
"mujoco_py.MjSim",
"os.path.exists",
"mujoco_py.load_model_from_path",
"numpy.asarray",
"brl_gym.envs.mujoco.model_updater.MujocoUpdater.set_params",
"numpy.concatenate",
"mujoco_py.load_mode... | [((1135, 1165), 'mujoco_py.load_model_from_path', 'load_model_from_path', (['fullpath'], {}), '(fullpath)\n', (1155, 1165), False, 'from mujoco_py import load_model_from_path, load_model_from_xml, MjSim, MjViewer\n'), ((1474, 1491), 'mujoco_py.MjSim', 'MjSim', (['self.model'], {}), '(self.model)\n', (1479, 1491), False... |
#!/usr/bin/env python3
import argparse
import os
import os.path as path
import numpy as np
import tensorflow as tf
from mobilenet.dataset import imagenet
def main(args):
tf.random.set_seed(0)
if not path.isdir(args.examples_dir):
os.makedirs(args.examples_dir)
data, _ = imagenet(args.split, tu... | [
"tensorflow.image.convert_image_dtype",
"tensorflow.random.set_seed",
"os.makedirs",
"argparse.ArgumentParser",
"numpy.argmax",
"os.path.isdir",
"tensorflow.io.encode_jpeg"
] | [((179, 200), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(0)'], {}), '(0)\n', (197, 200), True, 'import tensorflow as tf\n'), ((754, 854), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter', 'add_help': '(False)'}), '(formatter_class=argpa... |
# -*- coding: utf-8 -*-
'''
Standard Dynamic Energy Budget model
'''
import numpy as np
import pandas as pd
import scipy.integrate as sid
import lmfit
import matplotlib.pyplot as plt
import seaborn as sns
import corner
from tqdm import tqdm
from collections import namedtuple
from lossfunc import symmetric_loss_functio... | [
"numpy.ones",
"pandas.DataFrame",
"tqdm.tqdm",
"lossfunc.symmetric_loss_function",
"deb_aux.physical_volume",
"numpy.exp",
"numpy.array",
"numpy.zeros",
"numpy.finfo",
"numpy.cbrt",
"scipy.integrate.ode",
"lmfit.Parameters",
"matplotlib.pyplot.subplots"
] | [((365, 384), 'numpy.finfo', 'np.finfo', (['np.double'], {}), '(np.double)\n', (373, 384), True, 'import numpy as np\n'), ((903, 989), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Min', 'Max', 'Value', 'Dimension', 'Units', 'Description']"}), "(columns=['Min', 'Max', 'Value', 'Dimension', 'Units',\n 'Desc... |
import numpy as np
from itertools import chain, islice, product, repeat, cycle, izip
from fos.actor.surf import CommonSurfaceGroup, IlluminatedSurfaceGroup
from fos.core.world import World
from fos.lib.pyglet.gl import *
from fos.lib.pyglet.graphics import Batch
from fos.core.actor import Actor
from fos.geometry.ve... | [
"itertools.chain",
"numpy.eye",
"itertools.cycle",
"numpy.array",
"itertools.chain.from_iterable",
"fos.geometry.vec3.Vec3",
"itertools.izip",
"itertools.repeat"
] | [((1850, 1922), 'itertools.chain.from_iterable', 'chain.from_iterable', (['(vertices[index] for face in faces for index in face)'], {}), '(vertices[index] for face in faces for index in face)\n', (1869, 1922), False, 'from itertools import chain, islice, product, repeat, cycle, izip\n'), ((6900, 6909), 'numpy.eye', 'np... |
from pyAudioAnalysis import audioFeatureExtraction
from keras.preprocessing import sequence
from scipy import stats
import numpy as np
import cPickle
import sys
import globalvars
def feature_extract(data, nb_samples, dataset, save=True):
f_global = []
i = 0
for (x, Fs) in data:
# 34D short-term ... | [
"numpy.argmax",
"numpy.sum",
"numpy.zeros",
"scipy.stats.zscore",
"pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction",
"pyAudioAnalysis.audioFeatureExtraction.stFeatureSpeed",
"keras.preprocessing.sequence.pad_sequences",
"sys.stdout.write"
] | [((927, 1037), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['f_global'], {'maxlen': 'globalvars.max_len', 'dtype': '"""float64"""', 'padding': '"""post"""', 'value': '(-100.0)'}), "(f_global, maxlen=globalvars.max_len, dtype='float64',\n padding='post', value=-100.0)\n", (949, 1037), Fal... |
import numpy as np
import math
from os import path
import imageio
from datetime import date
def convertCSVtoImage(Filepath, FileFormat):
supportedFileFormats = ["png","jpeg","jpg","bmp"]
if not FileFormat in supportedFileFormats:
raise ValueError("Outputformat {} is not supported! The following are al... | [
"imageio.imwrite",
"math.floor",
"os.path.splitext",
"numpy.ndindex",
"os.path.isfile",
"numpy.array",
"numpy.zeros",
"imageio.imread",
"datetime.date.today"
] | [((1834, 1873), 'imageio.imwrite', 'imageio.imwrite', (['outputPath', 'imageArray'], {}), '(outputPath, imageArray)\n', (1849, 1873), False, 'import imageio\n'), ((2558, 2582), 'imageio.imread', 'imageio.imread', (['Filepath'], {}), '(Filepath)\n', (2572, 2582), False, 'import imageio\n'), ((395, 416), 'os.path.isfile'... |
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
#Run Cell
x = np.linspace(0, 20, 100)
plt.plot(x, np.sin(x))
plt.show() | [
"numpy.sin",
"numpy.linspace",
"matplotlib.pyplot.show"
] | [((91, 114), 'numpy.linspace', 'np.linspace', (['(0)', '(20)', '(100)'], {}), '(0, 20, 100)\n', (102, 114), True, 'import numpy as np\n'), ((138, 148), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (146, 148), True, 'import matplotlib.pyplot as plt\n'), ((127, 136), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n'... |
import math
import numpy as np
import tvm
from tvm.tir import IterVar
from .hw_abs_dag import construct_dag
from itertools import permutations, product
from functools import reduce
from . import _ffi_api
####################################################
# schedule parameter functions
##############################... | [
"math.ceil",
"functools.reduce",
"itertools.product",
"math.sqrt",
"numpy.max"
] | [((427, 443), 'math.sqrt', 'math.sqrt', (['value'], {}), '(value)\n', (436, 443), False, 'import math\n'), ((3913, 3977), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', '[nodes[x] for x in output_names]', '[]'], {}), '(lambda x, y: x + y, [nodes[x] for x in output_names], [])\n', (3919, 3977), False, 'from fun... |
# (C) Copyright 1996- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernment... | [
"numpy.load",
"matplotlib.pyplot.savefig",
"cartopy.crs.PlateCarree"
] | [((794, 818), 'matplotlib.pyplot.savefig', 'plt.savefig', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (805, 818), True, 'import matplotlib.pyplot as plt\n'), ((860, 880), 'numpy.load', 'np.load', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (867, 880), True, 'import numpy as np\n'), ((625, 643), 'cartopy.crs.PlateCarree', '... |
import time
import numpy
from ..Instruments import EG_G_7265
#from ..Instruments import SRS_SR830
from ..UserInterfaces.Loggers import NullLogger
class VSMController2(object):
#Controlador y sensor del VSM
def __init__(self, Logger = None):
self.LockIn = EG_G_7265(RemoteOnly = False)
... | [
"numpy.abs",
"time.sleep",
"numpy.append",
"numpy.array",
"numpy.zeros"
] | [((1316, 1330), 'time.sleep', 'time.sleep', (['(15)'], {}), '(15)\n', (1326, 1330), False, 'import time\n'), ((1575, 1588), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1585, 1588), False, 'import time\n'), ((1864, 1878), 'numpy.zeros', 'numpy.zeros', (['n'], {}), '(n)\n', (1875, 1878), False, 'import numpy\n')... |
from collections import defaultdict
class Graph:
def __init__(self,graph):
self.graph = graph # residual graph
self. ROW = len(graph)
def BFS(self,s, t, parent):
# Mark all the vertices as not visited
visited =[False]*(self.ROW)
queue=[]
... | [
"timeit.default_timer",
"numpy.loadtxt"
] | [((1588, 1610), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (1608, 1610), False, 'import timeit\n'), ((1664, 1686), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (1684, 1686), False, 'import timeit\n'), ((1490, 1513), 'numpy.loadtxt', 'np.loadtxt', (['"""file1.txt"""'], {}), "(... |
import os
from timemachines.skaters.localskaters import local_skater_from_name
from timemachines.skating import prior
import numpy as np
if __name__=='__main__':
from timemachines.skaters.sk.skinclusion import using_sktime
assert using_sktime
skater_name = __file__.split(os.path.sep)[-1].replace('test_skat... | [
"timemachines.skating.prior",
"numpy.random.randn",
"timemachines.skaters.localskaters.local_skater_from_name"
] | [((380, 415), 'timemachines.skaters.localskaters.local_skater_from_name', 'local_skater_from_name', (['skater_name'], {}), '(skater_name)\n', (402, 415), False, 'from timemachines.skaters.localskaters import local_skater_from_name\n'), ((449, 469), 'numpy.random.randn', 'np.random.randn', (['(100)'], {}), '(100)\n', (4... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 14:29:29 2021
@author: surajitrana
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_piechart():
dataset = np.array([20, 25, 10, 15, 30])
chart_lables = np.array(["Audi", "Mercedez", "BMW", "Tesla", "Volvo"])
chart_ex... | [
"numpy.array",
"matplotlib.pyplot.pie",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((202, 232), 'numpy.array', 'np.array', (['[20, 25, 10, 15, 30]'], {}), '([20, 25, 10, 15, 30])\n', (210, 232), True, 'import numpy as np\n'), ((252, 307), 'numpy.array', 'np.array', (["['Audi', 'Mercedez', 'BMW', 'Tesla', 'Volvo']"], {}), "(['Audi', 'Mercedez', 'BMW', 'Tesla', 'Volvo'])\n", (260, 307), True, 'import ... |
'''
Thermodynamic helper functions.
'''
from __future__ import division, print_function, absolute_import
import numpy as np
# Saturation vapor pressure from the Clausius-Clapeyron relation.
# --> assumes L is constant with temperature!
def get_satvps(T,T0,e0,Rv,Lv):
return e0*np.exp(-(Lv/Rv)*(1./T - 1./T0))
# -... | [
"numpy.exp"
] | [((283, 324), 'numpy.exp', 'np.exp', (['(-(Lv / Rv) * (1.0 / T - 1.0 / T0))'], {}), '(-(Lv / Rv) * (1.0 / T - 1.0 / T0))\n', (289, 324), True, 'import numpy as np\n')] |
import json
import os
import sys
import albumentations as A
import numpy as np
import pandas as pd
import timm
import torch
import ttach as tta
from albumentations.augmentations.geometric.resize import Resize
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader
from tqdm import ... | [
"missed_planes.dataset.PlanesDataset",
"pandas.read_csv",
"torch.load",
"os.path.join",
"numpy.array",
"albumentations.Resize",
"torch.utils.data.DataLoader",
"json.load",
"torch.no_grad",
"ttach.aliases.d4_transform"
] | [((655, 686), 'pandas.read_csv', 'pd.read_csv', (["config['test_csv']"], {}), "(config['test_csv'])\n", (666, 686), True, 'import pandas as pd\n'), ((703, 796), 'missed_planes.dataset.PlanesDataset', 'PlanesDataset', (['test_data'], {'path': "config['test_path']", 'is_test': '(True)', 'augmentation': 'transforms'}), "(... |
import torch
import torch.nn as nn
from collections import OrderedDict
import numpy as np
from .. import util
class LinearBlock(nn.Module):
def __init__(self, linear_dim, output_dim, init_type='std'):
super().__init__()
modules = []
for i in range(8):
if i == 0:
... | [
"matplotlib.pyplot.imshow",
"collections.OrderedDict",
"torch.nn.LeakyReLU",
"torch.nn.ModuleList",
"matplotlib.pyplot.colorbar",
"torch.nn.Conv2d",
"torch.nn.InstanceNorm2d",
"matplotlib.pyplot.figure",
"torch.nn.Upsample",
"torch.nn.Linear",
"torch.zeros",
"numpy.log2",
"torch.Size",
"to... | [((1197, 1232), 'torch.nn.Linear', 'nn.Linear', (['latent_dim', '(channels * 2)'], {}), '(latent_dim, channels * 2)\n', (1206, 1232), True, 'import torch.nn as nn\n'), ((2153, 2213), 'torch.nn.Conv2d', 'nn.Conv2d', (['channels', 'channels'], {'kernel_size': '(3, 3)', 'padding': '(0)'}), '(channels, channels, kernel_siz... |
from os import listdir
import json
import numpy as np
DATA_DIR="quickdraw_data_reduced"
def parse_line(ndjson_line):
"""Parse an ndjson line and return ink (as np array) and classname."""
sample = json.loads(ndjson_line)
class_name = sample["word"]
if not class_name:
print ("Empty classname")
return N... | [
"json.loads",
"os.listdir",
"numpy.max",
"numpy.zeros",
"numpy.min",
"numpy.save"
] | [((1620, 1639), 'numpy.save', 'np.save', (['"""X.npy"""', 'X'], {}), "('X.npy', X)\n", (1627, 1639), True, 'import numpy as np\n'), ((1640, 1659), 'numpy.save', 'np.save', (['"""Y.npy"""', 'Y'], {}), "('Y.npy', Y)\n", (1647, 1659), True, 'import numpy as np\n'), ((203, 226), 'json.loads', 'json.loads', (['ndjson_line']... |
# Collection of preprocessing functions
from nltk.tokenize import word_tokenize
from transformers import CamembertTokenizer
from transformers import BertTokenizer
from tqdm import tqdm
import numpy as np
import pandas as pd
import re
import string
import unicodedata
import tensorflow as tf
import glob
i... | [
"re.escape",
"pandas.read_csv",
"tensorflow.io.read_file",
"tensorflow.cast",
"os.remove",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.asarray",
"unicodedata.normalize",
"pandas.DataFrame",
"glob.glob",
"numpy.squeeze",
"tensorflow.io.decode_jpeg",
"re.sub",
"tensorflow.image.resi... | [((502, 563), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['model_bert'], {'do_lowercase': '(False)'}), '(model_bert, do_lowercase=False)\n', (531, 563), False, 'from transformers import BertTokenizer\n'), ((581, 652), 'transformers.CamembertTokenizer.from_pretrained', 'CamembertToke... |
import argparse
import asyncio
import logging
import math
import os
import cv2
import numpy
from aiortc import RTCPeerConnection
from aiortc.mediastreams import VideoFrame, VideoStreamTrack
from signaling import CopyAndPasteSignaling
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
OUTPUT_PATH = os.path.joi... | [
"logging.basicConfig",
"cv2.imwrite",
"math.ceil",
"signaling.CopyAndPasteSignaling",
"argparse.ArgumentParser",
"numpy.hstack",
"asyncio.gather",
"os.path.dirname",
"numpy.zeros",
"cv2.cvtColor",
"asyncio.sleep",
"numpy.frombuffer",
"asyncio.get_event_loop",
"aiortc.RTCPeerConnection"
] | [((322, 347), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (337, 347), False, 'import os\n'), ((410, 456), 'cv2.cvtColor', 'cv2.cvtColor', (['data_bgr', 'cv2.COLOR_BGR2YUV_YV12'], {}), '(data_bgr, cv2.COLOR_BGR2YUV_YV12)\n', (422, 456), False, 'import cv2\n'), ((598, 639), 'numpy.frombuffer... |
import pymongo
import datetime
import os
import numpy as np
import struct
from array import array
from pymongo import MongoClient
from mspasspy.ccore.seismic import (
Seismogram,
TimeReferenceType,
TimeSeries,
DoubleVector,
)
def find_channel(collection):
st = datetime.datetime(1990, 1, 1, 6)
... | [
"datetime.datetime",
"mspasspy.ccore.seismic.TimeSeries",
"array.array",
"numpy.random.rand",
"os.path.join",
"os.path.realpath",
"os.path.dirname",
"mspasspy.ccore.seismic.DoubleVector"
] | [((283, 315), 'datetime.datetime', 'datetime.datetime', (['(1990)', '(1)', '(1)', '(6)'], {}), '(1990, 1, 1, 6)\n', (300, 315), False, 'import datetime\n'), ((325, 357), 'datetime.datetime', 'datetime.datetime', (['(1990)', '(1)', '(4)', '(6)'], {}), '(1990, 1, 4, 6)\n', (342, 357), False, 'import datetime\n'), ((577, ... |
# Copyright 2018 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... | [
"SimpleITK.BinaryThresholdImageFilter",
"torch.Tensor",
"SimpleITK.ResampleImageFilter",
"multiprocessing.cpu_count",
"SimpleITK.BinaryMorphologicalClosingImageFilter",
"numpy.array",
"SimpleITK.MaskImageFilter",
"SimpleITK.BinaryMorphologicalOpeningImageFilter"
] | [((730, 744), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (742, 744), True, 'import multiprocessing as mp\n'), ((3801, 3821), 'numpy.array', 'np.array', (['image.size'], {}), '(image.size)\n', (3809, 3821), True, 'import numpy as np\n'), ((4018, 4044), 'SimpleITK.ResampleImageFilter', 'sitk.ResampleI... |
from threading import Lock
from flask import Flask, render_template, session, request, \
copy_current_request_context
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
from keras.models import load_model
import tensorflow as tf
import numpy as np
from vggish_input... | [
"flask.render_template",
"wget.download",
"numpy.mean",
"vggish_input.waveform_to_examples",
"keras.models.load_model",
"pathlib.Path",
"flask.Flask",
"threading.Lock",
"numpy.argmax",
"flask_socketio.SocketIO",
"numpy.take",
"helpers.dbFS",
"numpy.fromstring",
"time.time",
"tensorflow.g... | [((680, 695), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (685, 695), False, 'from flask import Flask, render_template, session, request, copy_current_request_context\n'), ((744, 780), 'flask_socketio.SocketIO', 'SocketIO', (['app'], {'async_mode': 'async_mode'}), '(app, async_mode=async_mode)\n', (752,... |
from utils import *
import numpy as np
import h5py
import os
import pandas as pd
from PIL import Image
from tqdm import tqdm
def resize_images(image_list, im_size):
"""Resize a list of images to a given size.
Parameters
----------
image_list : list
A list of images to resize, in any format... | [
"PIL.Image.open",
"pandas.read_csv",
"tqdm.tqdm",
"os.path.join",
"h5py.File",
"numpy.array"
] | [((2489, 2546), 'pandas.read_csv', 'pd.read_csv', (["param['csv_train']"], {'names': "['label']", 'sep': '""";"""'}), "(param['csv_train'], names=['label'], sep=';')\n", (2500, 2546), True, 'import pandas as pd\n'), ((2566, 2621), 'pandas.read_csv', 'pd.read_csv', (["param['csv_val']"], {'names': "['label']", 'sep': '"... |
# # Chapter 5: Image Enhancement
# Author: <NAME>
###########################################
# ## Problems
# ### 1.1 BLUR Filter to remove Salt & Pepper Noise
get_ipython().run_line_magic('matplotlib', 'inline')
import numpy as np
import matplotlib.pylab as plt
from PIL import Image, ImageFilter
from copy impor... | [
"matplotlib.pylab.xlim",
"matplotlib.pylab.subplots",
"scipy.signal.convolve",
"numpy.ma.masked_equal",
"numpy.random.rand",
"scipy.ndimage.gaussian_laplace",
"matplotlib.pylab.hist",
"PIL.ImageDraw.Draw",
"matplotlib.pylab.imshow",
"numpy.array",
"matplotlib.pylab.show",
"copy.deepcopy",
"s... | [((927, 961), 'PIL.Image.open', 'Image.open', (['"""images/Img_05_01.jpg"""'], {}), "('images/Img_05_01.jpg')\n", (937, 961), False, 'from PIL import Image, ImageDraw\n'), ((968, 996), 'matplotlib.pylab.figure', 'plt.figure', ([], {'figsize': '(12, 35)'}), '(figsize=(12, 35))\n', (978, 996), True, 'import matplotlib.py... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.