arxiv_id
stringlengths
0
16
text
stringlengths
10
1.65M
# -*- coding: utf-8 -*- import tensorflow as tf import pandas as pd import numpy as np import os import matplotlib.pyplot as plt # 训练集的路径 train_file = '/media/jxnu/Files/dog_vs_cat/train' def get_file(file_path): cats = [] label_cats = [] dogs = [] label_dogs = [] for file in os.listdir(file_pat...
from deepnote.modules import Metric, Note import numpy as np from scipy.stats import entropy import itertools from .repr import MusicRepr from .scale import Scale def pitch_histogram_entropy(seq : MusicRepr, window : int = 1, pitch_class: bool = False, return_probs=True): """ seq : input sequence window :...
# Copyright 2020 NXP Semiconductors # Copyright 2020 Marco Franchi # # This file was copied from NXP Semiconductors PyeIQ project respecting its # rights. All the modified parts below are according to NXP Semiconductors PyeIQ # project`s LICENSE terms. # # Reference: https://source.codeaurora.org/external/imxsupport/py...
""" Author: Peratham Wiriyathammabhum """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats eps = np.finfo(float).eps """ Importance sampling is a framework. It enables estimation of an r.v. X from a black box target distribution f using a known proposal distribution ...
# !/cs/usr/liorf/PycharmProjects/proj_scwgbs/venv/bin python # !/cs/usr/liorf/PycharmProjects/proj_scwgbs/venv/bin python import argparse import collections import copy import glob import os import re import sys import numpy as np import pandas as pd from tqdm import tqdm sys.path.append(os.path.dirname(os.getcwd())...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn plt.style.use('ggplot') import arch from arch.unitroot import ADF from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.seasonal import seasonal_decompose import os import datetime as dt # # dff_df_R001...
## Leetcode problem 210: Course schedule II. #https://leetcode.com/problems/course-schedule-ii/ #based on topological sorting. import numpy as np import algorith.clr_book.ch22_elemtary_graph.graph as gr from typing import List class Solution(): def findOrder(self, numCourses: int, prerequisites: List[List[int]])...
# written by LazyGuyWithRSI import pyautogui import ctypes import time from PIL import ImageGrab import numpy as np import cv2 as cv import win32api import keyboard from configparser import ConfigParser # TODO HOTKEY not implemented yet # change HOTKEY to whatever key you want (ex. 'a', 'f2') even modifiers (ex. 'ctr...
import multiprocessing import re from pyomyo import Myo, emg_mode import numpy as np import matplotlib.pyplot as plt from matplotlib import animation import bone import serial_utils as s # Use device manager to find the Arduino's serial port. COM_PORT = "COM9" RESET_SCALE = True LEGACY_DECODE = False # If false, will...
#!/usr/bin/env python # coding: utf-8 # In[1]: import sys sys.path.insert(0, '../py') from graviti import * from numpy.linalg import norm import numpy as np import os import os.path from os import path import sys import glob import h5py import seaborn as sns import matplotlib.pyplot as plt import matplotlib #matp...
#!/usr/bin/python # -*- coding: latin-1 -*- """ Rays are stand-ins for lightrays heading from the camera through the scene. .. moduleauthor:: Adrian Köring """ import numpy as np from padvinder.util import normalize from padvinder.util import check_finite class Ray(object): """ A ray consists of a starting ...
#import matplotlib #matplotlib.use('Agg') from matplotlib.animation import FuncAnimation, writers import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import cv2 import numpy as np skeleton_parents = [0,1,2,0,4,5,0,7,8,9,8,11,12,8,14,15] #h36m #skeleton_parents = [0,0,1,2,0,0,5,6,7,8,0,0,11,12,1...
""" Reward normalization schemes. """ from math import sqrt import numpy as np class RewardNormalizer: """ Normalize rewards in rollouts with a gradually updating divisor. """ def __init__(self, update_rate=0.05, discount=0.0, scale=1.0, epsilon=1e-5): """ Create a reward normal...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # 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 appl...
# Copyright 2019 DIVERSIS Software. 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 law o...
import xspec import numpy as n import sys nh_vals = 10**n.arange(-2,4,0.05) z_vals = 10**n.arange(-3,0.68,0.025) nh_val = 1000.# nh_vals[0] redshift = 2. # z_vals[0] def get_fraction_obs(nh_val, redshift, kev_min_erosita = 0.5, kev_max_erosita = 2.0): print(nh_val, redshift) kev_min_erosita_RF = kev_min_erosi...
#Write by Chiru Ge, contact: gechiru@126.com # -*- coding: utf-8 -*- ## use GPU import os import tensorflow as tf os.environ['CUDA_VISIBLE_DEVICES']='0' config=tf.ConfigProto() config.gpu_options.allow_growth= True sess=tf.Session(config=config) import numpy as np import matplotlib.pyplot as plt import scipy.io as si...
import re import os import time import itertools as it import numpy as np # logger def logger(verbose = False): def log(*arg): if verbose: print(*arg) return log # time utils def tic(): return time.time() def toc(start, msg=None): end = time.time() print("Done en {}s".format((...
#!/usr/bin/env python import argparse import shutil import keras from keras.models import Sequential import numpy as np np.random.seed(1234) import cPickle as pickle import h5py from keras.layers import Conv1D, MaxPool1D,Dense, Activation, Dropout, GaussianDropout, ActivityRegularization, Flatten from keras.optimizers...
import os import gzip import urllib.request import numpy as np import time import zipfile import io from scipy.io.wavfile import read as wav_read from tqdm import tqdm class warblr: """Binary audio classification, presence or absence of a bird. `Warblr <http://machine-listening.eecs.qmul.ac.uk/bird-audio-det...
from typing import Any, Dict, Tuple, Union import gym import numpy as np import torch import torch.optim as opt from torch.autograd import Variable from ....environments import VecEnv from ...common import RolloutBuffer, get_env_properties, get_model, safe_mean from ..base import OnPolicyAgent class VPG(OnPolicyAge...
# BSD 3-Clause License. # # Copyright (c) 2019-2021 Robert A. Milton. All rights reserved. # # 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 notic...
import pandas as pd from matplotlib import pyplot as plt import numpy as np from sklearn.preprocessing import MinMaxScaler import random MAXLIFE = 120 SCALE = 1 RESCALE = 1 true_rul = [] test_engine_id = 0 training_engine_id = 0 def kink_RUL(cycle_list, max_cycle): ''' Piecewise linear functi...
from typing import Tuple, List, Any, Optional from .connection import Connection from .drone_connection import DroneConnection from .window_manager import LocationWindowManager, TimeWindowManager from .waypoint_manager import WaypointManager from .event_manager import EventManager from common.protocol import Protocol f...
import itertools from tempfile import NamedTemporaryFile import matplotlib import matplotlib.pyplot as plt import numpy as np from bokeh.plotting import figure, output_file def get_validation_plot(true_value, prediction): output_file(NamedTemporaryFile().name) x_min = min(min(true_value), min(prediction)) ...
# Copyright 2020 Virginia Polytechnic Institute and State University. """ OpenFOAM I/O. These functions are accesible from ``dafi.random_field.foam``. """ # standard library imports import numpy as np import os import shutil import re import tempfile import subprocess # global variables NDIM = {'scalar': 1, ...
"""Collection of region proposal related utils The codes were largely taken from the original py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn), and translated into TensorFlow. Especially, each part was from the following: 1. _whctrs, _mkanchors, _ratio_enum, _scale_enum, get_anchors - ${py-faster-rcnn}/...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf import umap from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from tensorflow.keras.layers import Dense, Input from tensorflow.keras.models import Model, load_model from sklearn impor...
import numpy as np import condition import output import solver if __name__ == '__main__': md = 202 nd = 202 u = np.zeros((md, nd)) v = np.zeros((md, nd)) p = np.zeros((md, nd)) u_old = np.zeros((md, nd)) v_old = np.zeros((md, nd)) xp = np.zeros(md) yp = np.zeros(nd) # setu...
# -*- coding: utf-8 -*- """Discrete wavelet transform.""" import math import numpy as np import pandas as pd from sktime.datatypes import convert from sktime.transformations.base import BaseTransformer __author__ = "Vincent Nicholson" class DWTTransformer(BaseTransformer): """Discrete Wavelet Transform Transfo...
# This function is copied from https://github.com/Rubikplayer/flame-fitting ''' Copyright 2015 Matthew Loper, Naureen Mahmood and the Max Planck Gesellschaft. All rights reserved. This software is provided for research purposes only. By using this software you agree to the terms of the SMPL Model license here ht...
# -*- coding: utf-8 -*- """ @author: A. Popova """ import numpy as np #old_settings = np.seterr(all='ignore') def fact(x): res = 1 for i in range(int(x)): res *= (i+1.) return res data_ = np.genfromtxt(r'in_out/Submatrix.dat') m = len(data_) Nu = int(10*m) dnu = 2*np.pi/Nu M = np.zeros((m...
# -*- coding: utf-8 -*- """ Interfaz gráfica para el movimiento armónico de un edificio, de forma similar a un terremoto. @author: Anthony Gutiérrez """ import numpy as np import tkinter as tk from matplotlib.animation import FuncAnimation from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib...
import os import numpy as np import torch from tqdm import tqdm from zs3.dataloaders import make_data_loader from zs3.modeling.deeplab import DeepLab from zs3.modeling.sync_batchnorm.replicate import patch_replication_callback from zs3.dataloaders.datasets import DATASETS_DIRS from zs3.utils.calculate_weigh...
#%% Imports import pandas as pd import numpy as np #import neuprint as npr from neuprint import Client, fetch_traced_adjacencies, fetch_adjacencies from neuprint import fetch_synapse_connections from neuprint import fetch_synapse_connections, NeuronCriteria as NC, SynapseCriteria as SC from neuprint.utils import conne...
import gym import numpy as np import pytest from push_ups import spaces @pytest.fixture def env(): return gym.make("CartPole-v1") def test_equal_spaces(env): space_1 = spaces.BoxSpace(env.observation_space) space_2 = spaces.DiscreteSpace(env.action_space) assert space_1 == space_1 assert space...
import os import numpy as np import pandas as pd import xarray as xr import datetime import time import cftime import warnings import requests import shutil def set_bnds_as_coords(ds): new_coords_vars = [var for var in ds.data_vars if 'bnds' in var or 'bounds' in var] ds = ds.set_coords(new_coords_vars) re...
import torch import numpy as np import logging import os import torch.nn.functional as F ## Get the same logger from main" logger = logging.getLogger("anti-spoofing") def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (_, X1, X2, target) in enumerate(train_loader): ...
import numpy as np import math import pandas as pd from random import shuffle from matplotlib import pyplot as plt import matplotlib.pyplot as plt import matplotlib.pyplot as pause from mpl_toolkits.mplot3d import Axes3D from time import sleep import matplotlib.animation as animation import sys # DEFAULT P...
import numpy as np # import _proj as proj_lib import scipy.sparse as sparse import scipy.sparse.linalg as splinalg ZERO = "f" POS = "l" SOC = "q" PSD = "s" EXP = "ep" EXP_DUAL = "ed" POWER = "p" # The ordering of CONES matches SCS. CONES = [ZERO, POS, SOC, PSD, EXP, EXP_DUAL, POWER] def parse_cone_dict(cone_dict): ...
'''Trains a simple convnet on the MNIST dataset. based on a keras example by fchollet Find a way to improve the test accuracy to almost 99%! FYI, the number of layers and what they do is fine. But their parameters and other hyperparameters could use some work. ''' import numpy as np np.random.seed(1337) # for reprodu...
class A: def __init__(self): pass def f1(self, a): b = 1 c = 2 result = a**b + a**c return result def f2(self, a): b = 1 c = 2 result = a**b + a**c return result def f3(self, a): b = 1 c = 2 ...
import torch from torch.utils.data import Dataset import numpy as np from .grid_generator import SampleSpec DEFAULT_PAIRS = 4 DEFAULT_CLASSES = 4 sample_spec = SampleSpec(num_pairs=DEFAULT_PAIRS, num_classes=DEFAULT_CLASSES, im_dim=76, min_cell=15, max_cell=18) def set_sample_spec(num_pairs, num_classes, reset_every...
#!/usr/bin/env python3 import sys import mpmath as mp import psr_common mp.dps=250 mp.mp.dps = 250 if len(sys.argv) != 2: print("Usage: generate_constants.py outbase") quit(1) outbase = sys.argv[1] constants = {} # All constants to generate # variable base value ...
""" Configuration file for pytest, containing global ("session-level") fixtures. """ import pytest from astropy.utils.data import download_file import vip_hci as vip @pytest.fixture(scope="session") def example_dataset(): """ Download example FITS cube from github + prepare HCIDataset object. Returns...
""" Copyright (c) 2017 - Philip Paquette 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, merge, publish, distribu...
import random from typing import Callable, Dict, List import albumentations as alb import numpy as np import torch from torch.utils.data import Dataset from virtex.data.tokenizers import SentencePieceBPETokenizer from virtex.data import transforms as T from .arch_captions import ArchCaptionsDatasetRaw class ArchCap...
# -*- coding: utf-8 -*- """Ramdom_Search_Classes.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1bJw4Q1F3TYv8okhNqNTtw5CdCFH7-vrh """ import numpy as np import tensorflow as tf import keras from keras import models from keras import layers from...
import unittest import numpy as np from photonai_graph.GraphConstruction.graph_constructor_threshold import GraphConstructorThreshold class ThresholdTests(unittest.TestCase): def setUp(self): self.X4d_adjacency = np.ones((20, 20, 20, 1)) self.X4d_features = np.random.rand(20, 20, 20, 1) s...
#!/usr/bin/python3 import argparse import os import time from functools import partial import numpy as np import oneflow as flow from oneflow import nn from modeling import BertForPreTraining from utils.ofrecord_data_utils import OfRecordDataLoader def save_model(module: nn.Module, checkpoint_path: str, epoch: int,...
""" Calculates zonal-mean eddy rms of meridional wind on a given model level for aquaplanet model data """ import numpy as np import xarray as xr from ds21grl.misc import get_dim_exp,get_eddy,daysinmonths,get_season_daily from ds21grl.read_aqua import read_xt_ml_daily from ds21grl...
from sympy import Mul, Add, Rational, Float, Integer, Pow, Function from .util import ScalarSymbol, FunctionSymbol import keras import tensorflow as tf import numpy as np class MetaLayer(object): def __init__(self,type_key=None, name=None,input_key=None,output_key=None,options=None): self.type_key = type_...
from colorsys import rgb_to_hls from PIL import Image import matplotlib.pyplot as plt import numpy as np from math import sqrt import json #TODO: rename file #TODO: look at turning this into a module instead of a class #TODO: figure out gamma correction to get relative luminance for colormap y-axis #TODO: [POTENTIALL...
import h5py import numpy as np import pandas as pd import transforms3d import random import math def augment_cloud(Ps, args, return_augmentation_params=False): """" Augmentation on XYZ and jittering of everything """ # Ps is a list of point clouds M = transforms3d.zooms.zfdir2mat(1) # M is 3*3 identity ma...
import gym import numpy as np import random from collections import deque from tensorflow.keras import models, layers, optimizers import matplotlib.pyplot as plt class DQN: def __init__(self, env): self.env = env # replay buffer self.buffer = deque(maxlen=10000) self.discount = 1 ...
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import pandas as pd import numpy as np from colormap import rgb2hex class Ibcs(): def ibcs_grid(self,fig ,major_ticks1 ,major_ticks2 ,perc_ticks ,m_gr ,t_gr ,l_gr ...
__all__ = [ 'TableToTimeGrid', 'ReverseImageDataAxii', 'TranslateGridOrigin', ] __displayname__ = 'Transform' import numpy as np import vtk from vtk.numpy_interface import dataset_adapter as dsa from .. import _helpers, interface from ..base import FilterBase ############################################...
from . import datafetcher import matplotlib.pyplot as plt from datetime import datetime, timedelta from floodsystem.stationdata import build_station_list from floodsystem.station import MonitoringStation import numpy as np from floodsystem.analysis import polyfit import matplotlib def plot_water_levels(station, dates,...
#Exercícios Numpy-03 #******************* import numpy as np arr=np.zeros(10) print('arr=',arr)
import requests from bs4 import BeautifulSoup from calendar import monthrange from datetime import datetime import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler from utils import getLogger from ArticleParser import ArticleParser logger = getLogger("ScrapeDaily") class ScrapeDaily: ...
# Copyright 2021 Lawrence Livermore National Security, LLC """ This script is used by cmec-driver to run the ASoP-Coherence metrics. It is based on the workflow in asop_coherence_example.py and can be called with the aruments listed below. If no configuration file with module settings is provided, the settings will be ...
# Copyright (C) 2019 Klaus Spanderen # # This file is part of QuantLib, a free-software/open-source library # for financial quantitative analysts and developers - http://quantlib.org/ # # QuantLib is free software: you can redistribute it and/or modify it under the # terms of the QuantLib license. You should have rece...
# -*- coding: utf-8 -*- """ Created on Fri Aug 25 15:31:20 2017 @author: Sadhna Kathuria """ ## calculate pi using monte carlo simulation import numpy as np import matplotlib.pyplot as plt nums = 1000 iter = 100 #def pi_run(nums,iter): pi_avg =0 pi_val_list =[] for i in range(iter): value = 0 x=np.ran...
from flask import Flask,render_template,request,redirect,url_for import easygui import sqlite3 as sql import csv import random import math import numpy as np from pysqlcipher import dbapi2 as sqlcipher from sklearn import tree app=Flask(__name__) @app.route("/") def index(): #if request.method== 'POST': return ren...
import numpy as np import matplotlib.pyplot as plt N=10000 normal_values = np.random.normal(size=N) ''' normal_values = np.random.beta(9,0.5, size=N) ''' dummy, bins, dummy = plt.hist(normal_values, np.sqrt(N), normed=True, lw=1) sigma = 1 mu = 0 plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**...
__author__ = 'sibirrer' from lenstronomy.LensModel.Profiles.cored_density import CoredDensity import numpy as np import numpy.testing as npt import pytest class TestCoredDensity(object): """ tests the Gaussian methods """ def setup(self): self.model = CoredDensity() def test_function(se...
import datetime as dt import numpy as np import pandas as pd import sqlite3 from epl.query import create_and_query, create_conn def result_calculator(match_results, res_type): """ Function to output the league table for a set of matches including MP, GF, GA and points match_results: dataframe of match re...
#!/usr/bin/env python # native Python imports import os.path import sys import numpy as np # third-party imports import cyvcf as vcf # geminicassandra modules import version from ped import load_ped_file import gene_table import infotag from database_cassandra import insert, batch_insert, create_tables import annota...
import unittest import numpy as np from pyfiberamp.fibers import YbDopedDoubleCladFiber from pyfiberamp.steady_state import SteadyStateSimulation class YbDoubleCladWithGuessTestCase(unittest.TestCase): @classmethod def setUpClass(cls): Yb_number_density = 3e25 core_r = 5e-6 backgroun...
#!/usr/bin/python # -*- coding: utf-8 -*- import threading import curses import FontManager import numpy as np import PacketFormat as PF WIN_WIDTH = 256 WIN_HEIGHT = 32 POLLING_SEC = 0.050 SCROLL_SEC = POLLING_SEC * 1.5 class ScreenThread(threading.Thread): def __init__(self, dev_so): """ ・ホストと通信...
# Copyright 2017 Rice UniversityDAPIInvoke.split_api_call(value2add) # # 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 a...
import neural_network_lyapunov.examples.quadrotor2d.quadrotor_2d as\ quadrotor_2d import neural_network_lyapunov.relu_system as relu_system import neural_network_lyapunov.lyapunov as lyapunov import neural_network_lyapunov.feedback_system as feedback_system import neural_network_lyapunov.train_lyapunov as train_lya...
#!/usr/bin/env python -u # Validation script for GASKAP HI data # # Author James Dempsey # Date 23 Nov 2019 from __future__ import print_function, division import argparse import csv import datetime import glob import math import os import re from string import Template import shutil import time import warnings i...
# /usr/bin/env python3 import numpy as np import pandas as pd def operaciones(): #debido a quee pandas necesita de Numpys este puede usar los uFuncs de Numpy #np.sin,cos,tans,arctan.arcsin,exp ser= pd.Series(np.random.randint(1,90,size=8)) df= pd.DataFrame(np.random.randint(1,90,size=(4,5)),index=['a...
import copy import os import numpy as np import pandas as pd from scipy import optimize # code models from src.toric_model import Toric_code from src.planar_model import Planar_code from src.xzzx_model import xzzx_code from src.rotated_surface_model import RotSurCode # decoders from decoders import MCMC, single_temp,...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tests for the core module. """ import numpy as np from numpy.testing import assert_allclose import pytest from ..core import Segment, SegmentationImage try: import matplotlib # noqa HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTL...
from time import perf_counter import warnings import torch import torch.nn.functional as F import numpy as np from mmdet.datasets.builder import PIPELINES from mmdet.datasets.pipelines.compose import Compose @PIPELINES.register_module() class Timer(Compose): """Times a list of transforms and stores result in img...
from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor import os, cv2, json import numpy as np from progress.bar import Bar from PIL import Image, ImageDraw from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog i...
import cv2 import face_recognition import numpy as np import pickle _KNOWN_FACE_ENCODINGS_FILE = 'known-face-encodings.pkl' _KNOWN_FACE_IDS_FILE = 'known-face-ids.pkl' # the two lists are parallel. meaning, # face_encoding at index 0 of 'known_face_encodings' belongs to the face_id at index 0 of 'known_face_ids' # k...
""" Core MagGeo_Sequential Model Created on Thur Feb 17, 22 @author: Fernando Benitez-Paez """ import datetime as dt from datetime import timedelta import sys,os from matplotlib.pyplot import pause import pandas as pd import numpy as np from tqdm import tqdm import click from yaml import load, SafeLoader from virescl...
import numpy as np import json import scipy.interpolate import matplotlib.pyplot as plt from collections import OrderedDict from pprint import pprint import matplotlib import argparse ################################################################################################################## ## This script allow...
from multiprocessing import Pool from numpy import array from ..array_array import apply, separate_and_apply def apply_with_vector(ve, ma, fu, se=False, n_jo=1): if se: ap = separate_and_apply else: ap = apply po = Pool(processes=n_jo) re_ = array(po.starmap(ap, ([ve, ro, fu] f...
import scipy from scipy.misc import imsave import os import cv2 import numpy as tf # Removes items that appear in a listmore than once def remove_duplicates(image_list): return list(set(image_list)) # Gets a list of all images (including if it's used multiple times) def find_images(list_of_folders): length ...
# Basic libs import os, time, glob, random, pickle, copy, torch import open3d as o3d import numpy as np import open3d from scipy.spatial.transform import Rotation from torchvision.transforms import transforms # Dataset parent class from torch.utils.data import Dataset from collections import namedtuple from common.cam...
import numpy as onp import legate.numpy as np import timeit import deriche_numpy as np_impl def kernel(alpha, imgIn): k = (1.0 - np.exp(-alpha)) * (1.0 - np.exp(-alpha)) / ( 1.0 + alpha * np.exp(-alpha) - np.exp(2.0 * alpha)) a1 = a5 = k a2 = a6 = k * np.exp(-alpha) * (alpha - 1.0) a3 = a7 =...
import pymysql import datetime from pandas import DataFrame import numpy as np from dbutils.steady_db import connect class RankDB(): """ a mariadb wrapper for the following tables: - stock_data - corporate_data - corporate_financials - model_event_queue - top_performers...
""" # Test uzf for the vs2d comparison problem in the uzf documentation except in # this case there are 15 gwf and uzf cells, rather than just one cell. """ import os import numpy as np try: import pymake except: msg = "Error. Pymake package is not available.\n" msg += "Try installing using the following...
from tqdm import tqdm import numpy as np from polaris2.micro.micro import det from polaris2.geomvis import R3S2toR, utilmpl, phantoms import logging log = logging.getLogger('log') N = 80 log.info('Making '+str(N)+' frames') for i in tqdm(range(N)): xp, yp, zp = phantoms.sphere_spiral(i/(N-1)) obj = R3S2toR.xyz...
import numpy as np from scipy.optimize import linear_sum_assignment as linear_assignment # from sklearn.metrics import normalized_mutual_info_score, adjusted_rand_score # nmi = normalized_mutual_info_score # ari = adjusted_rand_score def acc(y_true, y_pred): """ Calculate clustering accuracy. Require scikit-...
import matplotlib.pyplot as plt import numpy as np from fast_image_classification.preprocessing_utilities import read_img_from_path from fast_image_classification.training_utilities import get_seq def plot_figures(names, figures, nrows=1, ncols=1): """Plot a dictionary of figures. Parameters ---------- ...
# License: MIT from typing import List import numpy as np from openbox.utils.config_space import Configuration, ConfigurationSpace WAITING = 'waiting' RUNNING = 'running' COMPLETED = 'completed' PROMOTED = 'promoted' def sample_configuration(configuration_space: ConfigurationSpace, excluded_configs: List[Configurat...
import sys if sys.version_info < (3, 6): sys.stdout.write( "Minkowski Engine requires Python 3.6 or higher. Please use anaconda https://www.anaconda.com/distribution/ for isolated python environment.\n" ) sys.exit(1) try: import torch except ImportError: raise ImportError('Pytorch not found...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from typing import Dict, Optional, Union import numpy import torch import torch.nn.functional as F from allennlp.common import Params from allennlp.common.checks import ConfigurationError from allennlp.data import Vocabulary from allennlp.models.model import Model from al...
# Copyright (c) FULIUCANSHENG. # Licensed under the MIT License. import os import sys import json import argparse import logging import numpy as np import pandas as pd submission_files = { "cola": "CoLA.tsv", "sst2": "SST-2.tsv", "mrpc": "MRPC.tsv", "stsb": "STS-B.tsv", "mnli": "MNLI-m.tsv", "...
# import fitz import pytesseract from PIL import Image import io import cv2 import numpy as np from pdf2image import convert_from_bytes import re from core import logging logger = logging.getLogger(__name__) def de_skew(image, show=False, delta=0): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = 255 - g...
import numpy as np import cv2 from matplotlib import pyplot as plt """ @X: input data @k: number of clusters """ def kmeans_wrapper(X, k, image_as_input = False): if not image_as_input: X = np.float32(X) else: orig_shape = X.shape # flatten the image into a vector of BGR entries ...
import numpy as np import os import re import cPickle class read_cifar10(object): def __init__(self, data_path=None, is_training=True): self.data_path = data_path self.is_training = is_training def load_data(self): files = os.listdir(self.data_path) if self.is_training is True: pattern = ...
import copy import math import pdb import random import timeit import cPickle as pickle import numpy as np from poim import * import poim from shogun.Features import * from shogun.Kernel import * from shogun.Classifier import * from shogun.Evaluation import * from shutil import * dna = ['A', 'C', 'G', 'T'] def simula...
"""Starting from a halo mass at z=0, the two functions below give descriptions for how halo mass and Vmax smoothly evolve across time. """ from numba import njit from math import log10, exp __all__ = ('halo_mass_vs_redshift', 'vmax_vs_mhalo_and_redshift') @njit def halo_mass_vs_redshift(halo_mass_at_z0, redshift, h...
# -*- coding: utf-8 -*- """ Created on Wed Mar 16 15:03:37 2016 keshengxuu@gmail.com @author: keshengxu """ import numpy as np from scipy.stats import norm from scipy import integrate import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import os.path from matplotlib import colors import matplotlib.g...