arxiv_id
stringlengths
0
16
text
stringlengths
10
1.65M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 8 14:44:34 2018 @author: jack.lingheng.meng """ import tensorflow as tf import numpy as np import time import gym from Environment.LASEnv import LASEnv from LASAgent.RandomLASAgent import RandomLASAgent from LASAgent.LASAgent_Actor_Critic import...
import numpy as np from scipy.spatial.distance import cdist K = lambda x, y, bw: np.exp(-0.5*cdist(x, y, 'sqeuclidean') / bw**2) def mmd(x: np.ndarray, y: np.ndarray, bw: float) -> float: """Computes the maximum mean discrepancy between two samples. This is a measure of the similarity of two distributions th...
from os.path import dirname, abspath import numpy as np import cv2 import matplotlib.pyplot as plt # Global constants and parameters OUTPUT_DIR = dirname(dirname(abspath(__file__))) + "/output_images/" LANE_REGION_HEIGHT = 0.63 # top boundary (% of ysize) LANE_REGION_UPPER_WIDTH = 0.05 # upper width (% of ysiz...
import json import argparse import tensorflow.keras as keras import numpy as np import tensorflow as tf from image_quality_assessment.utils import utils import grpc from tensorflow_serving.apis import predict_pb2, prediction_service_pb2_grpc TFS_HOST = 'localhost' TFS_PORT = 8500 def normalize_labels(labels): la...
import math from PIL import Image import numpy as np import filterdata as fd import config import scipy.misc imagesbase = config.imagesbase fullpath = config.fullpath outputdir = config.outputdir outputdir1 = config.outputdir if fullpath else '' idx = 0 cnttxt = 0; cntnon = 0; phasenames = ['train', 'val'] for phase i...
from datetime import datetime, timedelta from services.log_service import LogService import torch import numpy as np from entities.metric import Metric from entities.data_output_log import DataOutputLog class LogServiceFake(LogService): def __init__(self): pass def log_progress( self, ...
## same as the analytic case but with the fft import numpy as np import matplotlib.pyplot as plt from numpy.linalg import cond import cmath; from scipy import linalg as LA from numpy.linalg import solve as bslash import time from convolution_matrices.convmat1D import * from RCWA_1D_functions.grating_fft.gratin...
#import libraries import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import seaborn from matplotlib import pyplot as plt from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix from sklearn.metrics...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from pathlib import Path import pathlib import os import zipfile from multiprocessing import Pool import datetime from dateutil.relativedelta import relativedelta def df_from_csv_with_geo(file_path, nrows=None): """Extract useful columns from ...
from dataclasses import dataclass import gc from torch import optim import numpy as np import random import os from src.models import * # To eliminate randomness def seed_everything(seed: int = 77): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(s...
from __future__ import print_function import os import glob # may cause segmentation fault in (C+Python) environment import numpy as np import cv2 import csv import faiss import pandas as pd import utm ### For dataset import torch import torch.nn.functional as F from torch.utils.data import Dataset from ...
from numpy.testing import assert_almost_equal, assert_raises import numpy as np from id3.data import load_data import uuid X = np.arange(20).reshape(10, 2) y = np.arange(10).reshape(10, ) def test_load_data(): assert_raises(IOError, load_data.load_data, str(uuid.uuid4())) X_, y_, _ = load_data.load_data("tes...
import numpy as np import time from datetime import timedelta def sum_1to1000(): ret = 0 for i in range(1, 1001): ret += i return ret def sum_1to1000_nparray(): a = np.ones(1000) b = np.arange(1,1001) return int(a.dot(b)) pass if __name__ == "__main__": start = time.time() ...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import numpy as np from svm_model import SVM_Model from svm_model import SVM_Model from sklearn.datasets import load_iris ...
import unittest import shapely import numpy as np from mlx.od.nms import compute_nms, compute_iou class TestNMS(unittest.TestCase): def test_iou(self): geom1 = shapely.geometry.box(0, 0, 4, 4) geom2 = shapely.geometry.box(2, 2, 6, 6) iou = compute_iou(geom1, geom2) self.assertEqua...
from sympy import * from tait_bryan_R_utils import * x_t, y_t, z_t = symbols('x_t y_t z_t') px, py, pz = symbols('px py pz') om, fi, ka = symbols('om fi ka') pxc, pyc, pzc = symbols('pxc pyc pzc') omc, fic, kac = symbols('omc fic kac') om_mirror = symbols('om_mirror') ray_dir_x, ray_dir_y, ray_dir_z, ray_length = symb...
""" Random choices functions Copyright (c) 2019 Julien Kervizic Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt WIDTH = 12 HEIGHT = 3 plt.rcParams['font.size'] = 14 plt.rcParams['legend.fontsize'] = 14 plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['ps.fonttype'] = 42 plt.rcParams['font.family'] = 'Times New Roman' SCHEDULELIST = [1,1,25] ARMSLIST ...
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import numpy as np import torch from perfectpitch.onsetsdetector.model import OnsetsDetector from perfectpitch.utils.transcription import pianoroll_to_transcription class Transcriber: def __init__(self, onsets_detector_path, device): self._device = torch.device(device) self._onsets_detector = On...
import os import numpy as np import time import sys from PIL import Image import cv2 import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms from DensenetModels import DenseNet121 from DensenetModels import DenseNet169 from DensenetModels...
# Copyright 2022 The DDSP Authors. # # 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 wri...
#//////////////////////////////////////////////////////////////// #// #// Python modules #// #// ------------------------------------------------------------- #// #// AUTHOR: Miguel Ramos Pernas #// e-mail: miguel.ramos.pernas@cern.ch #// #// Last update: 04/10/2017 #// #// -----------------------------------------...
""" Primary function of recipe here """ import mbuild as mb import numpy as np from numpy import sqrt, pi, arctan2, arcsin class build_silica_NP(mb.Compound): """ Build a tethered_NP compound. Example would be a silica nanoparticle covered in alkane chains Parameters ---------- Args: n_c...
import argparse import logging import os, sys import csv import numpy as np import random import time from run_ple_utils import make_ple_env def main_event_dependent(): parser = argparse.ArgumentParser() parser.add_argument('--test_env', help='testv environment ID', default='ContFlappyBird-v3') parser.add...
"""Function to show an example of the created points of the sampler. """ import numpy as np import matplotlib.pyplot as plt def scatter(subspace, *samplers): """Shows (one batch) of used points in the training. If the sampler is static, the shown points will be the points for the training. If not the po...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2017 by University of Kassel and Fraunhofer Institute for Wind Energy and # Energy System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed # by a BSD-style license that can be found in the LICENSE file. import numpy as np import pytest i...
from sklearn.ensemble import RandomForestRegressor import time from sklearn.base import BaseEstimator from typing import Optional, Dict, Union, Tuple import pandas as pd import numpy as np from sklearn.linear_model import RidgeCV def train_ridge_lr_model( xtrain: Union[np.ndarray, pd.DataFrame], ytrain: Union...
import unittest import numpy as np import numpy.testing as npt import wisdem.drivetrainse.layout as lay npts = 12 ct = np.cos(np.deg2rad(5)) st = np.sin(np.deg2rad(5)) class TestDirectLayout(unittest.TestCase): def setUp(self): self.inputs = {} self.outputs = {} self.discrete_inputs = {}...
# -*- coding: utf-8 -*- """ Written by Daniel M. Aukes Email: danaukes<at>gmail.com Please see LICENSE for full license. """ import pynamics from pynamics.frame import Frame from pynamics.variable_types import Differentiable,Constant,Variable from pynamics.system import System from pynamics.body import Body from pynam...
"""Provides data structures for encapsulating loss data.""" import numpy class Loss: """Encapsulates training loss data. .. py:attribute:: label A string that will be used in graph legends for this loss data. .. py:attribute:: loss_values A numpy.ndarray containing the training loss dat...
""" This file is the main source file of the ProcessMCRaT library which is used to read and process the results of a MCRaT simulation Written by: Tyler Parsotan April 2021 """ import os import astropy as ap import h5py as h5 import numpy as np from astropy import units as u from astropy import constants as const from...
from DataSocket import TCPSendSocket, RAW, TCPReceiveSocket import time import numpy as np import threading import sys send_port = 4242 receive_port = 4343 ip = '0.0.0.0' start_time = time.time() # define function to print the echo back from matlab def print_data(data): global start_time now = time.time() ...
import copy import numpy as np import torch from sklearn.cluster import KMeans from utils.checkings import * from torch.optim.lr_scheduler import LambdaLR os.environ["OMP_NUM_THREADS"] = "8" # Limit the CPU usage during KMeans clustering def create_folders(names, data_dir): datasets = ["ethucy", "SDD"] folde...
""" Copyright 2019 Zachary Phillips, Waller Lab, University of California, Berkeley Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of cond...
#!/usr/bin/env python3 # Copyright 2017 Christian Henning # # 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 l...
#!/usr/bin/env python3s import os.path import tensorflow as tf import helper import warnings from distutils.version import LooseVersion import project_tests as tests from tqdm import tqdm import numpy as np KEEP_PROB = 0.8 #lower value will help generalize more (but with fewer epochs, higher keep_prob creates more cle...
''' File: get_historical.py Authors: Prakash Dhimal, Kevin Sanford Description: Python module to get historical prices and volumes for a given company ''' import numpy as np import normalize as scale ''' @param - historical - list containing historical prices, and volumes @retruns opening - list containing dail...
# Copyright 2016 The TensorFlow 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 ...
import numpy as np def test_generate_minimax_move(): """ First checking whether the agent can return an action. Then it asserts the agent will producing valid move. Next, it will test if the agent can produce a winning move given a board state """ from agents.agent_minimax import generate_...
import sys sys.dont_write_bytecode = True import numpy as np import scipy.sparse as sp from network_propagation_methods import sample_data, netprop, minprop_2, minprop_3 #### Parameters ############# # convergence threshold eps = 1e-6 # maximum number of iterations max_iter = 1000 # diffusion parameters alphaP, alpha...
import numpy as np import os from datetime import datetime from pytz import timezone import matplotlib.pyplot as plt from agent_qlean import QLearnAgent from agent_bandit import BanditAgent from environment import Environment from simulator import parameters from simulator.transaction_model import TransactionModel from...
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PyTorchDisentanglement.utils.file_utils import Logger class BaseModel(nn.Module): def __init__(self): super(BaseModel, self).__init__() self.params_loaded = False def setup(self, params, logge...
import os import re import itertools import cv2 import time import numpy as np import torch from torch.autograd import Variable from utils.craft_utils import getDetBoxes, adjustResultCoordinates from data import imgproc from data.dataset import SynthTextDataSet import math import xml.etree.ElementTree as elemTree #...
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x, y = np.random.rand(2, 100) * 4 hist, xedges, yedges = np.histogram2d(x, y, bins=4) elements = (len(xedges) - 1) * (len(yedges) - 1) xpos, ypos = np.meshgrid(xedge...
from jaxns.nested_sampling import NestedSampler from jaxns.prior_transforms import PriorChain, MVNDiagPrior, UniformPrior, GaussianProcessKernelPrior, HalfLaplacePrior,MVNPrior from jaxns.plotting import plot_cornerplot, plot_diagnostics from jaxns.gaussian_process.kernels import RBF from jax.scipy.linalg import solve_...
from tqdm import tqdm import numpy as np from dataclasses import dataclass from typing import Dict, List, Tuple, Union import ipdb import collections import random import torch from copy import deepcopy from torch.nn.utils.rnn import pad_sequence from transformers.tokenization_utils_base import BatchEncoding def _sa...
from cupy import _util # expose cache handles to this module from cupy.fft._cache import get_plan_cache # NOQA from cupy.fft._cache import clear_plan_cache # NOQA from cupy.fft._cache import get_plan_cache_size # NOQA from cupy.fft._cache import set_plan_cache_size # NOQA from cupy.fft._cache import get_plan_cache...
import numpy as np import mdtraj as md import pytest from scattering.utils.io import get_fn from scattering.utils.run import run_total_vhf, run_partial_vhf @pytest.mark.parametrize("step", [1, 2]) def test_run_total_vhf(step): trj = md.load(get_fn("spce.xtc"), top=get_fn("spce.gro")) chunk_length = 4 n_...
import tensorflow as tf from tensorflow import keras print(tf.VERSION) print(tf.keras.__version__) from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.inception_v3 import preprocess_input import numpy as np import argparse import matplotlib.pyplot as plt import json parser = argparse....
"""Utility functions module.""" import cvxpy as cp import datetime import logging import numpy as np import os import pandas as pd import plotly.graph_objects as go import plotly.io as pio import psychrolib import pvlib import re import scipy.sparse import subprocess import sys import time import typi...
"""Prepare CelebAHQ dataset""" import os import torch import numpy as np from PIL import Image from .segbase import SegmentationDataset class CelebaHQSegmentation(SegmentationDataset): NUM_CLASS = 15 def __init__(self, root='/home/mo/datasets/face_mask/', split='train', mode=None, transform=None, **kwargs):...
""" Test functions for the shoyu.py module """ import os import pickle import numpy as np from ramannoodles import shoyu # open spectra library SHOYU_DATA_DICT = pickle.load(open('raman_spectra/shoyu_data_dict.p', 'rb')) def test_download_cas(): """ Test function that confirms that the raman_spectra/ directo...
import numpy as np import pandas as pd from pandas.io.parsers import read_csv from BOAmodel import * from collections import defaultdict """ parameters """ # The following parameters are recommended to change depending on the size and complexity of the data N = 2000 # number of rules to be used in SA_patternbase...
import sys import os sys.path.insert( 0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")) ) import torch import torch.nn.functional as F import numpy as np import imageio import util import warnings from data import get_split_dataset from render import NeRFRenderer from model import make_mode...
from config import TIMITConfig from argparse import ArgumentParser from multiprocessing import Pool import os from TIMIT.dataset import TIMITDataset if TIMITConfig.training_type == 'H': from TIMIT.lightning_model_h import LightningModel else: from TIMIT.lightning_model import LightningModel from sklearn.met...
""" Generate data for the diffusion forward model. Author: Panagiotis Tsilifis Date: 6/12/2014 """ import numpy as np import fipy as fp import os import matplotlib.pyplot as plt # Make the source nx = 101 ny = nx dx = 1./101 dy = dx rho = 0.05 q0 = 1. / (np.pi * rho ** 2) T = 0.3 mesh = fp.Grid2D(dx=dx...
""" setup.py file for SWIG example """ from distutils.core import setup, Extension import numpy polyiou_module = Extension('_polyiou', sources=['polyiou_wrap.cxx', 'polyiou.cpp'], ) setup(name = 'polyiou', version = '0.1', author = "SWIG Docs", ...
# -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding Ltd. # # 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 require...
""" author: Junxian Ye time: 12/22/2016 link: https://github.com/un-knight/coursera-machine-learning-algorithm """ import numpy as np import pandas as pd import sklearn.svm import seaborn as sns from matplotlib import pyplot as plt from func import tools def gaussian_kernel(x1, x2, sigma=1.0): diff = x1 - x2 ...
from __future__ import division import math import numpy as np import unittest from chainer import testing from chainercv.utils import tile_images @testing.parameterize(*testing.product({ 'fill': [128, (104, 117, 123), np.random.uniform(255, size=(3, 1, 1))], 'pad': [0, 1, 2, 3] })) class TestTileImages(uni...
import numpy as np import time class mpc_controller(): def __init__(self, env, dyn_model, horizon = 20, cost_fn = None, num_simulated_paths = 1000,): self.env = env self.dyn_model = dyn_model self.horizon =...
# -*- coding: utf-8 -*- # Author: Jiajun Ren <jiajunren0522@gmail.com> import os import numpy as np import pytest from renormalizer.spectra import SpectraOneWayPropZeroT, SpectraTwoWayPropZeroT, SpectraExact from renormalizer.spectra.tests import cur_dir from renormalizer.tests import parameter from renormalizer.uti...
import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import math import torch.nn.functional as F import pdb from mmd_comp import MultipleKernelMaximumMeanDiscrepancy, JointMultipleKernelMaximumMeanDiscrepancy from kernels import GaussianKernel def Entropy(input_): bs = input_.s...
"""Unittests for the functions in svid_location, using the true data from 2020-02-11.""" import unittest import numpy.testing as npt import pandas.testing as pt from itertools import product import numpy as np import math from scipy.special import expit from gnssmapper.algo.FPL import FourParamLogisticRegression c...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import json SUMMARY_LOG_SAVE_PATH = "" DENSENET_MODEL_PREDICT_RESULT_FILE = "" RESNET_MODEL_PREDICT_RESULT_FILE = "" XCEPTION_MODEL_PREDICT_RESULT_FILE = "" def Var...
import numpy as np import time from .gdtwcpp import solve from .signal import signal from .utils import process_function class GDTW: def __init__(self): # generic input vars self.x = None self.x_a = None self.x_f = None self.y ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 14 14:34:24 2022 @author: Manuel Huber """ import os.path import multiprocessing from multiprocessing import Process, Manager import ee import geemap import numpy as np Map = geemap.Map() import matplotlib.pyplot as plt from colour import Color #from ...
import sys import os import time from json_tricks.np import dump, load from functools import reduce import numpy as np import tensorflow as tf from sklearn.linear_model import LinearRegression # from scipy.sparse import hstack, csr_matrix, csr import pandas as pd import edward as ed from edward.models import Normal i...
# Image-based testing borrowed from vispy """ Procedure for unit-testing with images: Run individual test scripts with the PYQTGRAPH_AUDIT environment variable set: $ PYQTGRAPH_AUDIT=1 python pyqtgraph/graphicsItems/tests/test_PlotCurveItem.py Any failing tests will display the test results, standard...
# -*- coding: utf-8 -*- # Copyright 2021 Huawei Technologies Co., Ltd # # 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 app...
#!/usr/bin/env python import random, math import numpy as np import game from randomPlayer import RandomPlayer import play class OmniscientAdversary: def __init__(self, nPlay): self._rp = RandomPlayer() self._rand = random.Random() self._epsSame = 1e-6 self._nPlay = nPlay def ...
# coding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License...
import os import streamlit.components.v1 as components import streamlit as st import time import numpy as np import IPython.display as ipd #ipd.Audio(audio, rate=16000) from online_scd.model import SCDModel from online_scd.streaming import StreamingDecoder import timeit import base64 import scipy.io.wavfile from on...
''' 03_WindyGridWorld_nStepSARSA_OffPolicy.py : n-step off-policy SARSA applied to Windy Grid World problem (Example 6.5) Cem Karaoguz, 2020 MIT License ''' import numpy as np import pylab as pl from IRL.environments.Gridworlds import StochasticGridWorld from IRL.agents.TemporalDifferenceLearning import nStepOffPoli...
from competition_and_mutation import Competition, MoranStyleComp, normal_fitness_dist, uniform_fitness_dist from colourscales import get_colourscale_with_random_mutation_colour import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np def example1(): # Run a single simulation of algorithm 1 ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging import unittest import numpy as np # pyre-fixme[21]: Could not find module `pytest`. import pytest # pyre-fixme[21]: Could not find `pyspark`. from pyspark.sql.functions import asc # pyre-fixme[21]: Could ...
from __future__ import division, print_function, absolute_import import time import numpy as np import tensorflow as tf from scipy.stats.mstats import gmean from tefla.da import tta from tefla.da.iterator import BatchIterator from tefla.utils import util class PredictSessionMixin(object): def __init__(self, we...
import os import logging import queue import re import shutil import string import torch import torch import torch.nn as nn import torch.nn.functional as F import tqdm import numpy as np import ujson as json from torch.utils.data import Dataset def masked_softmax(logits, mask, dim=-1, log_softmax=False): """Take ...
import numpy as np import itertools as it #solve #A.T*Ax=A.T*b #x=inv(A.T*A)*A.T*b #Z=inv(H.T*H)*H.T*y def min2_mtx(A,b): x=np.matmul(A.T,A) x=np.linalg.inv(x) x=np.matmul(x,A.T) x=np.matmul(x,b) return x #euler #t time array #y0 init value #f function f(t,y) def euler(t,y0,f): h=t[1]-t[0] ...
# -*- coding: utf-8 -*- """ Created on Sat May 25 14:21:27 2019 @author: Tin """ import numpy as np import pandas as pd import datetime from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import warnings ...
#!python3 # ##----------------------------------------## # # Author: M. Burak Yesilyurt # # Truss Optimization by Employing # # Genetic Algorithms # # ##----------------------------------------## # # Importing necessary modules # To run the code below, imported...
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
""" populates Vivus() with all geometric quantities including Diameter() which carries (x,y) coordinates of min/max diameter endpoints and pixel length values """ import logging import numpy as np from itertools import product as iterp from . import params as p mlg = logging.getLogger(__name__) def xys2dists(...
import logging import os import pickle from collections import defaultdict from typing import Dict import h5py # type: ignore import numpy as np from probing_project.utils import Observation from rich.progress import track from torch.nn import CrossEntropyLoss from .pos_task import POSTask logger = logging.getLogge...
# -*- coding: utf-8 -*- """ shepherd.calibration ~~~~~ Provides CalibrationData class, defining the format of the SHEPHERD calibration data :copyright: (c) 2019 by Kai Geissdoerfer. :license: MIT, see LICENSE for more details. """ import yaml import struct from scipy import stats import numpy as np from pathlib imp...
import numpy as np import copy from operator import itemgetter # from sympy import expand def rollout_policy_fn(board): """a coarse, fast version of policy_fn used in the rollout phase.""" # rollout randomly action_probs = np.random.rand(len(board.availables)) return zip(board.availables, ac...
#!/usr/bin/env python3 # # Converter from Keras saved NN to JSON """ ____________________________________________________________________ Variable specification file In additon to the standard Keras architecture and weights files, you must provide a "variable specification" json file with the following format: { ...
import pandas as pd import numpy as np from sklearn import datasets from Kmeans_python.fit import fit # Test function for center def test_edge(): test_df = pd.DataFrame({'X1': np.zeros(10), 'X2': np.ones(10)}) centers, labels = fit(test_df, 1) print(labels) assert centers.all() == np.array([0, 1])....
""" Analytics Vidhya Jobathon File Description: Utils + Constants Date: 27/02/2021 Author: vishwanath.prudhivi@gmail.com """ #import required libraries import pandas as pd import numpy as np import logging import xgboost as xgb from catboost import CatBoostClassifier, Pool...
############################################################################################################# ################################################## IMPORTS ################################################## ####################################################################################################...
import copy import time import numpy as np from ray.rllib.agents.pg import PGTrainer, PGTorchPolicy from marltoolbox.envs.matrix_sequential_social_dilemma import IteratedPrisonersDilemma from marltoolbox.examples.rllib_api.pg_ipd import get_rllib_config from marltoolbox.utils import log, miscellaneous from marltoolbo...
import os from abc import ABC, abstractmethod from pathlib import Path from configobj import ConfigObj from lmfit.models import LorentzianModel, QuadraticModel, LinearModel, ConstantModel, PolynomialModel from matplotlib import pyplot as plt from scipy.signal import savgol_filter try: from plot_python_vki import ...
""" Data preparation for Pendigits data. The result of this script is input for the workshop participants. This dataset has only numerical data (16 columns), with little meaning (originating from downsampling coordinates in time from digits written on a digital pad) Done here: - mapping of outliers: b'yes'/b'no' to 1...
import numpy as np import matplotlib.pyplot as plt import os, random import json import torch from torch import nn from torch import optim import torch.nn.functional as F import torchvision from torchvision import datasets, transforms, models from collections import OrderedDict from PIL import Image import time import ...
import abc import logging import pprint import random import typing from operator import itemgetter from numpy.random import RandomState import d3m.exceptions as exceptions from .template_hyperparams import Hyperparam _logger = logging.getLogger(__name__) DimensionName = typing.NewType('DimensionN...
# (C) William W. Cohen and Carnegie Mellon University, 2016 import theano import theano.tensor as T import theano.sparse as S import theano.sparse.basic as B from . import matrixdb import numpy def debugVar(v,depth=0,maxdepth=10): if depth>maxdepth: print('...') else: print('| '*(depth+1), end=' ') pr...
# Copyright 2017-2020 Lawrence Livermore National Security, LLC and other # Hatchet Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: MIT import glob import struct import re import os import traceback import numpy as np import pandas as pd import multiprocessing as mp import...
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2016 CNRS # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals # Monkey-patch because I trained with a newer version. # This can be removed once PyTorch 0.4.x is out. # See https://discuss.pytorch.org/t/question-about-rebuild-tensor-...