arxiv_id stringlengths 0 16 | text stringlengths 10 1.65M |
|---|---|
# -*- coding: utf-8 -*-
"""
Name: Anomaly Detection for Anonymous Dataset
Author: Pablo Reynoso
Date: 2022-03-22
Version: 1.0
"""
"""## 0) Libraries/Frameworks"""
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.metri... | |
import pylab as pl
import numpy as np
def tickline():
pl.xlim(0, 10), pl.ylim(-1, 1), pl.yticks([])
ax = pl.gca()
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_positi... | |
import torch
import torch.nn as nn
import pandas as pd
import yaml
import logging
import sys
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
from discriminator import Discriminator_Agnostic, Discriminator_Awareness, Generator
from dfencoder.autoencoder import AutoEncoder
from sklearn impor... | |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
from sklearn.preprocessing import LabelEncoder
from keras.utils.np_utils import to_categorical
# In[2]:
from train_valid_split import train_valid_split... | |
import json
import gc
from keras.models import Model
from keras.layers import Input, Concatenate, Average
from keras import backend as K
from keras.optimizers import Adam
from keras.utils import generic_utils
import numpy as np
from layers import GradientPenalty, RandomWeightedAverage
import utils
class WGANGP(obje... | |
import paddle.v2 as paddle
import numpy as np
# init paddle
paddle.init(use_gpu=False)
# network config
x = paddle.layer.data(name='x', type=paddle.data_type.dense_vector(2))
y_predict = paddle.layer.fc(input=x, size=1, act=paddle.activation.Linear())
y = paddle.layer.data(name='y', type=paddle.data_type.dense_vector... | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Szymon Biliński
#
# 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
#
# Un... | |
from growcut import growcut_python
from numba import autojit
benchmarks = (
("growcut_numba",
autojit(growcut_python.growcut_python)),
) | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import numpy as np
from tvm import te
import logging
import sys, time, subprocess
import json
import os
def schedule(attrs):
cfg, s, output = attrs.auto_config, attrs.scheduler, attrs.outputs[0]
th_vals, rd_vals = [attrs.get_extent(x) f... | |
"""
Render the models from 24 elevation angles, as in thesis NMR
Save as an image.
9. 17. 2020
created by Zheng Wen
9. 19. 2020
ALL RENDER ARE FINISHED WITHOUT TEXTURE
Run from anaconda console
NOTE:
RENDER FROM ORIGINAL SHOULD BE RANGE(360, 0, -15)
HERE RANGE(0, 360, 15)
SOLUTION: RENAME FILES OR GENE... | |
"""
helpers
=======
Collection of internal helper functions and classes, used by different
modules.
"""
import numpy as np
__all__ = ['check_vecsize', 'maxreldiff', 'Struct']
def check_vecsize(v,n=None):
"""
Check whether 'v' is a 1D numpy array. If 'n' is given, also check
whether its length is equal ... | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmdet.core import delta2bbox
from mmdet.ops import nms
from ..registry import HEADS
from .anchor_head import AnchorHead
from mmdet.core.bbox.geometry import bbox_overlaps
import numpy as np
@HEADS.register_module
... | |
#!/usr/bin/env python
"""
Extract custom features
-----------------------
This example shows how to extract features from the tissue image using a custom function.
The custom feature calculation function can be any python function that takes an image as input, and
returns a list of features.
Here, we show a simple ex... | |
from numpy import log10
from conversions import *
#====================================================================
# FUSELAGE GROUP
#
# airframe, pressurization, crashworthiness
#
# ALL UNITS IN IMPERIAL
#====================================================================
f_lgloc = 1.0#1.16 # 1.1627 lan... | |
# 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 applicable law or agreed to... | |
from __future__ import absolute_import
import os, re, collections
import requests, nltk
import numpy as np
import pandas as pd
import tensorflow as tf
import xml.etree.ElementTree as ET
from TF2.extract_features_Builtin import *
type = 'bert'
if type == 'bert':
bert_folder = 'Pretrained/uncased_L-12_H-768_A-12/... | |
import numpy as np
import torch
import torch.nn as nn
import layers
class GCN(nn.Module):
def __init__(self, input_dim, hidden_dims, output_dim,
dropout=0.5):
"""
Parameters
----------
input_dim : int
Dimension of input node features.
hidden_di... | |
'''Action decision module'''
from pdb import set_trace as T
import numpy as np
from collections import defaultdict
import torch
from torch import nn
from forge.blade.io.stimulus.static import Stimulus
from forge.ethyr.torch.policy import attention
from forge.ethyr.torch.policy import functional
from pcgrl.game.io.... | |
import os
import unittest
import numpy as np
from gnes.encoder.audio.vggish import VggishEncoder
class TestVggishEncoder(unittest.TestCase):
@unittest.skip
def setUp(self):
self.dirname = os.path.dirname(__file__)
self.video_path = os.path.join(self.dirname, 'videos')
self.video_bytes... | |
from flask import Flask,jsonify,request
import pandas as pd
import numpy as np
import time
from sklearn.model_selection import train_test_split
import sys
import turicreate as tc
sys.path.append("..")
import json
from flask_cors import CORS
from flask import request
import datetime
import json as json
from pymongo impo... | |
#! /usr/bin/env python
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import Count
from django.db.models import Q
from face_manager.models import Person, Face
from filepopulator.models import ImageFile
from itertools import chain
from PIL import Image
from ... | |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
SMALL_SIZE = 14
MEDIUM_SIZE = 18
LARGE_SIZE = 22
HEAD_WIDTH = 1
HEAD_LEN = 1
FAMILY = "Times New Roman"
plt.rc("font", size=SMALL_SIZE, family=FAMILY)
plt.rc("axes", titlesize=MEDIUM_SIZE, labelsize=MEDIUM_SIZE, linewidth=2.0)... | |
# Copyright 2014-2020 The PySCF Developers. 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 appl... | |
from __future__ import annotations
__all__ = ['Mosaic', 'Tile', 'get_fusion']
import dataclasses
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass, field
from functools import partial
from itertools import chain
from typing import NamedTuple... | |
"""Common functions to marshal data to/from PyTorch
"""
import collections
from typing import Optional, Sequence, Union, Dict
import numpy as np
import torch
from torch import nn
__all__ = [
"rgb_image_from_tensor",
"tensor_from_mask_image",
"tensor_from_rgb_image",
"count_parameters",
"transfer_... | |
from functools import lru_cache
import numpy as np
from scipy.linalg import eigh_tridiagonal, eigvalsh_tridiagonal
from scipy.optimize import minimize
from waveforms.math.signal import complexPeaks
class Transmon():
def __init__(self, **kw):
self.Ec = 0.2
self.EJ = 20
self.d = 0
... | |
import time
import json
import logging
import random
import os
import pyautogui
import pyscreenshot as ImageGrab
import sys
import tkinter as tk
from tkinter import *
import numpy
from pynput.mouse import Listener as MouseListener
from pynput import mouse
from model.character import Character
# This class contains all... | |
# Author: Samuel Marchal samuel.marchal@aalto.fi Sebastian Szyller sebastian.szyller@aalto.fi Mika Juuti mika.juuti@aalto.fi
# Copyright 2019 Secure Systems Group, Aalto University, https://ssg.aalto.fi
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... | |
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
class Bandit:
def __init__(self , m , INIT_VAL):
self.m = m #true mean
self.mean = INIT_VAL
self.N = 0.0000000001
def pull(self):
return np.random.randn() + self.m
def push(self , x):
self.N += 1
self.mean = (1 - (1.0... | |
# -*- coding: utf-8 -*-
import os
import configparser
import argparse
import numpy as np
import signal
import shutil
import cv2
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import progressbar
import tensorflow as tf
from . import ae_factory as factory
from . import utils as u
def main():
workspace_path = os.environ... | |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2015, PyStan developers
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
#---------------------------------------------------------------------------... | |
#
# File:
# skewt2.py
#
# Synopsis:
# Draws skew-T visualizations using dummy data.
#
# Category:
# Skew-T
#
# Author:
# Author: Fred Clare (based on an NCL example of Dennis Shea)
#
# Date of original publication:
# March, 2005
#
# Description:
# This example draws two skew-T plots using real... | |
#!/usr/bin/python3
import gzip
import os
import sys
import re
import numpy as np
import prediction_v4_module as pr
import pandas as pd
from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
from sklearn import linear_model
from sklearn import tree
def read_features(f_handle, label):
... | |
import os
import numpy as np
import pandas as pd
from surili_core.workspace import Workspace
class Dataframes:
@staticmethod
def from_directory_structure(x_key: str = 'x', y_key: str = 'y'):
def apply(path: str):
data = Workspace.from_path(path) \
.folders \
... | |
from scipy.signal import get_window
def fourier_smooth(yi, d, fmax, shape='boxcar'):
"""y = fourier_smooth(yi, d, fmax, shape='boxcar').
Smoothing function that low-pass filters a signal
yi with sampling time d. Spectral components with
frequencies above a cut-off fmax are blocked, while
lower freq... | |
import json
import plotly
import random as rn
import numpy as np
import pandas as pd
import string
import pickle
import collections
from collections import Counter
import nltk
nltk.download(['punkt', 'wordnet', 'stopwords'])
import re
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from... | |
import os
import numpy as np
import argparse
import pickle
from nms import nms
def class_agnostic_nms(boxes, scores, iou=0.7):
if len(boxes) > 1:
boxes, scores = nms(np.array(boxes), np.array(scores), iou)
return list(boxes), list(scores)
else:
return boxes, scores
def parse_det_pkl(... | |
# coding=utf-8
import os, sys
import shutil
import sys
import time
import shutil
import re
import cv2
import numpy as np
import tensorflow as tf
import codecs
from collections import Counter
import matplotlib.pyplot as plt
import glob
from PIL import Image
from cnocr import CnOcr
from fuzzywuzzy import fuzz
sys.pa... | |
'''
Video game description language -- plotting functions.
@author: Tom Schaul
'''
import pylab
from scipy import ones
from pylab import cm
from random import random
def featurePlot(size, states, fMap, plotdirections=False):
""" Visualize a feature that maps each state in a maze to a continuous value.
... | |
import numpy as np
import tensorflow as tf
from collections import OrderedDict
from copy import deepcopy
import logging
import traceback
import sys
from ma_policy.variable_schema import VariableSchema, BATCH, TIMESTEPS
from ma_policy.util import shape_list
from ma_policy.layers import (entity_avg_pooling_masked, entity... | |
import nnet
from MVNormal import MVNormal
import theano_helpers
import svn
import random
from DropoutMask import * | |
import numpy as np
import seaborn as sns
palette = sns.color_palette('colorblind')
metric_en_name = {
'Błąd aproksymacji (AE) prawdopodobieństwa a posteriori': 'Approximation error for posterior',
r'Błąd estymacji częstości etykietowania': 'Label frequency estimation error',
r'Błąd estymacji prawdopodobie... | |
"""Generative Adversarial Networks."""
from deepchem.models import TensorGraph
from deepchem.models.tensorgraph import layers
from collections import Sequence
import numpy as np
import tensorflow as tf
import time
class GAN(TensorGraph):
"""Implements Generative Adversarial Networks.
A Generative Adversarial Ne... | |
from operator import index
import os
import subprocess
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
import pandas as pd
import numpy as np
import pysam
from scipy.io import mmwrite
from scipy.sparse import coo_matrix
import celescope.tools.utils as utils
from celescope.__init... | |
import numpy as np
import paddle.fluid as fluid
from paddle.fluid.dygraph import to_variable
from paddle.fluid.dygraph import Layer
from paddle.fluid.dygraph import Conv2D
from paddle.fluid.dygraph import BatchNorm
from paddle.fluid.dygraph import Dropout
from resnet_dilated import ResNet50
# pool with different bin_s... | |
import sys, os
import subprocess
import numpy as np
import pandas as pd
from Bio.PDB import *
from Bio import SeqIO
from Bio import AlignIO
from Bio import Align
import itertools as it
def filterandparse_sequences(fastaOUT, theta):
"""
filter for gaps and N characters
"""
data = pd.read_csv("../../... | |
"""
Data from https://www.isi.edu/~lerman/downloads/digg2009.html
Extract network and diffusion cascades from Digg
"""
import os
import pandas as pd
import networkx as nx
import numpy as np
from urllib.request import urlopen
from zipfile import ZipFile
def extract_network(file):
friends = pd.read_csv(file,heade... | |
import numpy as np
import brainscore
from brainio.assemblies import DataAssembly
from brainscore.benchmarks._properties_common import PropertiesBenchmark, _assert_texture_activations
from brainscore.benchmarks._properties_common import calc_texture_modulation, calc_sparseness, calc_variance_ratio
from brainscore.metri... | |
import matplotlib.pyplot as plt
import numpy as np
from . import implantation_range, reflection_coeff
from . import estimate_inventory_with_gp_regression
DEFAULT_TIME = 1e7
database_inv_sig = {}
def fetch_inventory_and_error(time):
"""Fetch the inventory and error for a given time
Args:
time (floa... | |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# Install it using pip install hmmlearn
from hmmlearn import hmm
# Set random seed for reproducibility
np.random.seed(1000)
if __name__ == '__main__':
# Create a Multinomial HMM
hmm_model = hmm.MultinomialHMM(n_components=... | |
#-*- coding:utf-8 -*-
#'''
# Created on 2020/9/10 10:32
#
# @Author: Jun Wang
#'''
import os
import time
from tqdm import tqdm
from collections import OrderedDict
import numpy as np
from numpy.random import choice
import pandas as pd
import matplotlib.pyplot as plt
import PIL
from torch.nn import ... | |
import numpy as np
from autograd import numpy as anp
from autograd import jacobian
from scipy.optimize import least_squares
from core.calib.kruppa.common import mul3
class KruppaSolver(object):
"""
Hartley's formulation
https://ieeexplore.ieee.org/document/574792
"""
def __init__(self, verbose=2):
... | |
"""
TODO
- set up datastream
- num_parallel_calls til map
- add cache?
- add oversampling https://github.com/tensorflow/tensorflow/issues/14451
- make wandb callback
- set up early stopping
"""
import os
from functools import partial
import numpy as np
import tensorflow as tf
from tensorflow.keras impor... | |
"""Test the vasprun.xml parser."""
# pylint: disable=unused-import,redefined-outer-name,unused-argument,unused-wildcard-import,wildcard-import
# pylint: disable=invalid-name
import pytest
import numpy as np
from aiida_vasp.utils.fixtures import *
from aiida_vasp.utils.aiida_utils import get_data_class
@pytest.mark.... | |
from ..base import GreeksFDM, Option as _Option
from ..vanillaoptions import GBSOption as _GBSOption
import numpy as _np
from scipy.optimize import root_scalar as _root_scalar
import sys as _sys
import warnings as _warnings
import numdifftools as _nd
from ..utils import docstring_from
class RollGeskeWhaleyOption(_Opt... | |
#!/usr/bin/env python3
import argparse
from pathlib import Path
import numpy as np
from matplotlib import pyplot as plt
from tqdm import tqdm
import dns
def main():
parser = argparse.ArgumentParser("Computes direction-dependent dropoffs.")
parser.add_argument(
"statePath",
type=str,
... | |
import matplotlib
matplotlib.use('TkAgg')
import pymc3 as pm
import pandas as pd
import matplotlib
import numpy as np
import pickle as pkl
import datetime
from BaseModel import BaseModel
import isoweek
from matplotlib import rc
from shared_utils import *
from pymc3.stats import quantiles
from matplotlib import pyplot a... | |
import codecs
import hashlib
import json
import logging
import numbers
import os
import re
import shutil
import sys
import six
from six.moves.collections_abc import Sequence as SixSequence
import wandb
from wandb import util
from wandb._globals import _datatypes_callback
from wandb.compat import tempfile
from wandb.ut... | |
# Bismillah
# Bagian 1 - Import library yang dibutuhkan
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def compare_values(act_col, sat_col):
act_vals = []
sat_vals = []
# Buat List dulu agar bisa dicek
for a_val in act_col:
act_vals.append(a_val)
... | |
#!/usr/bin/python
import os, sys
import json
from typing import Optional
import numpy as np
import re
### YOUR CODE HERE: write at least three functions which solve
### specific tasks by transforming the input x and returning the
### result. Name them according to the task ID as in the three
### examples below. Dele... | |
import numpy as np
import joblib
from .rbm import RBM
from .utils import sigmoid
# TODO(anna): add sparsity constraint
# TODO(anna): add entroty loss term
# TODO(anna): add monitoring kl divergence (and reverse kl divergence)
# TODO(anna): run on the paper examples again
# TODO(anna): try unit test case? say in a 3x3... | |
import numpy as np
from matplotlib import pyplot
from scipy.integrate import solve_ivp as ode45
from scipy.interpolate import CubicSpline
def seirmodel(t, y, gamma, sigma, eta, Rstar):
n = 10**7
dy = np.zeros(5)
#beta(t) et e(t) donc 5eqn, page 2 equations
dy[0] = (-y[4]*y[0]*y[2])/n ... | |
import numpy as np
from .nv_py_regular_linreg import nv_regular_linreg
from .mp_py_regular_linreg import mp_regular_linreg
from .cpp_py_regular_linreg import cpp_regular_linreg
from .sklearn_py_regular_linreg import sklearn_regular_linreg
class RegularizedLinearRegression(object):
def __init__(self, alpha=1.0, L1... | |
"""
base.py: Base class for linear transforms
"""
import numpy as np
import os
class BaseLinTrans(object):
"""
Linear transform base class
The class provides methods for linear operations :math:`z_1=Az_0`.
**SVD decomposition**
Some estimators require an SVD-like decomposition. The... | |
# -*- coding: utf-8 -*-
"""
Created on Mon May 13 23:28:06 2019
@author: walter
"""
import arcade
import numpy as np
SCREEN_WIDTH = 320
SCREEN_HEIGHT = 240
SCREEN_TITLE = "Pong"
MOVEMENT_SPEED = 2
PADDLE_MOVEMENT_SPEED = 1.25
PLAYER1_UP = arcade.key.W
PLAYER1_DOWN = arcade.key.S
PLAYER2_UP = arcade.key.UP
PLAYER2_D... | |
"""Train and test CNN classifier"""
import dga_classifier.data as data
import numpy as np
from keras.preprocessing import sequence
import sklearn
from sklearn.model_selection import train_test_split
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Activation, Conv1D, Input, Dense, co... | |
# -*- coding: utf-8 -*-
"""
vb_nmf.py
Variational Bayes NMF
"""
import scipy as sp
from ..bayes import *
def vb_nmf(X, a_w, b_w, a_h, b_h, n_iter=100):
"""
Variational Bayes NMF
変分ベイズ法によるNMF
"""
# initialize
Winit = gamma(x, a_w, b_w/a_w)
Hinit = gamma(x, a_h, b_h/a_h)
Lw = Winit
... | |
import numpy as np
from . import integer_manipulations as int_man
from . import quaternion as quat
from math import pi
class Col(object):
"""
This class is defined to ouput a word or sentence in a different color
to the standard shell.
The colors available are:
``pink``, ``blue``, ``green``, ``dgr... | |
from __future__ import division, absolute_import, print_function
import sys, os, re, mapp
import sphinx
if sphinx.__version__ < "1.0.1":
raise RuntimeError("Sphinx 1.0.1 or newer required")
needs_sphinx = '1.0'
# -----------------------------------------------------------------------------
# General configurati... | |
from ScopeFoundry import Measurement
from ScopeFoundry.helper_funcs import sibling_path, load_qt_ui_file
from ScopeFoundry import h5_io
import pyqtgraph as pg
import numpy as np
import time
class SineWavePlotMeasure(Measurement):
# this is the name of the measurement that ScopeFoundry uses
# when display... | |
# import numpy as np
# from array import *
fhandi=open('answer.txt')
fhando=open('histoplotuvw1qq.dat','w')
#x=raw_input('Enter the number of bins > ')
x=1000
y=x/20
bins=int(x)
brange=[0]
nrange=[]
to=float(0.0)
# nrange=array('f',[0])
b0=100
b1=200
b2=300
b3=400
b4=500
b5=600
b6=700
b7=800
b8=90... | |
## Este script no es necesario usarlo después del 01 de Abril de 2020
"""
Se realiza este script para construir las columnas "casos_nuevos" y
"fallecidos_nuevos", sólo para los informes diarios previos (e incluído) al
01 de Abril. Esto porque el minsal antes del 25 de marzo no indicaba los
"casos nuevos", sino que... | |
import json
import os
import numpy as np
import torch
import torchvision
from torch.autograd import Variable
from fool_models.stack_attention import CnnLstmSaModel
from neural_render.blender_render_utils.constants import find_platform_slash
from utils.train_utils import ImageCLEVR_HDF5
from skimage.color import rgba2... | |
##########################################################################
# Name: calEvoRateLow.py
#
# Calucurate Bomb Low
#
# Usage:
#
# Author: Ryosuke Tomita
# Date: 2021/08/13
##########################################################################
from netCDF4 import Dataset
import numpy as np
fileName = Datase... | |
# -*- coding: utf-8 -*-
# This is the skeleton of PISCOLA, the main file
import piscola
from .filter_utils import integrate_filter, calc_eff_wave, calc_pivot_wave, calc_zp, filter_effective_range
from .gaussian_process import gp_lc_fit, gp_2d_fit
from .extinction_correction import redden, deredden, calculate_ebv
from ... | |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
import pytest
import numpy as np
from ..common_utils import (
create_iris_data, create_lightgbm_classifier
)
from responsibleai import ModelAnalysis
class TestCounterfactualAdvancedFeatures(object):
@pytest.mark.parametrize('vary_all_... | |
"""
:author: Damian Eads, 2009
:license: modified BSD
"""
import numpy as np
def square(width, dtype=np.uint8):
"""
Generates a flat, square-shaped structuring element. Every pixel
along the perimeter has a chessboard distance no greater than radius
(radius=floor(width/2)) pixels.
Parameters
... | |
#!/usr/bin/env python3
# Tensorflow
import tensorflow as tf
import warnings
warnings.filterwarnings("ignore")
import re
# import nltk
# import tqdm as tqdm
# import sqlite3
import pandas as pd
import numpy as np
from pandas import DataFrame
import string
#from nltk.corpus import stopwords
#stop = stopwords.words("e... | |
from rdkit import Chem
from functools import partial
from fuseprop import extract_subgraph
from .hypergraph import mol_to_hg
from GCN.feature_extract import feature_extractor
from copy import deepcopy
import numpy as np
class MolGraph():
def __init__(self, mol, is_subgraph=False, mapping_to_input_mol=None):
... | |
"""
Refin Ananda Putra
github.com/refinap
"""
#create network
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
import tensorflow as tf
from keras.models import Model, Sequential
from keras.layers import Input, Activation, Dense
from tensorflow.keras.optimizers import SGD
#gener... | |
import numpy as np
from scipy.signal import windows
from ..optics import OpticalElement, LinearRetarder, Apodizer, AgnosticOpticalElement, make_agnostic_forward, make_agnostic_backward, Wavefront
from ..propagation import FraunhoferPropagator
from ..field import make_focal_grid, Field, field_dot
from ..aperture import... | |
from copy import copy
from itertools import count
import click
import matplotlib
import matplotlib.cm
import numpy as np
import pandas as pd
import xarray as xr
from lib import click_utils
import plot
from visualization.style import set_style
gs_labels = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]
... | |
# pre/_shiftscale.py
"""Tools for preprocessing data."""
__all__ = [
"shift",
"scale",
]
import numpy as np
# Shifting and MinMax scaling =================================================
def shift(X, shift_by=None):
"""Shift the columns of X by a vector.
Parameters
--... | |
# https://cran.r-project.org/web/packages/PerformanceAnalytics/vignettes/portfolio_returns.pdf
import pandas as pd
import numpy as np
import warnings
# https://stackoverflow.com/questions/16004076/python-importing-a-module-that-imports-a-module
from . import functions as pa
class Portfolio(object):
"""
"""
... | |
import h5py
import numpy as np
import cv2
def read_new(archive_dir):
with h5py.File(archive_dir, "r", chunks=True, compression="gzip") as hf:
"""
Load our X data the usual way,
using a memmap for our x data because it may be too large to hold in RAM,
and loading Y as normal ... | |
from ray import tune
import numpy as np
import pdb
from softlearning.misc.utils import get_git_rev, deep_update
M = 256
REPARAMETERIZE = True
NUM_COUPLING_LAYERS = 2
GAUSSIAN_POLICY_PARAMS_BASE = {
'type': 'GaussianPolicy',
'kwargs': {
'hidden_layer_sizes': (M, M),
'squash': True,
}
}
G... | |
# Copyright 2021 Sony Group Corporation.
#
# 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 ... | |
#!/usr/bin/env python3
"""Generate graph of fictional/mythical classes from Wikidata JSON dump"""
import sys
import json
import networkx as nx
from wd_constants import lang_order
roots = ('Q18706315', 'Q14897293', 'Q17442446')
subclass = 'P279'
def get_label(obj):
"""get appropriate label, using language fall... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ### Libraries
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from matplotlib import cm, pyplot as plt
from matplotlib.dates import YearLocator, MonthLocator
from hmmlearn.hmm import GaussianHMM
import scipy
im... | |
from typing import Callable
import numpy as np
def odesolver45(f: Callable, t: float, y: np.ndarray, h: float, *args, **kwargs):
"""
Calculate the next step of an IVP of a time-invariant ODE with a RHS
described by f, with an order 4 approx. and an order 5 approx.
Adapted from here: https://github.co... | |
import tensorflow as tf
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
n = 100
x = np.linspace(-10, 10, n)
y = np.linspace(-10, 10, n)
X, Y = np.meshgrid(x, y)
plt.figure(figsize=(8, 6))
Z = X + Y
plt.subplot(221)
plt.pcolormesh(X, Y, Z, cmap='rainbow')
plt.subplot(222)
plt.contourf(X, Y,... | |
# Copyright 2015 Mario Graff Guerrero
# 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... | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... | |
from __future__ import annotations
import functools
import dataclasses
from typing import Any, Optional
from dataclasses import dataclass
@dataclass(frozen=True)
class State:
left_one: Optional[str]
left_two: Optional[str]
right_one: Optional[str]
right_two: Optional[str]
one: tuple[Optional[str... | |
# -*- coding: utf-8 -*-
"""dataset_collection
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lHElNaOJc6KguYAQuFrWGjVqDUUk3an8
"""
import os
from requests import get
import pandas as pd
import numpy as np
from tqdm import tqdm
os.system("wget https:/... | |
import os
import argparse
import numpy as np
import pandas as pd
def arg_parse():
parser = argparse.ArgumentParser(description='RPIN Parameters')
parser.add_argument('--folder', required=True, help='folder name to retrive results', type=str)
return parser.parse_args()
def main():
'''
returns two... | |
"""
Visibility Road Map Planner
author: Atsushi Sakai (@Atsushi_twi)
"""
import os
import sys
import math
import numpy as np
import matplotlib.pyplot as plt
from geometry import Geometry
sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
"/../VoronoiRoadMap/")
from dijkstra_search import... | |
# author: Xiang Gao at Microsoft Research AI NLP Group
import torch, os, pdb
import numpy as np
from transformers19 import GPT2Tokenizer, GPT2Model, GPT2Config
from shared import EOS_token
class OptionInfer:
def __init__(self, cuda=True):
self.cuda = cuda
class ScorerBase(torch.nn.Module):
def __i... | |
from modules.world import World, Landmark, Map, Goal
from modules.grid_map_2d import GridMap2D
from modules.robot import IdealRobot
from modules.sensor import IdealCamera, Camera
from modules.agent import Agent, EstimationAgent, GradientAgent
from modules.gradient_pfc import GradientPfc
from modules.mcl import Particle... | |
import unittest
import numpy
from cqcpy import test_utils
from cqcpy.ov_blocks import one_e_blocks
from cqcpy.ov_blocks import two_e_blocks
from kelvin import quadrature
from kelvin import ft_cc_energy
from kelvin import ft_cc_equations
def evalL(T1f, T1b, T1i, T2f, T2b, T2i, L1f, L1b, L1i, L2f, L2b, L2i,
F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.