code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# Image Class: Image.py
import numpy as np
import cv2
import pytesseract as tess
from scripts.align import *
import concurrent.futures as cf
class Img:
def __init__(self,name,data):
self._raw = data
self._name = name
self._scaled = scaleImg(self._raw)
self._gray = self.clahe... | [
"pytesseract.image_to_pdf_or_hocr",
"numpy.int_",
"cv2.putText",
"cv2.cvtColor",
"cv2.getStructuringElement",
"cv2.imwrite",
"cv2.dnn.blobFromImage",
"numpy.zeros",
"cv2.threshold",
"numpy.float32",
"cv2.getTextSize",
"cv2.rectangle",
"cv2.dnn.readNetFromCaffe",
"cv2.createCLAHE",
"cv2.d... | [((776, 806), 'numpy.zeros', 'np.zeros', (['data.shape', 'np.uint8'], {}), '(data.shape, np.uint8)\n', (784, 806), True, 'import numpy as np\n'), ((1124, 1179), 'cv2.drawContours', 'cv2.drawContours', (['canvas', 'cntsH', '(-1)', '(255, 255, 255)', '(1)'], {}), '(canvas, cntsH, -1, (255, 255, 255), 1)\n', (1140, 1179),... |
"""
Utility classes and methods for working with POM output.
The Princeton Ocean Modeling System (POM) is "a sigma coordinate (terrain-
following), free surface ocean model with embedded turbulence and wave
sub-models, and wet-dry capability." See http://www.ccpo.odu.edu/POMWEB/ for
more information.
This module prov... | [
"numpy.minimum",
"numpy.ma.compressed",
"thyme.util.interp.interpolate_to_regular_grid",
"osgeo.ogr.CreateGeometryFromWkt",
"osgeo.ogr.GetDriverByName",
"numpy.logical_not",
"numpy.nanmin",
"numpy.ma.empty",
"osgeo.ogr.FieldDefn",
"osgeo.ogr.Geometry",
"scipy.interpolate.interp1d",
"osgeo.osr.... | [((14364, 14413), 'numpy.ma.empty', 'numpy.ma.empty', ([], {'shape': '[num_sigma, num_ny, num_nx]'}), '(shape=[num_sigma, num_ny, num_nx])\n', (14378, 14413), False, 'import numpy\n'), ((15028, 15066), 'numpy.ma.empty', 'numpy.ma.empty', ([], {'shape': '[num_ny, num_nx]'}), '(shape=[num_ny, num_nx])\n', (15042, 15066),... |
from PIL import ImageFilter
import random
from jittor import transform
from PIL import Image
import numpy as np
import json
import random
import numpy as np
from PIL import Image
from jittor.dataset import Dataset
from os.path import join
from utils import retrieve_sub_names, get_suffix
class TwoCropsTransform:
d... | [
"PIL.ImageFilter.GaussianBlur",
"numpy.load",
"utils.get_suffix",
"random.uniform",
"jittor.transform.ToTensor",
"jittor.transform.RandomCropAndResize",
"jittor.transform.ImageNormalize",
"PIL.Image.open",
"utils.retrieve_sub_names",
"jittor.transform.RandomHorizontalFlip",
"os.path.join",
"ji... | [((804, 883), 'jittor.transform.ImageNormalize', 'transform.ImageNormalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (828, 883), False, 'from jittor import transform\n'), ((3401, 3433), 'utils.retrieve_sub_names', 'retrieve_su... |
# Generate look up tables for activation and activation derivative
# Output files from here used in sigmoid_sigmoidprime_table.v in dnn-rtl/src
# 'size' and 'maxdomain' here should match with 'lut_size' and 'maxdomain' in the RTL
# 'wordbits' is USUALLY equal to frac_bits in the RTL, but may be less
import numpy as np... | [
"numpy.log2",
"numpy.exp"
] | [((390, 400), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (396, 400), True, 'import numpy as np\n'), ((1458, 1476), 'numpy.log2', 'np.log2', (['maxdomain'], {}), '(maxdomain)\n', (1465, 1476), True, 'import numpy as np\n'), ((1531, 1544), 'numpy.log2', 'np.log2', (['size'], {}), '(size)\n', (1538, 1544), True, 'im... |
"""
..
Copyright (c) 2014-2017, Magni developers.
All rights reserved.
See LICENSE.rst for further information.
Module providing functionality for visualising images.
The module provides functionality for adjusting the intensity of an image. It
provides a wrapper of the `matplotlib.pyplot.imshow` function... | [
"magni.utils.plotting.setup_matplotlib",
"numpy.ones_like",
"numpy.amin",
"matplotlib.colors.Normalize",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.imshow",
"numpy.amax",
"numpy.ma.array",
"magni.utils.validation.validate_numeric",
"matplotlib.pyplot.sca",
"matplotlib.pyplot.subplots_adjust",
... | [((3843, 3871), 'magni.utils.plotting.setup_matplotlib', '_plotting.setup_matplotlib', ([], {}), '()\n', (3869, 3871), True, 'from magni.utils import plotting as _plotting\n'), ((3915, 3924), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3922, 3924), True, 'import matplotlib.pyplot as plt\n'), ((4192, 4201), '... |
import numpy as np
from . import random
class TransformationsGenerator:
def __init__(self, transforms, seed=0):
self.transforms = transforms
self.rs = np.random.RandomState(seed)
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
... | [
"numpy.random.RandomState"
] | [((173, 200), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (194, 200), True, 'import numpy as np\n')] |
import os
import numpy as np
from perform.constants import FD_STEP_DEFAULT
from perform.rom.projection_rom.projection_rom import ProjectionROM
from perform.input_funcs import catch_input
class AutoencoderProjROM(ProjectionROM):
"""Base class for all non-linear manifold projection-based ROMs using autoencoders.
... | [
"perform.input_funcs.catch_input",
"numpy.transpose",
"os.path.isfile",
"numpy.reshape",
"os.path.join"
] | [((3057, 3126), 'os.path.join', 'os.path.join', (['rom_domain.model_dir', 'rom_domain.model_files[model_idx]'], {}), '(rom_domain.model_dir, rom_domain.model_files[model_idx])\n', (3069, 3126), False, 'import os\n'), ((3142, 3170), 'os.path.isfile', 'os.path.isfile', (['decoder_path'], {}), '(decoder_path)\n', (3156, 3... |
"""
Use the benchmark graphs to test the performance of QAOA+
"""
import os, sys, argparse, glob
import numpy as np
from ansatz import qaoa_plus
import pickle, random
from utils.graph_funcs import *
from utils.helper_funcs import *
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-p','... | [
"sys.path.append",
"os.mkdir",
"pickle.dump",
"argparse.ArgumentParser",
"os.path.isdir",
"ansatz.qaoa_plus.solve_mis",
"ansatz.qaoa_plus.get_approximation_ratio",
"numpy.arange",
"glob.glob",
"ansatz.qaoa_plus.get_ranked_probs"
] | [((264, 289), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (287, 289), False, 'import os, sys, argparse, glob\n'), ((1590, 1615), 'sys.path.append', 'sys.path.append', (['DQVAROOT'], {}), '(DQVAROOT)\n', (1605, 1615), False, 'import os, sys, argparse, glob\n'), ((1634, 1666), 'glob.glob', 'gl... |
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace( 0, 0.1, 1000, endpoint = False ) # 定義時間陣列
f1 = 20 # 低頻頻率
f2 = 200 # 高頻頻率
x = np.cos( 2 * np.pi * f1 * t ) * np.cos( 2 * np.pi * f2 * t )
envelop1 = np.cos( 2 * np.pi * f1 * t ) # 包絡
envelop2 = -np.cos( 2 * np.pi * f1 * t )
p... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axis",
"numpy.cos",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((56, 97), 'numpy.linspace', 'np.linspace', (['(0)', '(0.1)', '(1000)'], {'endpoint': '(False)'}), '(0, 0.1, 1000, endpoint=False)\n', (67, 97), True, 'import numpy as np\n'), ((241, 267), 'numpy.cos', 'np.cos', (['(2 * np.pi * f1 * t)'], {}), '(2 * np.pi * f1 * t)\n', (247, 267), True, 'import numpy as np\n'), ((319,... |
import sys
import datetime
import numpy as np
from stock.utils.symbol_util import get_stock_symbols, get_realtime_by_date
from stock.marketdata.storefactory import get_store
from config import store_type
import pandas as pd
def print_stocks(date):
store = get_store(store_type)
exsymbols = store.get_stock_exsym... | [
"pandas.DataFrame",
"datetime.date.today",
"stock.marketdata.storefactory.get_store",
"numpy.argmin",
"numpy.min",
"numpy.max",
"pandas.set_option"
] | [((3367, 3406), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', 'None'], {}), "('display.max_rows', None)\n", (3380, 3406), True, 'import pandas as pd\n'), ((261, 282), 'stock.marketdata.storefactory.get_store', 'get_store', (['store_type'], {}), '(store_type)\n', (270, 282), False, 'from stock.market... |
"""Baseball Data Helper Functions"""
__author__ = '<NAME>'
import pandas as pd
import numpy as np
import re
import io
from pathlib import Path
import statsmodels.api as sm
from IPython.display import HTML, display
from sqlalchemy.types import SmallInteger, Integer, BigInteger, Float
def to_csv_with_types(df, filena... | [
"pandas.DataFrame",
"sqlalchemy.types.Float",
"io.StringIO",
"statsmodels.api.nonparametric.lowess",
"pandas.read_csv",
"numpy.iinfo",
"pathlib.Path",
"re.sub",
"IPython.display.HTML"
] | [((715, 729), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (719, 729), False, 'from pathlib import Path\n'), ((1212, 1226), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (1216, 1226), False, 'from pathlib import Path\n'), ((1486, 1563), 'pandas.read_csv', 'pd.read_csv', (['p'], {'parse_date... |
"""
Copyright 2018-2019 CS Systèmes d'Information
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... | [
"json.loads",
"ikats.core.resource.api.IkatsApi.md.update",
"logging.StreamHandler",
"time.time",
"logging.Formatter",
"ikats.core.resource.api.IkatsApi.md.read",
"numpy.array",
"ikats.core.resource.api.IkatsApi.ts.delete",
"numpy.float64",
"ikats.algo.quality_stats.quality_stats.calc_quality_stat... | [((1098, 1169), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s:%(levelname)s:%(funcName)s:%(message)s"""'], {}), "('%(asctime)s:%(levelname)s:%(funcName)s:%(message)s')\n", (1115, 1169), False, 'import logging\n'), ((1261, 1284), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1282, 12... |
import unittest
import numpy as np
from python_solutions.Google_6_09_2019_problem import is_toeplitz_matrix
class Google_6_09_2019_test(unittest.TestCase):
def test_example_1(self):
example = np.array(
[
[1, 2, 3, 4, 8],
[5, 1, 2, 3, 4],
[4, 5, ... | [
"numpy.array",
"python_solutions.Google_6_09_2019_problem.is_toeplitz_matrix"
] | [((207, 285), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 8], [5, 1, 2, 3, 4], [4, 5, 1, 2, 3], [7, 4, 5, 1, 2]]'], {}), '([[1, 2, 3, 4, 8], [5, 1, 2, 3, 4], [4, 5, 1, 2, 3], [7, 4, 5, 1, 2]])\n', (215, 285), True, 'import numpy as np\n'), ((403, 430), 'python_solutions.Google_6_09_2019_problem.is_toeplitz_matrix', 'is... |
import logging
from textwrap import dedent
import numpy as np
import scipy.stats as stats
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Count, F, OuterRef, Subquer... | [
"alert.models.validate_add_drop_semester",
"numpy.mean",
"django.db.transaction.atomic",
"django.db.models.Value",
"django.utils.timezone.now",
"courses.util.get_add_drop_period",
"courses.models.StatusUpdate.objects.filter",
"django.db.models.F",
"alert.models.Section.objects.filter",
"django.db.... | [((3652, 3674), 'courses.util.get_current_semester', 'get_current_semester', ([], {}), '()\n', (3672, 3674), False, 'from courses.util import get_add_drop_period, get_current_semester\n'), ((10730, 10752), 'courses.util.get_current_semester', 'get_current_semester', ([], {}), '()\n', (10750, 10752), False, 'from course... |
"""
dispparam.py
Definition of a class that sets the parameters to be used when an
image is displayed
"""
from math import fabs
import numpy as np
from matplotlib import pyplot as plt
# -----------------------------------------------------------------------
class DispParam(object):
"""
A DispParam objec... | [
"numpy.indices",
"numpy.atleast_1d",
"numpy.zeros",
"math.fabs"
] | [((6293, 6316), 'numpy.zeros', 'np.zeros', (['icoords.shape'], {}), '(icoords.shape)\n', (6301, 6316), True, 'import numpy as np\n'), ((6515, 6540), 'numpy.atleast_1d', 'np.atleast_1d', (['data.shape'], {}), '(data.shape)\n', (6528, 6540), True, 'import numpy as np\n'), ((6236, 6258), 'numpy.indices', 'np.indices', (['... |
def optimizeData(l):
import numpy as np
def antiAliasV2(l,steps):
file=[np.linspace(start=l[v],stop=l[v-1],num=steps) for v in range(len(l))]
return [x for lst in file for x in lst][steps:]
def biggestDataDifferenceV2(l):
gaps=[abs(l[v]-l[v-1]) for v in range(len(l))]
return max(gaps[1:])
def dataR... | [
"numpy.linspace",
"numpy.array",
"numpy.ma.masked_where"
] | [((655, 671), 'numpy.array', 'np.array', (['newOne'], {}), '(newOne)\n', (663, 671), True, 'import numpy as np\n'), ((393, 429), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(nList < 0)', 'nList'], {}), '(nList < 0, nList)\n', (411, 429), True, 'import numpy as np\n'), ((434, 470), 'numpy.ma.masked_where', 'np.ma.... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
from __future__ import print_function
import numpy as np
import utility_functions
def test_decide_time_index_and_unit():
lines = ["34293842, 123890121930", "34293845, 123890122040"]
index, unit, r_index = utility_functions.decide_time_index_and_unit(
l... | [
"utility_functions.interpolate_imu_data",
"numpy.linalg.norm",
"numpy.array",
"utility_functions.parse_time",
"utility_functions.decide_time_index_and_unit"
] | [((265, 321), 'utility_functions.decide_time_index_and_unit', 'utility_functions.decide_time_index_and_unit', (['lines', '""","""'], {}), "(lines, ',')\n", (309, 321), False, 'import utility_functions\n'), ((474, 530), 'utility_functions.decide_time_index_and_unit', 'utility_functions.decide_time_index_and_unit', (['li... |
from typing import Any, Generator, List, Dict, Optional
import numpy as np
import json
import os
from .preprocessing import Preprocessor
import tensorflow as tf
from tensorflow.keras.mixed_precision import experimental as mixed_precision
policy = mixed_precision.Policy("mixed_float16")
mixed_precision.set_policy(polic... | [
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.reshape",
"tensorflow.keras.layers.LayerNormalization",
"tensorflow.matmul",
"tensorflow.keras.layers.LeakyReLU",
"os.path.join",
"tensorflow.nn.softmax",
"numpy.zeros_like",
"tensorflow.keras.layers.Concatenate",
"t... | [((248, 287), 'tensorflow.keras.mixed_precision.experimental.Policy', 'mixed_precision.Policy', (['"""mixed_float16"""'], {}), "('mixed_float16')\n", (270, 287), True, 'from tensorflow.keras.mixed_precision import experimental as mixed_precision\n'), ((288, 322), 'tensorflow.keras.mixed_precision.experimental.set_polic... |
'''
This module contains different methods to calculate the optimal weights of combination of assets
'''
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from typing import Union
from .porfolio import portfolio_vol, portfolio_return
from.decorators import accepts
@accepts((pd.DataFrame, np.a... | [
"scipy.optimize.minimize",
"numpy.sum",
"numpy.clip",
"numpy.array",
"numpy.repeat"
] | [((3128, 3161), 'numpy.repeat', 'np.repeat', (['(1 / n_assets)', 'n_assets'], {}), '(1 / n_assets, n_assets)\n', (3137, 3161), True, 'import numpy as np\n'), ((4278, 4466), 'scipy.optimize.minimize', 'minimize', (['neg_sharpe', 'init_guess'], {'args': '(riskfree_rate, expected_returns, covariance_matrix)', 'method': '"... |
"""Useful utilities for computational graph and components construction."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Dict, Tuple
import enum
import numpy as np
import tensorflow as tf
import wavefunctions
import utils
class Reso... | [
"tensorflow.random_uniform",
"tensorflow.add_n",
"tensorflow.reduce_sum",
"tensorflow.abs",
"tensorflow.argmax",
"tensorflow.stop_gradient",
"tensorflow.variable_scope",
"numpy.ones",
"tensorflow.multiply",
"tensorflow.assign_add",
"tensorflow.argmin",
"numpy.arange",
"utils.random_configura... | [((1637, 1692), 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': 'inputs.shape', 'dtype': 'tf.float32'}), '(shape=inputs.shape, dtype=tf.float32)\n', (1654, 1692), True, 'import tensorflow as tf\n'), ((1709, 1742), 'tensorflow.multiply', 'tf.multiply', (['inputs', 'sites_sample'], {}), '(inputs, sites_s... |
#!usr/bin/env python3
import cv2
import math
import hashlib
import numpy as np
from functools import reduce
def global_feature(auth_data):
md5 = hashlib.md5()
md5.update(auth_data.encode('utf-8'))
md5 = md5.hexdigest()
md5 = f'{int(md5, 16):0128b}'
md5 = [int(md5[i:i+8], 2) for i in range(0, 128, 8... | [
"numpy.full",
"numpy.putmask",
"hashlib.md5",
"numpy.uint8",
"cv2.imwrite",
"numpy.zeros",
"numpy.split",
"cv2.imread",
"math.log10",
"numpy.mean",
"numpy.array",
"cv2.split",
"functools.reduce",
"numpy.dot",
"cv2.merge"
] | [((150, 163), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (161, 163), False, 'import hashlib\n'), ((334, 365), 'functools.reduce', 'reduce', (['(lambda x, y: x ^ y)', 'md5'], {}), '(lambda x, y: x ^ y, md5)\n', (340, 365), False, 'from functools import reduce\n'), ((689, 724), 'functools.reduce', 'reduce', (['(lamb... |
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import random
from mpl_toolkits.axes_grid1 import make_axes_locatable
import warnings
warnings.simplefilter("ignore")
np.random.seed(1)
random.seed(1... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.yscale",
"numpy.random.seed",
"numpy.abs",
"pandas.read_csv",
"numpy.ones",
"statsmodels.api.tsa.stattools.acf",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.exp",
"numpy.random.normal",
"matplotlib.pyplot.fill_between",
"ma... | [((256, 287), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (277, 287), False, 'import warnings\n'), ((289, 306), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (303, 306), True, 'import numpy as np\n'), ((307, 321), 'random.seed', 'random.seed', (['(1)'], {})... |
import numpy as np
import cv2
import pose_estimation as pose
npzfile = np.load("pnp_data.npz")
names = npzfile.files
for name in names:
print(name, npzfile[name].shape)
points_3d = npzfile[names[0]]
shape = points_3d.shape
points_3d = np.reshape(points_3d, (shape[0], 3))
print(points_3d.shape)
points_2d = npzfile... | [
"numpy.load",
"pose_estimation.solve_pnp",
"numpy.zeros",
"cv2.Rodrigues",
"numpy.array",
"numpy.reshape"
] | [((72, 95), 'numpy.load', 'np.load', (['"""pnp_data.npz"""'], {}), "('pnp_data.npz')\n", (79, 95), True, 'import numpy as np\n'), ((241, 277), 'numpy.reshape', 'np.reshape', (['points_3d', '(shape[0], 3)'], {}), '(points_3d, (shape[0], 3))\n', (251, 277), True, 'import numpy as np\n'), ((387, 403), 'numpy.zeros', 'np.z... |
'''
_Generator Class of Definitive Screening Design Generator Module
'''
import numpy as np
from tagupy.design.generator import _dsd_ref as ref
from tagupy.type import _Generator as Generator
from tagupy.utils import is_positive_int
class DSD(Generator):
'''
Generator Class of Definitive Screening Design Gen... | [
"tagupy.utils.is_positive_int",
"numpy.vstack",
"tagupy.design.generator._dsd_ref._get_dsd"
] | [((1713, 1735), 'tagupy.utils.is_positive_int', 'is_positive_int', (['n_rep'], {}), '(n_rep)\n', (1728, 1735), False, 'from tagupy.utils import is_positive_int\n'), ((4221, 4246), 'tagupy.utils.is_positive_int', 'is_positive_int', (['n_factor'], {}), '(n_factor)\n', (4236, 4246), False, 'from tagupy.utils import is_pos... |
import numpy
import scipy.optimize as optimize
import operator
from nltk import PorterStemmer
# The sigmoid function is used to map the output of our
# prediction z = x * theta into a probability value (range [0, 1])
def sigmoid(z):
return 1 / (1 + (numpy.exp(-z)));
class LearningAlgorithm(object):
def __ini... | [
"scipy.optimize.minimize",
"numpy.sum",
"numpy.log",
"numpy.zeros",
"numpy.transpose",
"numpy.exp",
"operator.itemgetter",
"nltk.PorterStemmer"
] | [((349, 363), 'numpy.zeros', 'numpy.zeros', (['(0)'], {}), '(0)\n', (360, 363), False, 'import numpy\n'), ((570, 584), 'numpy.zeros', 'numpy.zeros', (['(0)'], {}), '(0)\n', (581, 584), False, 'import numpy\n'), ((688, 702), 'numpy.zeros', 'numpy.zeros', (['(0)'], {}), '(0)\n', (699, 702), False, 'import numpy\n'), ((49... |
from sac.misc import utils
from sac.misc.sampler import rollouts
from sac.policies.hierarchical_policy import FixedOptionPolicy
import argparse
import joblib
import json
import numpy as np
import os
import re
import tensorflow as tf
def collect_expert_trajectories(expert_snapshot, max_path_length):
tf.logging.inf... | [
"numpy.sum",
"argparse.ArgumentParser",
"tensorflow.logging.info",
"numpy.argmax",
"sac.policies.hierarchical_policy.FixedOptionPolicy",
"tensorflow.reset_default_graph",
"tensorflow.logging.set_verbosity",
"numpy.mean",
"numpy.linalg.norm",
"os.path.join",
"numpy.std",
"os.path.dirname",
"o... | [((306, 355), 'tensorflow.logging.info', 'tf.logging.info', (['"""Collecting expert trajectories"""'], {}), "('Collecting expert trajectories')\n", (321, 355), True, 'import tensorflow as tf\n'), ((981, 1005), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (1003, 1005), True, 'import tens... |
"""
Core Function Code
"""
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
class ResponseSurface:
def __init__(self,inputs,output,degree = 2, intercept = True, interaction_only = False):
X = inputs
... | [
"numpy.meshgrid",
"numpy.argmax",
"numpy.ravel",
"numpy.zeros",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.PolynomialFeatures",
"numpy.shape",
"numpy.random.random",
"numpy.min",
"numpy.row_stack",
"numpy.linspace",
"numpy.where",
"numpy.round",
"numpy.delete"
] | [((1212, 1280), 'numpy.linspace', 'np.linspace', (['varLims[selectvar[0], 0]', 'varLims[selectvar[0], 1]', '(100)'], {}), '(varLims[selectvar[0], 0], varLims[selectvar[0], 1], 100)\n', (1223, 1280), True, 'import numpy as np\n'), ((1293, 1361), 'numpy.linspace', 'np.linspace', (['varLims[selectvar[1], 0]', 'varLims[sel... |
import asyncio
import numpy as np
def rotation_matrix(theta):
"""
Returns a 2-dimensional rotation array of a given angle.
Notes
-----
Matrix multiplication of a rotation matrix with a camera's plane will
rotate the plane.
"""
x = np.cos(theta)
y = np.sin(theta)
return np.arr... | [
"asyncio.sleep",
"numpy.sin",
"numpy.array",
"numpy.linspace",
"numpy.cos"
] | [((266, 279), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (272, 279), True, 'import numpy as np\n'), ((288, 301), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (294, 301), True, 'import numpy as np\n'), ((314, 354), 'numpy.array', 'np.array', (['[[x, y], [-y, x]]'], {'dtype': 'float'}), '([[x, y], [-y, ... |
import numpy as np
import pandas as pd
def make_a_small_dataframe():
return pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
| [
"numpy.array"
] | [((95, 138), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (103, 138), True, 'import numpy as np\n')] |
from __future__ import print_function
from scipy.spatial.distance import cosine
import numpy as np
from numpy import linalg as LA
# def cos(x,y):
# cos = 0.5 *(1+ (np.inner(x,y))/(LA.norm(x)*LA.norm(y)))
# return cos
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return n... | [
"numpy.maximum",
"numpy.sum",
"numpy.linalg.norm",
"numpy.exp",
"numpy.inner",
"numpy.squeeze"
] | [((1030, 1054), 'numpy.inner', 'np.inner', (['feats', 'feats_p'], {}), '(feats, feats_p)\n', (1038, 1054), True, 'import numpy as np\n'), ((1063, 1076), 'numpy.squeeze', 'np.squeeze', (['a'], {}), '(a)\n', (1073, 1076), True, 'import numpy as np\n'), ((1263, 1283), 'numpy.maximum', 'np.maximum', (['feats', '(0)'], {}),... |
from cv_bridge import CvBridge
import cv2
import math
import numpy as np
import PIL.Image as Image
from carla.image_converter import depth_to_array
from carla.sensor import Camera
from erdos.op import Op
from erdos.utils import setup_logging
import messages
from utils import add_bounding_box, get_3d_world_position, ... | [
"utils.map_ground_3D_transform_to_2D",
"cv_bridge.CvBridge",
"numpy.uint8",
"utils.map_ground_bounding_box_to_2D",
"cv2.waitKey",
"math.tan",
"utils.add_bounding_box",
"numpy.identity",
"carla.image_converter.depth_to_array",
"numpy.array",
"cv2.imshow",
"erdos.utils.setup_logging",
"carla.s... | [((771, 810), 'erdos.utils.setup_logging', 'setup_logging', (['self.name', 'log_file_name'], {}), '(self.name, log_file_name)\n', (784, 810), False, 'from erdos.utils import setup_logging\n'), ((880, 890), 'cv_bridge.CvBridge', 'CvBridge', ([], {}), '()\n', (888, 890), False, 'from cv_bridge import CvBridge\n'), ((1924... |
from encoder.encoder import Encoder
from decoder.decoder import Decoder
from model.utils import categorical_cross_entropy, OHE
import numpy as np
CONTEXT_LEN = 16
MAX_NUM = 20
class Seq2Seq:
def __init__(self):
self.encoder = Encoder(MAX_NUM)
self.decoder = Decoder(MAX_NUM, 1)
# Forward ... | [
"model.utils.OHE",
"numpy.argmax",
"numpy.array",
"encoder.encoder.Encoder",
"decoder.decoder.Decoder"
] | [((241, 257), 'encoder.encoder.Encoder', 'Encoder', (['MAX_NUM'], {}), '(MAX_NUM)\n', (248, 257), False, 'from encoder.encoder import Encoder\n'), ((281, 300), 'decoder.decoder.Decoder', 'Decoder', (['MAX_NUM', '(1)'], {}), '(MAX_NUM, 1)\n', (288, 300), False, 'from decoder.decoder import Decoder\n'), ((1402, 1422), 'm... |
"""Plots of results
"""
# import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# decision trees
d = pd.read_csv('data/DT.csv')
# per turbine
d0 = d.groupby('turbine', as_index=False)['f1'].mean()
d1 = d.groupby('turbine', as_index=False)['f1'].max()
d2 = d.groupby('turbine', as_in... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"matplotlib.pyplot.legend",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.errorbar"
] | [((138, 164), 'pandas.read_csv', 'pd.read_csv', (['"""data/DT.csv"""'], {}), "('data/DT.csv')\n", (149, 164), True, 'import pandas as pd\n'), ((508, 531), 'numpy.array', 'np.array', (["d0['turbine']"], {}), "(d0['turbine'])\n", (516, 531), True, 'import numpy as np\n'), ((536, 554), 'numpy.array', 'np.array', (["d0['f1... |
"""
STAIN.NORM: various methods for stain normalization.
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
__author__ = 'vlad'
__version__ = 0.1
import numpy as np
from skimage.util import img_as_float
from skimage.exposure import rescale_intensity
def compute_macenko_norm_mat... | [
"numpy.arctan2",
"numpy.log",
"numpy.zeros",
"numpy.cross",
"numpy.hstack",
"numpy.percentile",
"numpy.any",
"numpy.sin",
"numpy.cos",
"numpy.dot",
"numpy.cov"
] | [((1058, 1082), 'numpy.dot', 'np.dot', (['odhat', 'V[:, 1:3]'], {}), '(odhat, V[:, 1:3])\n', (1064, 1082), True, 'import numpy as np\n'), ((1092, 1128), 'numpy.arctan2', 'np.arctan2', (['theta[:, 1]', 'theta[:, 0]'], {}), '(theta[:, 1], theta[:, 0])\n', (1102, 1128), True, 'import numpy as np\n'), ((1148, 1188), 'numpy... |
import netver.utils.propagation_utilities as prop_utils
import numpy as np
class Estimated( ):
"""
A class that implements an estimator for the real value of the violation rate. The approach is based on a sampling and propagation method, sampling a
points cloud from the domain of the property the method compute a... | [
"numpy.random.uniform",
"numpy.min",
"numpy.where",
"numpy.max"
] | [((4997, 5031), 'numpy.min', 'np.min', (['output_point_cloud'], {'axis': '(1)'}), '(output_point_cloud, axis=1)\n', (5003, 5031), True, 'import numpy as np\n'), ((5095, 5129), 'numpy.max', 'np.max', (['output_point_cloud'], {'axis': '(1)'}), '(output_point_cloud, axis=1)\n', (5101, 5129), True, 'import numpy as np\n'),... |
#!/usr/bin/env python
# coding: utf-8
import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
import os
os.chdir('../../')
a = sio.loadmat('time_1_4.mat')
cells = a['timedata']
cells.shape
t = np.linspace(0, 15, 361)
immune_cells = ['CD8 T', 'Mac', 'Neut', 'DC', 'CD4 T', 'Fib', 'virion', 'IFN', ... | [
"scipy.io.loadmat",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.cla",
"numpy.linspace",
"matplotlib.pyplot.tight_layout",
"os.chdir"
] | [((123, 141), 'os.chdir', 'os.chdir', (['"""../../"""'], {}), "('../../')\n", (131, 141), False, 'import os\n'), ((147, 174), 'scipy.io.loadmat', 'sio.loadmat', (['"""time_1_4.mat"""'], {}), "('time_1_4.mat')\n", (158, 174), True, 'import scipy.io as sio\n'), ((215, 238), 'numpy.linspace', 'np.linspace', (['(0)', '(15)... |
import numpy as np
import pdb
def bbox_iou(b1, b2):
'''
b: (x1,y1,x2,y2)
'''
lx = max(b1[0], b2[0])
rx = min(b1[2], b2[2])
uy = max(b1[1], b2[1])
dy = min(b1[3], b2[3])
if rx <= lx or dy <= uy:
return 0.
else:
interArea = (rx-lx)*(dy-uy)
a1 = float((b1[2] - b... | [
"cv2.waitKey",
"cv2.imread",
"numpy.array",
"numpy.squeeze",
"cv2.imshow",
"cv2.resize"
] | [((1180, 1294), 'cv2.imread', 'cv2.imread', (['"""/home/xhzhan/data/CityScapes/gtFine/val/frankfurt/frankfurt_000000_003920_gtFine_color.png"""'], {}), "(\n '/home/xhzhan/data/CityScapes/gtFine/val/frankfurt/frankfurt_000000_003920_gtFine_color.png'\n )\n", (1190, 1294), False, 'import cv2\n'), ((1295, 1322), 'cv... |
import sys, subprocess, os, struct, time
from multiprocessing import Pool
import numpy as np
import torch
import scipy
from scipy.stats import truncnorm, multivariate_normal, mvn
from scipy.special import erf, loggamma
from util import PyTorchDType as dtype
n_cache = 2**14
tLogGamma_cache = None
tarange = None
# tLo... | [
"torch.masked_select",
"numpy.sum",
"numpy.random.seed",
"numpy.abs",
"numpy.empty",
"numpy.random.exponential",
"torch.empty",
"numpy.ones",
"torch.cat",
"torch.full",
"numpy.linalg.norm",
"torch.arange",
"numpy.random.normal",
"torch.empty_like",
"numpy.arange",
"numpy.full",
"torc... | [((619, 628), 'numpy.log', 'np.log', (['U'], {}), '(U)\n', (625, 628), True, 'import numpy as np\n'), ((634, 666), 'numpy.sum', 'np.sum', (['E'], {'axis': '(1)', 'keepdims': '(True)'}), '(E, axis=1, keepdims=True)\n', (640, 666), True, 'import numpy as np\n'), ((803, 847), 'numpy.random.exponential', 'np.random.exponen... |
import numpy as np
from matplotlib import pyplot as plt
colours = np.array(["k", "g", "b", "r", "c", "m", "y", "w"])
x = np.linspace(0, 5, 1000)
y = np.ones(1000)
for i in xrange(8):
plt.plot(x, i*y, colours[i])
plt.ylim([-1, 8])
plt.show() | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.ones",
"numpy.array",
"numpy.linspace"
] | [((67, 117), 'numpy.array', 'np.array', (["['k', 'g', 'b', 'r', 'c', 'm', 'y', 'w']"], {}), "(['k', 'g', 'b', 'r', 'c', 'm', 'y', 'w'])\n", (75, 117), True, 'import numpy as np\n'), ((122, 145), 'numpy.linspace', 'np.linspace', (['(0)', '(5)', '(1000)'], {}), '(0, 5, 1000)\n', (133, 145), True, 'import numpy as np\n'),... |
import numpy as np
import pandas as pd
import os
import argparse
import json
import tensorflow.keras as k
def readData(tumorFileName, normalFileName):
x_true = pd.read_csv(tumorFileName, sep='\t', header=0, index_col=0).T
x_false = pd.read_csv(normalFileName, sep='\t', header=0, index_col=0).T
# if this d... | [
"json.load",
"tensorflow.keras.models.load_model",
"argparse.ArgumentParser",
"pandas.read_csv",
"numpy.zeros",
"numpy.array",
"pandas.concat"
] | [((439, 459), 'numpy.zeros', 'np.zeros', (['x.shape[0]'], {}), '(x.shape[0])\n', (447, 459), True, 'import numpy as np\n'), ((875, 909), 'tensorflow.keras.models.load_model', 'k.models.load_model', (['modelFileName'], {}), '(modelFileName)\n', (894, 909), True, 'import tensorflow.keras as k\n'), ((1180, 1242), 'argpars... |
import os
import json
import numpy as np
import SimpleITK as sitk
from radiomics import featureextractor
class CalculateFeatures(object):
def __init__(self):
self._input_image_file_path = None
self._input_mask_file_path = None
self._wavelet_enabled = False
self._log_enabled = Fals... | [
"os.makedirs",
"SimpleITK.ReadImage",
"json.dumps",
"radiomics.featureextractor.RadiomicsFeatureExtractor",
"os.path.splitext",
"numpy.sign",
"os.path.split",
"os.path.join"
] | [((3458, 3484), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['image_file'], {}), '(image_file)\n', (3472, 3484), True, 'import SimpleITK as sitk\n'), ((3500, 3525), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['mask_file'], {}), '(mask_file)\n', (3514, 3525), True, 'import SimpleITK as sitk\n'), ((4735, 4779), 'os.makedirs... |
from __future__ import print_function, division
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
from astropy.coordinates import SkyCoord
from astropy import units as u
import efficiency_estimate as eff #################!!! THIS IS SPECIFIC FOR THE SDSS DATA!!
#This co... | [
"efficiency_estimate.efficiency",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"numpy.savetxt",
"efficiency_estimate.prepare_uniform_sample",
"numpy.loadtxt",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.ylabel",
"matp... | [((3422, 3448), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 4)'}), '(figsize=(4, 4))\n', (3432, 3448), True, 'import matplotlib.pyplot as plt\n'), ((3452, 3475), 'numpy.arange', 'np.arange', (['(0)', '(1.01)', '(0.1)'], {}), '(0, 1.01, 0.1)\n', (3461, 3475), True, 'import numpy as np\n'), ((3475, 34... |
import os
import time
import numpy as np
import pandas as pd
import random
from collections import defaultdict
import torch as t
from torch import optim
from nbeats.contrib.nbeatsx.nbeatsx_model import NBeats, NBeatsBlock, IdentityBasis, TrendBasis, SeasonalityBasis
from nbeats.contrib.utils.pytorch.sampler import Ti... | [
"torch.optim.lr_scheduler.StepLR",
"nbeats.contrib.utils.pytorch.losses.MSELoss",
"nbeats.contrib.utils.pytorch.losses.MAPELoss",
"collections.defaultdict",
"nbeats.contrib.utils.pytorch.losses.SMAPELoss",
"torch.no_grad",
"os.path.join",
"pandas.DataFrame",
"torch.load",
"os.path.exists",
"nbea... | [((9588, 9869), 'nbeats.contrib.utils.pytorch.sampler.TimeseriesDataset', 'TimeseriesDataset', ([], {'model': '"""nbeats"""', 'ts_data': 'ts_data', 'static_data': 'static_data', 'meta_data': 'meta_data', 'window_sampling_limit': 'self.window_sampling_limit', 'offset': 'offset', 'input_size': 'self.input_size', 'output_... |
# -*- coding: utf-8 -*-
"""Heart Disease Prediction .ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1TkXEtBKFfx39F0rOCxdzRk4wr9PQn-fY
##**Import Libraries**
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pypl... | [
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"numpy.asarray",
"matplotlib.pyplot.figure",
"sklearn.linear_model.LogisticRegression",
"seaborn.countplot",
"seaborn.color_palette",
"google.colab.files.upload"... | [((400, 414), 'google.colab.files.upload', 'files.upload', ([], {}), '()\n', (412, 414), False, 'from google.colab import files\n'), ((465, 489), 'pandas.read_csv', 'pd.read_csv', (['"""heart.csv"""'], {}), "('heart.csv')\n", (476, 489), True, 'import pandas as pd\n'), ((946, 973), 'seaborn.countplot', 'sns.countplot',... |
# _*_ coding: utf-8 _*_
# using Python 3 to solve the problem.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
### Sigmoid Func ###
def sigmoidFunc(data):
g = 1.0 / ( 1.0 + np.exp(-data))
return g
### Training Logistic Func ###
def trainLogistic(dataset):
data = dataset
# 注... | [
"numpy.square",
"numpy.transpose",
"numpy.ones",
"numpy.shape",
"numpy.mean",
"numpy.exp",
"numpy.mat"
] | [((428, 442), 'numpy.shape', 'np.shape', (['data'], {}), '(data)\n', (436, 442), True, 'import numpy as np\n'), ((731, 746), 'numpy.ones', 'np.ones', (['(n, 1)'], {}), '((n, 1))\n', (738, 746), True, 'import numpy as np\n'), ((1402, 1416), 'numpy.shape', 'np.shape', (['data'], {}), '(data)\n', (1410, 1416), True, 'impo... |
"""
Goal - to draw trajectories on video
Jun 9th 2021
"""
import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import trajectorytools as tt
import trajectorytools.plot as t... | [
"cmapy.color",
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"cv2.putText",
"trajectorytools.Trajectories.from_idtrackerai",
"cv2.VideoCapture",
"numpy.linspace",
"numpy.int32",
"scipy.spatial.ConvexHull"
] | [((801, 826), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (824, 826), False, 'import argparse\n'), ((2832, 2863), 'cv2.VideoCapture', 'cv2.VideoCapture', (['args.a_string'], {}), '(args.a_string)\n', (2848, 2863), False, 'import cv2\n'), ((2994, 3025), 'cv2.VideoWriter_fourcc', 'cv2.VideoWri... |
'''
DESCRIPTION
This module takes the cleaned data from the ETL module and trains a ML classification model
The output is a model which can be used to predict on new data
INPUTS
database_filepath - path containing the processed data database
OUTPUTS
Saves the trained model to a pickle file
SCRIPT EXECUTION SAM... | [
"pandas.DataFrame",
"sklearn.model_selection.GridSearchCV",
"pickle.dump",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.feature_extraction.text.CountVectorizer",
"nltk.stem.WordNetLemmatizer",
"nltk.sent_tokenize",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.classification_report... | [((1125, 1190), 'nltk.download', 'nltk.download', (["['punkt', 'wordnet', 'averaged_perceptron_tagger']"], {}), "(['punkt', 'wordnet', 'averaged_perceptron_tagger'])\n", (1138, 1190), False, 'import nltk\n'), ((1622, 1669), 'sqlalchemy.create_engine', 'create_engine', (["('sqlite:///' + database_filepath)"], {}), "('sq... |
"""Engine that performs decisions about whether to employ a surrogate"""
from proxima.inference import BaseInferenceEngine, ScikitLearnInferenceEngine
from proxima.data import BaseDataSource
import numpy as np
from sklearn.neighbors import NearestNeighbors
# TODO (wardlt): Provide some mechanism for checking if UQ t... | [
"numpy.mean",
"sklearn.neighbors.NearestNeighbors"
] | [((2561, 2583), 'numpy.mean', 'np.mean', (['dists'], {'axis': '(1)'}), '(dists, axis=1)\n', (2568, 2583), True, 'import numpy as np\n'), ((2360, 2436), 'sklearn.neighbors.NearestNeighbors', 'NearestNeighbors', ([], {'n_neighbors': 'self.k', 'n_jobs': 'self.n_jobs', 'metric': 'self.metric'}), '(n_neighbors=self.k, n_job... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''An example of similarity comparison between graphs whose node or edge labels
are variable-length sequences rather than scalars using the marginalized graph
kernel.'''
import numpy as np
import networkx as nx
from graphdot import Graph
from graphdot.kernel.marginalized im... | [
"graphdot.microkernel.KroneckerDelta",
"graphdot.Graph.from_networkx",
"networkx.Graph",
"graphdot.microkernel.SquareExponential",
"graphdot.kernel.marginalized.MarginalizedGraphKernel",
"numpy.diag"
] | [((588, 598), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (596, 598), True, 'import networkx as nx\n'), ((732, 742), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (740, 742), True, 'import networkx as nx\n'), ((1432, 1477), 'graphdot.kernel.marginalized.MarginalizedGraphKernel', 'MarginalizedGraphKernel', (['knod... |
import os.path
import json
import pytorch_lightning as pl
import torch
import torch.backends.cudnn
from pytorch_lightning.loggers import WandbLogger
from src.models.ImagenetTransferLearning import ImagenetTransferLearning
from src.data.GoogleDataModule import GoogleDataModule
from src.models.ProgressiveRescalingCallba... | [
"copy.deepcopy",
"pytorch_lightning.callbacks.ModelCheckpoint",
"pytorch_lightning.seed_everything",
"json.load",
"numpy.ceil",
"src.models.ProgressiveRescalingCallback.ProgressiveRescaling",
"numpy.gcd.reduce",
"pytorch_lightning.loggers.WandbLogger",
"torch.cuda.is_available",
"src.data.GoogleDa... | [((550, 575), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (573, 575), False, 'import torch\n'), ((524, 546), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (536, 546), False, 'import torch\n'), ((581, 600), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu'... |
"""
project: Load Flow Calculation
author: @魏明江
time: 2020/02/22
attention:readData.py定义了数据类完成了从txt读取文档,然后建立节点导纳矩阵的过程
Data类包含的属性有 :path, input_file_list, admittance_matrix分别是
源文件路径,读取完成并经过数据转换后的输入列表,以及节点导纳矩阵
Data类包含的可用方法有read_data(self), get_admittance_matrix(self)
分别是读取并转换数据... | [
"numpy.zeros"
] | [((3905, 3954), 'numpy.zeros', 'np.zeros', (['(self.shape, self.shape)'], {'dtype': 'complex'}), '((self.shape, self.shape), dtype=complex)\n', (3913, 3954), True, 'import numpy as np\n'), ((3973, 4028), 'numpy.zeros', 'np.zeros', (['(self.shape - 1, self.shape - 1)'], {'dtype': 'float'}), '((self.shape - 1, self.shape... |
import numpy as np
from physics_sim import PhysicsSim
import math
class Task():
"""Task (environment) that defines the goal and provides feedback to the agent."""
def __init__(self, init_pose=None, init_velocities=None, init_angle_velocities=None,
runtime=5., target_pose=None):
# Si... | [
"numpy.tanh",
"numpy.concatenate",
"physics_sim.PhysicsSim"
] | [((348, 418), 'physics_sim.PhysicsSim', 'PhysicsSim', (['init_pose', 'init_velocities', 'init_angle_velocities', 'runtime'], {}), '(init_pose, init_velocities, init_angle_velocities, runtime)\n', (358, 418), False, 'from physics_sim import PhysicsSim\n'), ((3891, 3915), 'numpy.concatenate', 'np.concatenate', (['pose_al... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# import funkcí z jiného adresáře
import sys
import os.path
import numpy as np
# from scipy import signal
import matplotlib.pyplot as plt
# import skimage.exposure as skexp
path_to_script = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(path_to_scrip... | [
"matplotlib.pyplot.gray",
"argparse.ArgumentParser",
"misc.obj_from_file",
"scipy.ndimage.measurements.label",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.exp",
"loguru.logger.addHandler",
"lesioneditor.Lession_editor_slim.LessionEditor",
"numpy.zeros_like",
"scipy.ndimage.distance_transfor... | [((1270, 1302), 'pkg_resources.parse_version', 'parse_version', (['scipy.__version__'], {}), '(scipy.__version__)\n', (1283, 1302), False, 'from pkg_resources import parse_version\n'), ((1305, 1325), 'pkg_resources.parse_version', 'parse_version', (['"""0.9"""'], {}), "('0.9')\n", (1318, 1325), False, 'from pkg_resourc... |
"""Keras Sequence for Open-world assumption GCN."""
from typing import Tuple, List, Optional
import numpy as np
import tensorflow as tf
from ensmallen import Graph # pylint: disable=no-name-in-module
from keras_mixed_sequence import Sequence, VectorSequence
from embiggen.sequences.generic_sequences import EdgePredict... | [
"numpy.pad",
"tensorflow.TensorSpec",
"tensorflow.SparseTensorSpec",
"numpy.repeat"
] | [((6686, 6743), 'tensorflow.SparseTensorSpec', 'tf.SparseTensorSpec', ([], {'shape': '(None, None)', 'dtype': 'tf.float32'}), '(shape=(None, None), dtype=tf.float32)\n', (6705, 6743), True, 'import tensorflow as tf\n'), ((6266, 6310), 'tensorflow.TensorSpec', 'tf.TensorSpec', ([], {'shape': '(None,)', 'dtype': 'tf.int3... |
"""
Plot results.
"""
import csv
import matplotlib.pyplot as plt
import numpy as np
def movingaverage(y, window_size):
"""
Moving average function from:
http://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python
"""
window = np.ones(int(window_size))/float(window... | [
"matplotlib.pyplot.show",
"csv.reader",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"numpy.convolve",
"numpy.array",
"matplotlib.pyplot.ylabel"
] | [((338, 368), 'numpy.convolve', 'np.convolve', (['y', 'window', '"""same"""'], {}), "(y, window, 'same')\n", (349, 368), True, 'import numpy as np\n'), ((813, 827), 'numpy.array', 'np.array', (['y_av'], {}), '(y_av)\n', (821, 827), True, 'import numpy as np\n'), ((896, 905), 'matplotlib.pyplot.clf', 'plt.clf', ([], {})... |
import numpy as np, pandas as pd, os
import matplotlib.pyplot as plt
from torchvision import transforms
from torch.utils.data import Dataset
from PIL import Image, ImageEnhance
from random import uniform
class PapDataset(Dataset):
def __init__(self, root, subjects, train):
self.root_dir = root
sel... | [
"numpy.uint8",
"random.uniform",
"PIL.ImageEnhance.Contrast",
"torchvision.transforms.ToTensor",
"numpy.array",
"torchvision.transforms.Normalize",
"matplotlib.pyplot.imread",
"os.listdir",
"torchvision.transforms.Resize"
] | [((1601, 1630), 'matplotlib.pyplot.imread', 'plt.imread', (['self.dataset[idx]'], {}), '(self.dataset[idx])\n', (1611, 1630), True, 'import matplotlib.pyplot as plt\n'), ((2093, 2117), 'PIL.ImageEnhance.Contrast', 'ImageEnhance.Contrast', (['i'], {}), '(i)\n', (2114, 2117), False, 'from PIL import Image, ImageEnhance\n... |
"""
Generalized assigment problem: solve constrained optimal 2D binning problem.
Constraint programming implementation.
"""
# <NAME> <<EMAIL>>
# Copyright (C) 2021
import numpy as np
from ortools.sat.python import cp_model
class Binning2DCP:
def __init__(self, monotonic_trend_x, monotonic_trend_y, min_n_bins,
... | [
"numpy.ceil",
"numpy.zeros",
"ortools.sat.python.cp_model.CpSolver",
"ortools.sat.python.cp_model.CpModel"
] | [((1213, 1231), 'ortools.sat.python.cp_model.CpModel', 'cp_model.CpModel', ([], {}), '()\n', (1229, 1231), False, 'from ortools.sat.python import cp_model\n'), ((2791, 2810), 'ortools.sat.python.cp_model.CpSolver', 'cp_model.CpSolver', ([], {}), '()\n', (2808, 2810), False, 'from ortools.sat.python import cp_model\n'),... |
"""
Merge extracted score
By <NAME>
<EMAIL>
"""
import argparse
import numpy as np
import os
import yaml
from utils.metrics import accuracy
from utils.util import merge_config, add_config
def parse_option():
parser = argparse.ArgumentParser('training')
parser.add_argument('--config_file', type=str, required... | [
"argparse.ArgumentParser",
"numpy.empty",
"utils.metrics.accuracy",
"numpy.zeros",
"numpy.sort",
"utils.util.add_config",
"numpy.reshape",
"utils.util.merge_config"
] | [((225, 260), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""training"""'], {}), "('training')\n", (248, 260), False, 'import argparse\n'), ((860, 892), 'utils.util.add_config', 'add_config', (['args', '"""root"""', 'config'], {}), "(args, 'root', config)\n", (870, 892), False, 'from utils.util import merg... |
import assets as at
import numpy as np
import cvxopt as opt
from cvxopt import blas, solvers
import matplotlib.pyplot as plt
import pandas as pd
class Portfolio:
def __init__(self, assets: at.Assets, weights, risk_free_rate):
self._assets = assets
self._risk_free_rate = risk_free_rate
if l... | [
"numpy.polyfit",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.asscalar",
"matplotlib.pyplot.xlabel",
"pandas.DataFrame",
"numpy.multiply",
"numpy.transpose",
"cvxopt.solvers.qp",
"numpy.add",
"numpy.divide",
"cvxopt.matrix",
"matplotlib.pyplot.legend",
"numpy.asarray",
"numpy.linalg.... | [((1933, 1959), 'cvxopt.matrix', 'opt.matrix', (['covariance_mat'], {}), '(covariance_mat)\n', (1943, 1959), True, 'import cvxopt as opt\n'), ((1968, 1991), 'cvxopt.matrix', 'opt.matrix', (['(0.0)', '(n, 1)'], {}), '(0.0, (n, 1))\n', (1978, 1991), True, 'import cvxopt as opt\n'), ((2065, 2088), 'cvxopt.matrix', 'opt.ma... |
# -*- coding: utf-8 -*-
"""
Simulation
==========
The simulation code, but with units.
It is more difficult to add units to the simulation code than
the simple base classes. This is because there are complicated integrals,
derivatives, sums, and other pieces of code which are both numerically
sensitive and demanding ... | [
"numpy.sum",
"numpy.tanh",
"scipy.misc.derivative",
"scipy.integrate.quad",
"copy.copy",
"numpy.arccosh",
"jittermodel.q2unitless",
"math.fsum",
"numpy.arange",
"numpy.exp",
"numpy.cosh",
"numpy.log10",
"numpy.sinh",
"numpy.sqrt"
] | [((3216, 3259), 'numpy.arccosh', 'arccosh', (['(1 + d / R_tip + h / (E_s1 * R_tip))'], {}), '(1 + d / R_tip + h / (E_s1 * R_tip))\n', (3223, 3259), False, 'from numpy import pi, sinh, cosh, tanh, arccosh, exp, log10, arctanh\n'), ((4881, 4934), 'numpy.sqrt', 'np.sqrt', (['(k ** 2 + kappa ** 2 / E_s + omega / D * 1.0j)'... |
# Data science tools
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Image processing
import nibabel as nib
from scipy import ndimage
# Base operations
from tqdm import tqdm
from io import StringIO
import time
import os
# Cloud interface
#from google.cloud import storage
# from google.cloud... | [
"io.StringIO",
"numpy.save",
"matplotlib.pyplot.show",
"numpy.ceil",
"nibabel.load",
"matplotlib.pyplot.imshow",
"numpy.floor",
"numpy.genfromtxt",
"scipy.ndimage.zoom",
"time.time",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.round",
"os.listdir"
] | [((1154, 1185), 'os.listdir', 'os.listdir', (['RAW_IMAGE_DIRECTORY'], {}), '(RAW_IMAGE_DIRECTORY)\n', (1164, 1185), False, 'import os\n'), ((7407, 7418), 'time.time', 'time.time', ([], {}), '()\n', (7416, 7418), False, 'import time\n'), ((2540, 2579), 'nibabel.load', 'nib.load', (['f"""{file_path}/{mnc_files[i]}"""'], ... |
# stdlib
import subprocess
import warnings
# third party
import numpy as np
import pyperf
from syft_benchmarks import run_rept_suite
from syft_benchmarks import run_sept_suite
warnings.filterwarnings("ignore", category=UserWarning)
def get_git_revision_short_hash() -> str:
return (
subprocess.check_outp... | [
"syft_benchmarks.run_rept_suite",
"warnings.filterwarnings",
"subprocess.check_output",
"syft_benchmarks.run_sept_suite",
"pyperf.Runner",
"numpy.iinfo"
] | [((178, 233), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (201, 233), False, 'import warnings\n'), ((449, 467), 'numpy.iinfo', 'np.iinfo', (['np.int32'], {}), '(np.int32)\n', (457, 467), True, 'import numpy as np\n'), ((481... |
#!/usr/bin/env python3.7
'''
CODE FOR THE GENERATION OF THE KNAPSACK PROBLEM INSTANCES
Input:
- Capacity of the Knapsack. Introduced manually by the user in -k
- Number of random realizations. Introduce manually by the user in -n
Output:
- Available_Weights.csv, spreadsheet containing a column per problem realizatio... | [
"numpy.sum",
"argparse.ArgumentParser",
"time.process_time",
"numpy.random.randint",
"numpy.random.rand"
] | [((935, 1006), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Data Exploration for Stats-Omega"""'}), "(description='Data Exploration for Stats-Omega')\n", (958, 1006), False, 'import os, argparse\n'), ((1975, 2012), 'numpy.random.rand', 'np.random.rand', (['(knapsack_capacity + 1)'], {}... |
import itertools
from scipy.linalg import pinv2, block_diag, cholesky
from sklearn.cross_decomposition import CCA, PLSCanonical
import numpy as np
import cca_zoo.KCCA
import cca_zoo.alternating_least_squares
import cca_zoo.generate_data
import cca_zoo.plot_utils
from hyperopt import tpe, hp, fmin, STATUS_OK,Trials
fro... | [
"numpy.sum",
"scipy.linalg.cholesky",
"hyperopt.hp.choice",
"numpy.isnan",
"numpy.argsort",
"numpy.arange",
"numpy.linalg.norm",
"hyperopt.hp.quniform",
"numpy.array_split",
"numpy.linalg.pinv",
"scipy.linalg.pinv2",
"numpy.linalg.eig",
"sklearn.cross_decomposition.PLSCanonical",
"numpy.cu... | [((12112, 12143), 'numpy.zeros', 'np.zeros', (['(n_reps, latent_dims)'], {}), '((n_reps, latent_dims))\n', (12120, 12143), True, 'import numpy as np\n'), ((12524, 12545), 'numpy.zeros', 'np.zeros', (['latent_dims'], {}), '(latent_dims)\n', (12532, 12545), True, 'import numpy as np\n'), ((13856, 13883), 'numpy.arange', ... |
import os
import time
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from util.evaluation import AverageMeter, accuracy, pairwise_distances
from util.utils import length_to_mask
from trainer.trainer import Trainer
from modules.losses import get_gan_loss, KLLoss
from .networks im... | [
"torch.no_grad",
"os.makedirs",
"util.evaluation.accuracy",
"torch.load",
"torch.argmax",
"os.path.exists",
"torch.cat",
"torch.nn.CrossEntropyLoss",
"time.time",
"torch.save",
"util.evaluation.pairwise_distances",
"numpy.array",
"util.evaluation.AverageMeter",
"torch.zeros",
"torch.tens... | [((2302, 2341), 'os.path.join', 'os.path.join', (['"""./tmp"""', 'self.args.log_id'], {}), "('./tmp', self.args.log_id)\n", (2314, 2341), False, 'import os\n'), ((6876, 6900), 'torch.load', 'torch.load', (['restore_path'], {}), '(restore_path)\n', (6886, 6900), False, 'import torch\n'), ((25131, 25161), 'torch.cat', 't... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import copy
import torch
from torchvision import datasets, transforms
from sampling import mnist_iid, mnist_noniid, mnist_noniid_unequal
from sampling import cifar_iid, cifar_noniid
import glob
from os.path import join
import numpy as np
from torch.ut... | [
"pandas.read_csv",
"torchvision.datasets.CIFAR10",
"sampling.cifar_iid",
"torchvision.transforms.Normalize",
"os.path.join",
"torch.utils.data.DataLoader",
"copy.deepcopy",
"torchvision.transforms.RandomHorizontalFlip",
"sampling.mnist_iid",
"PIL.ImageOps.grayscale",
"sampling.cifar_noniid",
"... | [((520, 552), 'numpy.random.permutation', 'np.random.permutation', (['n_samples'], {}), '(n_samples)\n', (541, 552), True, 'import numpy as np\n'), ((4271, 4407), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'mean_dataset', 'batch_size': 'batch_size', 'num_workers': '(0)', 'shuffle': '... |
import numpy as np
# The 'profiles.py' module is unchanged from the previous tutorial.
class Profile:
def __init__(self, centre=0.0, intensity=0.01):
"""Represents an Abstract 1D line profile.
Parameters
----------
centre : float
The x coordinate of the pr... | [
"numpy.divide",
"numpy.subtract",
"numpy.sqrt"
] | [((1807, 1840), 'numpy.subtract', 'np.subtract', (['xvalues', 'self.centre'], {}), '(xvalues, self.centre)\n', (1818, 1840), True, 'import numpy as np\n'), ((3359, 3392), 'numpy.subtract', 'np.subtract', (['xvalues', 'self.centre'], {}), '(xvalues, self.centre)\n', (3370, 3392), True, 'import numpy as np\n'), ((1922, 1... |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import gym
from gym import spaces
from stable_baselines import PPO2
from stable_baselines.common.callbacks import BaseCallback
import numpy as np
import multiprocessing as mp
import json
import time
from collections import... | [
"sys.path.append",
"json.load",
"multiprocessing.current_process",
"traci._trafficlight.Phase",
"time.time",
"collections.defaultdict",
"os.path.isfile",
"numpy.array",
"numpy.linalg.norm",
"traci._trafficlight.Logic",
"stable_baselines.PPO2.load",
"os.path.join",
"sys.exit",
"sumolib.chec... | [((447, 493), 'os.path.join', 'os.path.join', (["os.environ['SUMO_HOME']", '"""tools"""'], {}), "(os.environ['SUMO_HOME'], 'tools')\n", (459, 493), False, 'import os\n'), ((498, 520), 'sys.path.append', 'sys.path.append', (['tools'], {}), '(tools)\n', (513, 520), False, 'import sys\n'), ((531, 590), 'sys.exit', 'sys.ex... |
from __future__ import print_function
import cv2
import numpy as np
import glob, os
#import matplotlib.pyplot as plt
import sys
#import time
import h5py
import random
#from scipy import ndimage
import ntpath
import matplotlib.pyplot as plt
PATCH_PATH = '../h5/data/'
save_path='../h5/normals/'
SIZE_INP... | [
"ntpath.basename",
"numpy.empty",
"numpy.expand_dims",
"numpy.shape",
"ntpath.split",
"numpy.linalg.norm",
"numpy.squeeze",
"numpy.concatenate"
] | [((2361, 2379), 'ntpath.split', 'ntpath.split', (['path'], {}), '(path)\n', (2373, 2379), False, 'import ntpath\n'), ((607, 623), 'numpy.shape', 'np.shape', (['depths'], {}), '(depths)\n', (615, 623), True, 'import numpy as np\n'), ((909, 926), 'numpy.squeeze', 'np.squeeze', (['depth'], {}), '(depth)\n', (919, 926), Tr... |
import torch
import numpy as np
from torch.nn import functional as F
from torch.utils.data.dataloader import DataLoader
from torchvision.datasets import MNIST
import torchvision.transforms as transforms
from simple_deep_neural_net.dnn_model import DNNModel
class MNISTModel:
def __init__(self, batch_size=100):
... | [
"numpy.sum",
"numpy.multiply",
"torch.max",
"simple_deep_neural_net.dnn_model.DNNModel",
"torch.utils.data.dataloader.DataLoader",
"torch.no_grad",
"torch.sum",
"torchvision.transforms.ToTensor"
] | [((654, 739), 'simple_deep_neural_net.dnn_model.DNNModel', 'DNNModel', ([], {'in_features': 'in_features', 'hidden_features': '(32)', 'out_features': 'out_features'}), '(in_features=in_features, hidden_features=32, out_features=out_features\n )\n', (662, 739), False, 'from simple_deep_neural_net.dnn_model import DNN... |
import numpy as np
import pickle
import os
def save_dict_of_features(dict_of_features, language = None, name = 'dict_of_features', path = 'utils/collected_data/', override = False):
if not override:
try:
dictionary = load_obj(name, path)
except:
dictionary = {}
if l... | [
"pickle.dump",
"os.remove",
"os.path.exists",
"pickle.load",
"numpy.array"
] | [((942, 970), 'os.path.exists', 'os.path.exists', (['path_to_file'], {}), '(path_to_file)\n', (956, 970), False, 'import os\n'), ((582, 633), 'pickle.dump', 'pickle.dump', (['dictionary', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(dictionary, f, pickle.HIGHEST_PROTOCOL)\n', (593, 633), False, 'import pickle\n'), ((803, 81... |
"""
Credits:
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2022 <NAME> (Sinergise)
Copyright (c) 2019-2020 <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2019 <NAME>, <NAME> (Sinergise)
This source... | [
"numpy.maximum",
"numpy.ones",
"numpy.product",
"numpy.random.randint",
"numpy.arange",
"eolearn.core.RenameFeatureTask",
"eolearn.core.DeepCopyTask",
"eolearn.core.RemoveFeatureTask",
"numpy.random.rand",
"eolearn.core.ZipFeatureTask",
"pytest.raises",
"numpy.max",
"eolearn.core.MapFeatureT... | [((890, 918), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""patch"""'}), "(name='patch')\n", (904, 918), False, 'import pytest\n'), ((952, 961), 'eolearn.core.EOPatch', 'EOPatch', ([], {}), '()\n', (959, 961), False, 'from eolearn.core import EOPatch, FeatureType, CopyTask, DeepCopyTask, AddFeatureTask, RemoveF... |
# -*- coding: utf-8 -*-
import music21
import pretty_midi
import numpy as np
from music21.stream import Voice
import music21.features.jSymbolic as jSymbolic
# %% ---------------------------------------------------------
#
# Symbolic features computation
#
# -----------------------------------------------------------
... | [
"pretty_midi.Note",
"numpy.zeros",
"pretty_midi.PrettyMIDI",
"numpy.diff",
"pretty_midi.Instrument",
"music21.converter.parse"
] | [((4218, 4242), 'pretty_midi.PrettyMIDI', 'pretty_midi.PrettyMIDI', ([], {}), '()\n', (4240, 4242), False, 'import pretty_midi\n'), ((4291, 4324), 'pretty_midi.Instrument', 'pretty_midi.Instrument', ([], {'program': '(0)'}), '(program=0)\n', (4313, 4324), False, 'import pretty_midi\n'), ((4661, 4687), 'numpy.zeros', 'n... |
# Authors: <NAME> <<EMAIL>>
# License: MIT
from pathlib import Path
import os
import mne
import time
import xarray as xr
import numpy as np
import os.path as op
import pandas as pd
from .simulation import get_epochs_sim
def get_bem_artifacts(template, montage_name="HGSN129-montage.fif", subjects_dir=None, include_v... | [
"mne.datasets.fetch_fsaverage",
"mne.channels.make_standard_montage",
"mne.setup_volume_source_space",
"pathlib.Path",
"mne.compute_covariance",
"numpy.mean",
"numpy.arange",
"mne.get_volume_labels_from_src",
"mne.datasets.fetch_infant_template",
"os.path.join",
"mne.minimum_norm.make_inverse_op... | [((1394, 1437), 'mne.channels.compute_native_head_t', 'mne.channels.compute_native_head_t', (['montage'], {}), '(montage)\n', (1428, 1437), False, 'import mne\n'), ((3182, 3242), 'mne.create_info', 'mne.create_info', (['montage.ch_names'], {'sfreq': '(256)', 'ch_types': '"""eeg"""'}), "(montage.ch_names, sfreq=256, ch_... |
"""
Computational domain for isogeometric analysis.
"""
import os.path as op
import numpy as nm
from sfepy.base.base import assert_, Struct
from sfepy.discrete.common.domain import Domain
import sfepy.discrete.iga as iga
import sfepy.discrete.iga.io as io
from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors
... | [
"sfepy.discrete.fem.geometry_element.create_geometry_elements",
"sfepy.discrete.iga.io.read_iga_data",
"sfepy.discrete.iga.get_bezier_topology",
"sfepy.discrete.common.domain.Domain.__init__",
"numpy.unique",
"sfepy.base.base.Struct",
"numpy.empty_like",
"numpy.isfinite",
"sfepy.discrete.iga.compute... | [((491, 526), 'numpy.asarray', 'nm.asarray', (['degrees'], {'dtype': 'nm.int32'}), '(degrees, dtype=nm.int32)\n', (501, 526), True, 'import numpy as nm\n'), ((696, 809), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': '"""nurbs"""', 'knots': 'knots', 'degrees': 'degrees', 'cps': 'cps', 'weight... |
import numpy as np
import pytest
import resqpy.olio.write_data as wd
from pytest_mock import MockerFixture
def test_write_pure_binary_data(mocker: MockerFixture, caplog):
# Arrange
test_array = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]])
open_mock = mocker.mock_open()
fileno_mock = mocker.Mock(retu... | [
"resqpy.olio.write_data.write_pure_binary_data",
"numpy.array",
"resqpy.olio.write_data.write_array_to_ascii_file"
] | [((204, 250), 'numpy.array', 'np.array', (['[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]'], {}), '([[[0, 0], [0, 0]], [[0, 0], [0, 0]]])\n', (212, 250), True, 'import numpy as np\n'), ((541, 586), 'resqpy.olio.write_data.write_pure_binary_data', 'wd.write_pure_binary_data', (['"""test"""', 'test_array'], {}), "('test', test_ar... |
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import numpy as np
import os
from osgeo import gdal
from helper import write_tif
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
from tensorflow import keras
import tensorflow as tf
import model as m
from common import train_pipe, find_... | [
"warnings.simplefilter",
"model.get_model",
"common.train_pipe",
"numpy.argmax",
"numpy.empty",
"common.find_info",
"numba.njit",
"numpy.expand_dims",
"numpy.where",
"numpy.array",
"numba.prange",
"helper.write_tif",
"osgeo.gdal.Open"
] | [((17, 79), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (38, 79), False, 'import warnings\n'), ((354, 366), 'numba.njit', 'numba.njit', ([], {}), '()\n', (364, 366), False, 'import numba\n'), ((629, 641),... |
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from os import listdir
from os.path import isfile, join
import sys
import scipy.io as sio
import scipy.sparse
import json
PATH_SEG = 'structure/labs'
ROOT_TRACKS = 'tracks'
PATH_INSTRU_ACT = join(ROOT_TRACKS, 'act_in... | [
"json.dump",
"os.makedirs",
"numpy.asarray",
"os.path.exists",
"sys.stdout.flush",
"numpy.random.permutation",
"os.path.join",
"os.listdir"
] | [((295, 325), 'os.path.join', 'join', (['ROOT_TRACKS', '"""act_instr"""'], {}), "(ROOT_TRACKS, 'act_instr')\n", (299, 325), False, 'from os.path import isfile, join\n'), ((1229, 1258), 'os.path.join', 'join', (['PATH_SAVE_PHR', 'save_dir'], {}), '(PATH_SAVE_PHR, save_dir)\n', (1233, 1258), False, 'from os.path import i... |
'''
This script makes a figure showing Spitzer/IRAC colors for redshifted model
spectra. For this figure, the Spitzer/IRAC [3.6]-[4.5] colors are shown for
binary stellar population models and single stellar population models for a
large range of ionization parameters.
---> The stellar population models are BPASS model... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.loadtxt",
"numpy.linspace",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.savefig"
] | [((730, 763), 'numpy.loadtxt', 'np.loadtxt', (['"""Spitzer_IRAC.I1.dat"""'], {}), "('Spitzer_IRAC.I1.dat')\n", (740, 763), True, 'import numpy as np\n'), ((773, 806), 'numpy.loadtxt', 'np.loadtxt', (['"""Spitzer_IRAC.I2.dat"""'], {}), "('Spitzer_IRAC.I2.dat')\n", (783, 806), True, 'import numpy as np\n'), ((2040, 2067)... |
import os
import pathlib
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import sys
import time
import random
from tensorflow.keras.preprocessing.image import load_img,img_to_array
from tensorflow.keras import layers
from multiprocessing.dummy import Pool as ThreadPool
print('Python version:... | [
"numpy.pad",
"random.randint",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"numpy.argmax",
"tensorflow.keras.Input",
"numpy.zeros",
"time.time",
"tensorflow.keras.preprocessing.image.load_img",
"numpy.array",
"matplotlib.pyplot.imsave",
"tensorflow.keras.models.Sequenti... | [((553, 589), 'os.listdir', 'os.listdir', (['"""./training_data_inputs"""'], {}), "('./training_data_inputs')\n", (563, 589), False, 'import os\n'), ((599, 635), 'os.listdir', 'os.listdir', (['"""./training_data_labels"""'], {}), "('./training_data_labels')\n", (609, 635), False, 'import os\n'), ((732, 1205), 'numpy.ar... |
import os
from scipy.sparse import coo_matrix
import torch
import numpy as np
import tables as tb
from src.preprocessing.utils import DATASET_DIR, HDF5_DATASET, DATASET_NAME
from typing import Union, List, Tuple
class UserDataset(torch.utils.data.Dataset):
"""Implements User Dataloader"""
PATH = os.path.join... | [
"torch.logical_and",
"numpy.stack",
"torch.ones",
"torch.stack",
"torch.utils.data.DataLoader",
"torch.sparse_coo_tensor",
"numpy.empty",
"torch.any",
"tables.Filters",
"scipy.sparse.coo_matrix",
"torch.max",
"torch.rand",
"tables.open_file",
"os.path.join",
"torch.tensor",
"torch.from... | [((308, 347), 'os.path.join', 'os.path.join', (['DATASET_DIR', 'HDF5_DATASET'], {}), '(DATASET_DIR, HDF5_DATASET)\n', (320, 347), False, 'import os\n'), ((7992, 8031), 'os.path.join', 'os.path.join', (['DATASET_DIR', 'HDF5_DATASET'], {}), '(DATASET_DIR, HDF5_DATASET)\n', (8004, 8031), False, 'import os\n'), ((14414, 14... |
#! /usr/bin/env python
import numpy as np
import cv2
img = cv2.imread("frclogo.jpg")
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lower_lim = np.array([0,155,155])
upper_lim = np.array([179,255,255])
mask = cv2.inRange(hsv, lower_lim, upper_lim)
cv2.imshow("logo",img)
cv2.imshow("masked",mask)
cv2.waitKey(0)
cv2.destr... | [
"cv2.cvtColor",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imread",
"numpy.array",
"cv2.imshow",
"cv2.inRange"
] | [((61, 86), 'cv2.imread', 'cv2.imread', (['"""frclogo.jpg"""'], {}), "('frclogo.jpg')\n", (71, 86), False, 'import cv2\n'), ((93, 129), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2HSV'], {}), '(img, cv2.COLOR_BGR2HSV)\n', (105, 129), False, 'import cv2\n'), ((142, 165), 'numpy.array', 'np.array', (['[0, 155... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="QJzbCJZ9sIoX"
# ## VQ-VAE and Pixel CNN
#
# Code: https://... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"assembler.assembler",
"assembler.get_config",
"numpy.asarray",
"matplotlib.pyplot.axis",
"torchvision.utils.make_grid",
"torchvision.transforms.functional.to_pil_image",
"os.path.join"
] | [((1739, 1774), 'assembler.get_config', 'get_config', (['"""./configs/vq_vae.yaml"""'], {}), "('./configs/vq_vae.yaml')\n", (1749, 1774), False, 'from assembler import get_config, assembler\n'), ((1781, 1810), 'assembler.assembler', 'assembler', (['config', '"""training"""'], {}), "(config, 'training')\n", (1790, 1810)... |
import os
import pickle
import numpy as np
import torch
import torchvision
import torchvision.transforms as T
import torchvision.transforms.functional as TF
# from torch.utils.data.dataset import Subset
# from torchvision.transforms import (CenterCrop, Compose, RandomHorizontalFlip, Resize, ToTensor)
import pdb
st = ... | [
"torchvision.transforms.functional.to_tensor",
"os.path.exists",
"pickle.load",
"numpy.arange",
"torch.tensor"
] | [((1334, 1359), 'os.path.exists', 'os.path.exists', (['data_path'], {}), '(data_path)\n', (1348, 1359), False, 'import os\n'), ((1513, 1540), 'os.path.exists', 'os.path.exists', (['latent_path'], {}), '(latent_path)\n', (1527, 1540), False, 'import os\n'), ((5824, 5849), 'os.path.exists', 'os.path.exists', (['data_path... |
import tensorflow as tf
import numpy as np
import os
ALPHA_EPS = 1e-10
##########################
# Homography/matrix math for MPIs and plane sweep volumes
##########################
# Don't remember why I redefined matrix multiply
# but I'm sure I had a good reason at the time
def tfmm(A, B):
with tf.varia... | [
"tensorflow.cond",
"tensorflow.meshgrid",
"tensorflow.reduce_sum",
"tensorflow.clip_by_value",
"tensorflow.cumsum",
"tensorflow.reshape",
"tensorflow.zeros_like",
"tensorflow.logical_and",
"tensorflow.variable_scope",
"tensorflow.concat",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.sq... | [((10414, 10436), 'tensorflow.expand_dims', 'tf.expand_dims', (['pix', '(0)'], {}), '(pix, 0)\n', (10428, 10436), True, 'import tensorflow as tf\n'), ((10497, 10548), 'tensorflow.logical_and', 'tf.logical_and', (['(pix_y <= pose.h - 1.0)', '(pix_y >= 0.0)'], {}), '(pix_y <= pose.h - 1.0, pix_y >= 0.0)\n', (10511, 10548... |
import numpy as np
ignore_label = 255
id2label = {-1: ignore_label, 0: ignore_label, 1: ignore_label, 2: ignore_label,
3: ignore_label, 4: ignore_label, 5: ignore_label, 6: ignore_label,
7: 0, 8: 1, 9: ignore_label, 10: ignore_label, 11: 2, 12: 3, 13: 4,
14: ignore_label, 15: ignore... | [
"numpy.ones"
] | [((1103, 1137), 'numpy.ones', 'np.ones', (['arr.shape'], {'dtype': 'np.uint8'}), '(arr.shape, dtype=np.uint8)\n', (1110, 1137), True, 'import numpy as np\n')] |
import util
import numpy as np
import pandas as pd
import json
outputdir = 'output/HEAT'
util.ensure_dir(outputdir)
dataurl = 'input/HEAT/'
dataname = outputdir + '/HEAT'
idset = set()
geo = []
for i in range(41):
geo.append([str(i), 'Point', '[]'])
geo = pd.DataFrame(geo, columns=['geo_id', 'type', 'coordinates... | [
"pandas.DataFrame",
"numpy.genfromtxt",
"util.ensure_dir"
] | [((90, 116), 'util.ensure_dir', 'util.ensure_dir', (['outputdir'], {}), '(outputdir)\n', (105, 116), False, 'import util\n'), ((263, 323), 'pandas.DataFrame', 'pd.DataFrame', (['geo'], {'columns': "['geo_id', 'type', 'coordinates']"}), "(geo, columns=['geo_id', 'type', 'coordinates'])\n", (275, 323), True, 'import pand... |
"""
@Overview:
Implement Training ResNet 10 for Speaker Verification!
Enrollment set files will be in the 'Data/enroll_set.npy' and the classes-to-index file is 'Data/enroll_classes.npy'
Test set files are in the 'Data/test_set.npy' and the utterances-to-index file is 'Data/test_classes.npy'.
Training the ... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.cat",
"os.path.isfile",
"torch.nn.Softmax",
"Process_Data.audio_processing.truncatedinput",
"time.asctime",
"torch.utils.data.DataLoader",
"torch.load",
"torch.nn.TripletMarginLoss",
"Process_Data.audio_processing.concateinputfromMFB",
"Pr... | [((1956, 1989), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1979, 1989), False, 'import warnings\n'), ((2021, 2087), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch Speaker Recognition"""'}), "(description='PyTorch Speaker Recogni... |
import sys
import tensorflow as tf
import numpy as np
import time
from six.moves import xrange
#from inspect import signature
class FGSM:
def __init__(self, sess, model, eps, use_log=True, targeted=True, batch_size=1, ord=np.inf, clip_min=-0.5, clip_max=0.5):
"""
The implementation of Ian Goodfello... | [
"tensorflow.reduce_sum",
"tensorflow.abs",
"tensorflow.clip_by_value",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.stop_gradient",
"numpy.zeros",
"tensorflow.sign",
"tensorflow.square",
"tensorflow.gradients",
"tensorflow.sqrt"
] | [((1820, 1855), 'tensorflow.gradients', 'tf.gradients', (['self.adv_loss', 'self.x'], {}), '(self.adv_loss, self.x)\n', (1832, 1855), True, 'import tensorflow as tf\n'), ((3100, 3158), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['self.adv_x', 'self.clip_min', 'self.clip_max'], {}), '(self.adv_x, self.clip_min, se... |
from .tissueStack import *
from .pulse import *
from typing import Union
import numpy as np
__all__ = ['Tissue', 'RandomTissue2D']
class Tissue:
def __init__(self, stacks: List[TissueStack] = None, height=None, width=None, depth=None):
""" A collection of TissueStacks to act as a tissue sample. """
... | [
"numpy.full",
"numpy.random.uniform",
"numpy.moveaxis",
"numpy.zeros",
"numpy.sin",
"numpy.take",
"numpy.arange",
"numpy.linspace",
"numpy.concatenate"
] | [((4893, 4993), 'numpy.concatenate', 'np.concatenate', (['[self.scattDensity[None, :, :], self.opticAxis, self.birefringence[None, :, :]]'], {}), '([self.scattDensity[None, :, :], self.opticAxis, self.\n birefringence[None, :, :]])\n', (4907, 4993), True, 'import numpy as np\n'), ((8950, 8996), 'numpy.random.uniform... |
import numpy as np
from divide import Predicate
from node import Node
class DecisionTree:
def build(self, X, y):
self.root = self.build_subtree(X, y)
return self
def build_subtree(self, X, y):
predicate = DecisionTree.get_best_predicate(X, y)
if predicate:
X1, y1, ... | [
"node.Node",
"divide.Predicate",
"numpy.unique",
"numpy.argmax"
] | [((478, 587), 'node.Node', 'Node', ([], {'column': 'predicate.column', 'value': 'predicate.value', 'true_branch': 'true_branch', 'false_branch': 'false_branch'}), '(column=predicate.column, value=predicate.value, true_branch=\n true_branch, false_branch=false_branch)\n', (482, 587), False, 'from node import Node\n')... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker, cm
def bivariate_norm_distr(X,Y):
"""
Evaluates on a bivariate gaussian distribution
:param X: ndarray (pass heights)
:param Y: ndarray (pass weights)
:return: ndarray of probabilities for (x,y) in zip(X,Y)
"""
... | [
"matplotlib.pyplot.title",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"numpy.std",
"numpy.corrcoef",
"matplotlib.pyplot.legend",
"numpy.apply_along_axis",
"numpy.mean",
"numpy.array",
"numpy.loadtxt",
"numpy.linspace",
"numpy.exp",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
... | [((598, 611), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (606, 611), True, 'import numpy as np\n'), ((963, 991), 'numpy.apply_along_axis', 'np.apply_along_axis', (['f', '(0)', 'X'], {}), '(f, 0, X)\n', (982, 991), True, 'import numpy as np\n'), ((1099, 1170), 'numpy.loadtxt', 'np.loadtxt', (['"""whData.dat"""... |
import gc
import multiprocessing as mp
import time
import warnings
from threading import Thread
from typing import List, Optional
import numpy as np
import pandas as pd
import psutil
import scipy.sparse as sps
import tabmat as tm
from glum import GeneralizedLinearRegressor
from glum_benchmarks.cli_run import get_all_... | [
"scipy.sparse.issparse",
"gc.collect",
"multiprocessing.cpu_count",
"glum_benchmarks.util.get_sklearn_family",
"glum_benchmarks.cli_run.get_all_problems",
"threading.Thread",
"scipy.sparse.spdiags",
"time.sleep",
"numpy.linalg.inv",
"multiprocessing.Pool",
"glum.GeneralizedLinearRegressor",
"m... | [((1614, 1629), 'scipy.sparse.issparse', 'sps.issparse', (['x'], {}), '(x)\n', (1626, 1629), True, 'import scipy.sparse as sps\n'), ((2072, 2084), 'gc.collect', 'gc.collect', ([], {}), '()\n', (2082, 2084), False, 'import gc\n'), ((2569, 2581), 'gc.collect', 'gc.collect', ([], {}), '()\n', (2579, 2581), False, 'import ... |
"""Výpočet a vykreslení Wan-Sunova podivného atraktoru."""
# coding: utf-8
# # The Wang - Sun attractor
# Please also see https://hipwallpaper.com/view/9W3CM8
# In[1]:
# import všech potřebných knihoven - Numpy a Matplotlibu
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np... | [
"numpy.stack",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.min",
"numpy.max",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.... | [((822, 836), 'numpy.zeros', 'np.zeros', (['(n,)'], {}), '((n,))\n', (830, 836), True, 'import numpy as np\n'), ((841, 855), 'numpy.zeros', 'np.zeros', (['(n,)'], {}), '((n,))\n', (849, 855), True, 'import numpy as np\n'), ((860, 874), 'numpy.zeros', 'np.zeros', (['(n,)'], {}), '((n,))\n', (868, 874), True, 'import num... |
"""
This routine calculates the radar moments for the RPG 94 GHz FMCW radar 'LIMRAD94' and generates a NetCDF4 file.
The generated files can be used as input for the Cloudnet processing chain.
Args:
**date (string): format YYYYMMDD
**path (string): path where NetCDF file will be stored
Example:
python spe... | [
"numpy.ma.sum",
"numpy.sum",
"numpy.amin",
"numpy.argmax",
"numpy.ma.masked_less_equal",
"numpy.isnan",
"numpy.mean",
"sys.path.append",
"numpy.full",
"numpy.var",
"pyLARDA.helpers.lin2z",
"numpy.divide",
"numpy.nansum",
"copy.deepcopy",
"numpy.ma.masked_where",
"pyLARDA.helpers.z2lin"... | [((430, 461), 'sys.path.append', 'sys.path.append', (['"""../../larda/"""'], {}), "('../../larda/')\n", (445, 461), False, 'import sys\n'), ((462, 482), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (477, 482), False, 'import sys\n'), ((627, 660), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'f... |
# -*- coding: utf-8 -*-
r"""
Updates to the thin SVD using NumPy.
This function is a SAGE replication of <NAME> article on "Fast low-rank modifications
of the thin singular value decomposition." <http://www.stat.osu.edu/~dmsl/thinSVDtracking.pdf>
This function is an approximation to the true thin SVD, therefore, no test... | [
"numpy.multiply",
"numpy.zeros",
"numpy.transpose",
"numpy.linalg.eig",
"numpy.append",
"numpy.linalg.norm",
"numpy.reshape",
"numpy.linalg.inv",
"numpy.array",
"numpy.dot",
"numpy.add",
"numpy.diag"
] | [((4489, 4506), 'numpy.linalg.norm', 'np.linalg.norm', (['p'], {}), '(p)\n', (4503, 4506), True, 'import numpy as np\n'), ((4639, 4656), 'numpy.linalg.norm', 'np.linalg.norm', (['q'], {}), '(q)\n', (4653, 4656), True, 'import numpy as np\n'), ((4721, 4763), 'numpy.zeros', 'np.zeros', (['(k.shape[0] + 1, k.shape[0] + 1)... |
#!/usr/bin/env python
version = '1.2'
'''
PSF: PHOTOMETRY SANS FRUSTRATION
Written by <NAME>, 2015-2022
Requirements:
Needs photutils, astropy, numpy, matplotlib, skimage, requests, astroquery, astroalign.
Also pyzogy if running with template subtraction.
Previously in IRAF, completely re-... | [
"os.remove",
"astroquery.sdss.SDSS.get_images",
"argparse.ArgumentParser",
"photutils.utils.calc_total_error",
"matplotlib.pyplot.clf",
"numpy.nanmedian",
"photutils.aperture_photometry",
"matplotlib.pyplot.subplot2grid",
"astropy.io.fits.PrimaryHDU",
"astropy.stats.sigma_clipped_stats",
"numpy.... | [((3010, 3043), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (3033, 3043), False, 'import warnings\n'), ((3075, 3100), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3098, 3100), False, 'import argparse\n'), ((14407, 14429), 'matplotlib.pyplot.f... |
import tensorflow as tf
import numpy as np
from algorithms.ddpg.replay_buffer import ReplayBuffer
from algorithms.common.layers import mlp
class DDPGAgent(object):
"""
The basic DDPG agent
"""
def __init__(self, env, params, build_network=True, *args):
# Copy params
self.st... | [
"tensorflow.control_dependencies",
"tensorflow.trainable_variables",
"tensorflow.get_collection",
"tensorflow.global_variables_initializer",
"tensorflow.stop_gradient",
"tensorflow.constant_initializer",
"tensorflow.reduce_mean",
"algorithms.ddpg.replay_buffer.ReplayBuffer",
"tensorflow.variable_sco... | [((1064, 1141), 'algorithms.ddpg.replay_buffer.ReplayBuffer', 'ReplayBuffer', (['self.state_dim', 'self.action_dim', 'self.mem_size', 'self.batch_size'], {}), '(self.state_dim, self.action_dim, self.mem_size, self.batch_size)\n', (1076, 1141), False, 'from algorithms.ddpg.replay_buffer import ReplayBuffer\n'), ((1193, ... |
"""
Description:
1) 使用nltk包中的bleu计算工具来进行辅助计算
"""
import numpy as np
import re
from nltk.translate.bleu_score import corpus_bleu
def my_bleu_v1(candidate_token, reference_token):
"""
:description:
最简单的计算方法是看candidate_sentence 中有多少单词出现在参考翻译中, 重复的也需要计算.
计算出的数量作为分子,分母是candidate中的单词数量
... | [
"numpy.sum",
"numpy.power",
"numpy.max",
"re.findall",
"numpy.min"
] | [((828, 843), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (834, 843), True, 'import numpy as np\n'), ((1010, 1045), 're.findall', 're.findall', (['gram_sub_str', 'candidate'], {}), '(gram_sub_str, candidate)\n', (1020, 1045), False, 'import re\n'), ((767, 794), 'numpy.power', 'np.power', (['item', 'weights... |
import numpy as np
import tflearn
import tensorflow as tf
import random
def to_bits(str):
'''
Converts a string s to an array of bits of the composing characters
'''
result = []
for c in str:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
... | [
"tflearn.fully_connected",
"random.shuffle",
"tensorflow.reset_default_graph",
"tflearn.regression",
"tflearn.DNN",
"numpy.array",
"tflearn.initializations.uniform"
] | [((823, 847), 'random.shuffle', 'random.shuffle', (['training'], {}), '(training)\n', (837, 847), False, 'import random\n'), ((861, 879), 'numpy.array', 'np.array', (['training'], {}), '(training)\n', (869, 879), True, 'import numpy as np\n'), ((987, 1011), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.