repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
pySDC | pySDC-master/pySDC/implementations/hooks/log_extrapolated_error_estimate.py | from pySDC.core.Hooks import hooks
class LogExtrapolationErrorEstimate(hooks):
"""
Store the extrapolated error estimate at the end of each step as "error_extrapolation_estimate".
"""
def post_step(self, step, level_number):
"""
Record extrapolated error estimate
Args:
... | 908 | 25.735294 | 100 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/BaseTransfer_mass.py | from pySDC.core.BaseTransfer import base_transfer
from pySDC.core.Errors import UnlockError
class base_transfer_mass(base_transfer):
"""
Standard base_transfer class
Attributes:
logger: custom logger for sweeper-related logging
params(__Pars): parameter object containing the custom parame... | 6,619 | 34.212766 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferPETScDMDA.py | from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.petsc_vec import petsc_vec, petsc_vec_imex, petsc_vec_comp2
class mesh_to_mesh_petsc_dmda(space_transfer):
"""
This implementation can restrict and prolong between PETSc ... | 2,871 | 36.789474 | 103 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferMesh.py | import numpy as np
import scipy.sparse as sp
import pySDC.helpers.transfer_helper as th
from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh, comp2_mesh
class mesh_to_mesh(space_transfer):
"""
C... | 11,661 | 44.027027 | 115 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferMesh_MPIFFT.py | from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
from mpi4py_fft import PFFT, newDistArray
class fft_to_fft(space_transfer):
"""
Custon base_transfer class, implements Transfer.py
This i... | 5,515 | 41.430769 | 112 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferMesh_NoCoarse.py | from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
class mesh_to_mesh(space_transfer):
"""
Custon base_transfer class, implements Transfer.py
This implementation can restrict and prolong b... | 1,746 | 28.610169 | 106 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferMesh_FFT2D.py | import numpy as np
from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
class mesh_to_mesh_fft2d(space_transfer):
"""
Custon base_transfer class, implements Transfer.py
This implementation ... | 4,322 | 42.666667 | 113 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/__init__.py | 0 | 0 | 0 | py | |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferFenicsMesh.py | import dolfin as df
from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.fenics_mesh import fenics_mesh, rhs_fenics_mesh
class mesh_to_mesh_fenics(space_transfer):
"""
This implementation can restrict and prolong between f... | 2,708 | 32.444444 | 91 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferParticles_NoCoarse.py | from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.particles import particles, fields, acceleration
class particles_to_particles(space_transfer):
"""
Custon transfer class, implements SpaceTransfer.py
This implementa... | 1,724 | 27.278689 | 119 | py |
pySDC | pySDC-master/pySDC/implementations/transfer_classes/TransferMesh_FFT.py | import numpy as np
from pySDC.core.Errors import TransferError
from pySDC.core.SpaceTransfer import space_transfer
from pySDC.implementations.datatype_classes.mesh import mesh, imex_mesh
class mesh_to_mesh_fft(space_transfer):
"""
Custom base_transfer class, implements Transfer.py
This implementation ca... | 3,062 | 35.903614 | 99 | py |
pySDC | pySDC-master/docs/convert_markdown.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 19:47:56 2023
@author: telu
"""
import os
import glob
import json
import m2r2
import shutil
import numpy as np
mdFiles = ['README.md', 'CONTRIBUTING.md', 'CHANGELOG.md', 'CODE_OF_CONDUCT.md', 'docs/contrib']
docSources = 'docs/source'
# Move a... | 3,045 | 25.955752 | 96 | py |
pySDC | pySDC-master/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pySDC documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 11 15:58:40 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... | 10,415 | 28.258427 | 119 | py |
SGR | SGR-main/sgr_main.py | import os
from arg_parser import parse_args
from sgr.sgr import SGR
def main():
params = parse_args()
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, params.neat_config)
pop = SGR(
config_path,
params.robot_size,
params.spec_genotype_weight,
p... | 634 | 20.166667 | 61 | py |
SGR | SGR-main/multiple_env_hyperneat.py |
import os
import numpy as np
import sys
from typing import Dict
from pathos.multiprocessing import ProcessPool
from evogym import get_full_connectivity
import evogym.envs
from sgr.custom_reporter import CustomReporter, remove_reporters
from arg_parser import parse_args
from sgr.evogym_sim import get_obs_size
from sgr... | 2,869 | 33.578313 | 85 | py |
SGR | SGR-main/poet_test.py | from poet.poet import POET
from arg_parser import parse_args
from sgr.sgr import SGR
import os
import numpy as np
def main():
params = parse_args()
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, params.neat_config)
seed = np.random.SeedSequence()
poet_alg = P... | 451 | 17.833333 | 61 | py |
SGR | SGR-main/arg_parser.py | import argparse
import json
import os
def default_values():
default = {
"gens": 250,
"robot_size": 5,
"steps": 400,
"env": "dynamic", # env_names = ["CaveCrawler-v0", "UpStepper-v0", "ObstacleTraverser-v0"]
"n_threads": 4,
"save_to": "",
"goal_fit": 10,
... | 9,264 | 54.14881 | 137 | py |
SGR | SGR-main/poet/poet.py | from distutils.command.config import config
from time import time
from typing import List
import numpy as np
from copy import deepcopy
import pickle
from dynamic_env.env_config import EnvConfig
from sgr.sgr import SGR
from arg_parser import Parameters
import pathlib
RESULTS_DIR = "checkpoints"
class Pair:
""" A P... | 13,885 | 41.206687 | 182 | py |
SGR | SGR-main/poet/__init__.py | 0 | 0 | 0 | py | |
SGR | SGR-main/baseline_algs/single_genome_neat.py | import neat
import os
import numpy as np
import errno
import dill
import neat
import time
import neat.nn
import pathlib
import sys
from typing import Dict
from pathos.multiprocessing import ProcessPool
from evogym import get_full_connectivity
import evogym.envs
sys.path.append('../')
from sgr.custom_reporter import Cu... | 5,678 | 31.82659 | 136 | py |
SGR | SGR-main/baseline_algs/alt_arg_parser.py | import argparse
def parse_args():
args_dict = {}
# Default Values
gens = 500
robot_size = 5
steps = 600
env = "Walker-v0" # env_names = ["CaveCrawler-v0", "UpStepper-v0", "ObstacleTraverser-v0"]
n_threads = 6
save_to = ""
goal_fit = 10
max_stag = 100
structure_pop ... | 3,248 | 40.653846 | 121 | py |
SGR | SGR-main/baseline_algs/multiple_genome_neat.py | import neat
import os
import numpy as np
import errno
import dill
import neat
import math
import neat.nn
import pathlib
import sys
from typing import Dict
from pathos.multiprocessing import ProcessPool
from evogym import hashable
sys.path.append('../')
from alt_arg_parser import parse_args
from sgr.custom_reporter imp... | 5,814 | 33.613095 | 136 | py |
SGR | SGR-main/hyperneat/hyperNEAT.py | """
All Hyperneat related logic resides here.
"""
import neat
def create_phenotype_network(cppn, substrate, activation_function="tanh", output_activation="identity", output_node_idx=0):
"""
Creates a recurrent network using a cppn and a substrate.
"""
input_coordinates = substrate.input_coordinates
... | 3,452 | 34.96875 | 123 | py |
SGR | SGR-main/hyperneat/test_cppn.py | """
Visualizes a CPPN - remember to edit path in visualize.py, sorry.
"""
import pickle
from pureples.es_hyperneat.es_hyperneat import find_pattern
from pureples.shared.visualize import draw_pattern
path_to_cppn = "es_hyperneat_xor_small_cppn.pkl"
# For now, path_to_cppn should match path in visualize.py, sorry.
wit... | 469 | 28.375 | 65 | py |
SGR | SGR-main/hyperneat/__init__.py | 0 | 0 | 0 | py | |
SGR | SGR-main/hyperneat/substrate.py | import itertools as it
import numpy as np
def calc_layer(*coords):
coord_arr = []
for i in coords[:-1]:
aux = np.linspace(-1.0, 1.0, i) if (i > 1) else [0.0]
coord_arr.append(aux)
last_coord = [coords[-1]]
return tuple(it.product(*coord_arr, last_coord))
"""
The substrate.
"""
class S... | 785 | 25.2 | 122 | py |
SGR | SGR-main/hyperneat/visualize.py | """
Varying visualisation tools.
"""
import pickle
import graphviz
import matplotlib.pyplot as plt
def draw_net(net, filename=None, node_names={}, node_colors={}):
"""
Draw neural network with arbitrary topology.
"""
node_attrs = {
'shape': 'circle',
'fontsize': '9',
'height':... | 3,225 | 26.810345 | 99 | py |
SGR | SGR-main/hyperneat/create_cppn.py | """
CPPN creator.
"""
import neat
from neat.graphs import feed_forward_layers
def create_cppn(genome, config, output_activation_function="tanh"):
"""
Receives a genome and returns its phenotype (a FeedForwardNetwork).
"""
# Gather expressed connections.
connections = [cg.key for cg in genome.con... | 1,659 | 35.888889 | 96 | py |
SGR | SGR-main/dynamic_env/generateJSON.py | import json
import numpy as np
N_TYPES = ['empty', 'rigid', 'soft', 'hori', 'vert']
EMPTY_VX = 0
RIGID_VX = 1
SOFT_VX = 2
HORI_VX = 3
VERT_VX = 4
FIXED_VX = 5
STARTING_ZONE = 12
def base_json(width, height):
env_json = {
"grid_width": width,
"grid_height": height,
"objects": {}
}
... | 2,187 | 26.35 | 92 | py |
SGR | SGR-main/dynamic_env/traverser.py | from gym import error, spaces
from evogym import *
from evogym.envs import WalkingBumpy2, StairsBase
import numpy as np
import os
from dynamic_env.generateJSON import generate_env_json
from dynamic_env.env_config import EnvConfig
class DynamicObstacleTraverser(WalkingBumpy2):
def __init__(self, body, connectio... | 2,521 | 34.027778 | 139 | py |
SGR | SGR-main/dynamic_env/__init__.py | 0 | 0 | 0 | py | |
SGR | SGR-main/dynamic_env/env_config.py | from copy import deepcopy
import os
import numpy as np
import json
import itertools
from .generateJSON import generate_env_json
class EnvConfig:
idCounter = itertools.count().__next__
def __init__(self, seed, width = 150, height = 18, flat_start = 9):
self.id = self.idCounter()
self.seed = see... | 2,464 | 28.698795 | 79 | py |
SGR | SGR-main/sgr/custom_reporter.py | from __future__ import division, print_function
import time
from neat.math_util import mean, stdev
from neat.six_util import itervalues, iterkeys
from neat.reporting import ReporterSet
import neat
class CustomReporter():
"""Uses `print` to output information about the run; an example reporter class."""
def _... | 4,142 | 42.610526 | 166 | py |
SGR | SGR-main/sgr/generate_robot.py | import numpy as np
from .substrates import raise_substrate_error
from evogym import is_connected, has_actuator
N_TYPES = ['empty', 'rigid', 'soft', 'hori', 'vert']
def generate_robot_3D_out(net, robot_size):
graph_out = net.activate([1997])
formated_output = np.reshape(graph_out, (robot_size, robot_size, len(... | 1,509 | 29.2 | 88 | py |
SGR | SGR-main/sgr/sgr.py | from copy import deepcopy
from multiprocessing import TimeoutError
import multiprocess
import neat
import os
import numpy as np
import errno
import dill
import neat
import time
import neat.nn
import pathlib
import itertools
from neat.reporting import ReporterSet
from pathos.multiprocessing import ProcessPool
from hyp... | 9,182 | 35.879518 | 133 | py |
SGR | SGR-main/sgr/__init__.py | 0 | 0 | 0 | py | |
SGR | SGR-main/sgr/body_speciation.py | import neat
import numpy as np
from hyperneat.hyperNEAT import create_phenotype_network
from evogym import is_connected, has_actuator
def robot_from_genome(genome, robot_size, substrate, robot_func, config):
cppn = neat.nn.FeedForwardNetwork.create(genome, TempConfig(config))
design_net = create_phenotype_net... | 2,058 | 37.12963 | 163 | py |
SGR | SGR-main/sgr/evogym_sim.py | import math
from evogym import get_full_connectivity
import evogym.envs
import imageio
import numpy as np
import os
from dynamic_env.traverser import DynamicObstacleTraverser
from dynamic_env.env_config import EnvConfig
def get_env(robot, connections, env_name, dynamic_env_config:EnvConfig =None):
if env_name == ... | 2,276 | 32 | 114 | py |
SGR | SGR-main/sgr/substrates.py | import itertools as it
import math
import numpy as np
from sgr.evogym_sim import get_obs_size
from hyperneat.substrate import Substrate
def raise_substrate_error():
print("Substrate type should be specified")
print("Available substrates: [cppn, 3d]")
raise
def morph_substrate(robot_size, substrate_name):
... | 2,110 | 28.319444 | 70 | py |
SGR | SGR-main/configs/__init__.py | 0 | 0 | 0 | py | |
SGR | SGR-main/evaluators/poet_evaluator.py | import neat
import os
import evogym.envs
from evogym import is_connected, has_actuator, get_full_connectivity, hashable
import numpy as np
import pickle as pkl
import sys
sys.path.append('../')
from typing import List
from sgr.substrates import morph_substrate
from sgr.generate_robot import generate_robot
from sgr.sgr... | 5,858 | 32.672414 | 116 | py |
AACL-22 | AACL-22-main/utils/template_utils.py | import os
import pandas as pd
import os.path as path
import re
from pprint import pprint
import readtime
from jinja2 import Template
import numpy as np
from jinja2 import Template
from bs4 import BeautifulSoup
def read_json(path):
import json
with open(path) as json_file:
data = json.load(json_file)... | 8,250 | 31.105058 | 198 | py |
AACL-22 | AACL-22-main/utils/utils.py | import pandas as pd
import numpy as np
from nltk.metrics.agreement import AnnotationTask
from nltk.metrics import interval_distance, binary_distance
import datetime
from matplotlib import pyplot as plt
import seaborn as sns
import operator
from subprocess import PIPE, run
import pathlib
sns.set_style("darkgrid")
de... | 7,908 | 32.231092 | 212 | py |
NFLPlayPrediction | NFLPlayPrediction-master/main.py | import random
from machine_learning.classification import compare_classification_parameters
from machine_learning.neural_network_prediction import neural_network_prediction
from machine_learning.regression import compute_regression_results
from preprocessing.analysis import apply_pca, apply_kernel_pca, apply_anova_f_v... | 3,326 | 36.382022 | 102 | py |
NFLPlayPrediction | NFLPlayPrediction-master/postprocessing/evaluate.py | from __future__ import division
import math
import os
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from sklearn import tree
from sklearn.metrics import confusion_matrix as confusion_matrix_func
from sklearn.model_selection import KFold
def predict_superbowl(encoder, classif... | 5,550 | 36.255034 | 120 | py |
NFLPlayPrediction | NFLPlayPrediction-master/postprocessing/__init__.py | from evaluate import *
| 23 | 11 | 22 | py |
NFLPlayPrediction | NFLPlayPrediction-master/machine_learning/classification.py | from __future__ import division
from collections import Counter
from random import random
from sklearn import tree
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.neighbor... | 4,865 | 38.560976 | 112 | py |
NFLPlayPrediction | NFLPlayPrediction-master/machine_learning/neural_network_prediction.py | import os
import pickle
import numpy as np
from pybrain.datasets import SupervisedDataSet, ClassificationDataSet
from pybrain.structure import SigmoidLayer, LinearLayer
from pybrain.structure import TanhLayer
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
from ... | 7,740 | 42.982955 | 145 | py |
NFLPlayPrediction | NFLPlayPrediction-master/machine_learning/regression.py | from __future__ import division
from sklearn import tree
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR
from postprocessing.evaluate import regression_evaluate
'''
estimator = the SVM you wish to use to classify the data
features = a (sa... | 3,594 | 46.302632 | 120 | py |
NFLPlayPrediction | NFLPlayPrediction-master/machine_learning/__init__.py | from classification import *
from neural_network_prediction import *
from regression import * | 93 | 30.333333 | 39 | py |
NFLPlayPrediction | NFLPlayPrediction-master/machine_learning/trained_models/__init__.py | 0 | 0 | 0 | py | |
NFLPlayPrediction | NFLPlayPrediction-master/preprocessing/features.py | # Load games
from __future__ import division
import nflgame
# Extract features
import re
from collections import defaultdict
import numpy as np
from sklearn.feature_extraction import DictVectorizer
def extract_features(start_year, end_year):
play_features = []
success_labels = []
yard_labels = []
pr... | 16,208 | 48.417683 | 191 | py |
NFLPlayPrediction | NFLPlayPrediction-master/preprocessing/analysis.py | import pickle
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA, KernelPCA
from sklearn.feature_selection import VarianceThreshold
from sklearn.feature_selection import f_classif
def apply_pca(features, n_components):
pca = PCA(n_components = n_components)
pca.fit(featu... | 4,315 | 26.845161 | 91 | py |
NFLPlayPrediction | NFLPlayPrediction-master/preprocessing/__init__.py | from analysis import *
from features import * | 45 | 22 | 22 | py |
dswgan-paper | dswgan-paper-main/exhibits.py | import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import ot
#define paths and set random seed
data_path = "data/"
fig_path = "figures/"
random.seed(100)
################################################################################
## Helper Functions
############################... | 6,905 | 37.581006 | 109 | py |
dswgan-paper | dswgan-paper-main/gan_estimation/gan_baseline.py | import ldw_gan
import pandas as pd
# first redo with the original data
output_path = "data/generated/"
data_path = "data/original_data/"
#
file = data_path+"exp_merged.feather"
df = pd.read_feather(file).drop(["u74", "u75"], axis=1)
ldw_gan.do_all(df, "exp", batch_size=128, max_epochs=1000, path=output_path)
file = d... | 658 | 33.684211 | 77 | py |
dswgan-paper | dswgan-paper-main/gan_estimation/ldw_gan.py | #wrapper function to save model weights and generate large dataset for
#any Lalonde dataset passed
import wgan
import torch
import pandas as pd
import numpy as np
import ot
from hypergrad import AdamHD
def wd_distance(real, gen):
n = real.shape[0]
a = np.ones(n)/n
d_gen = ot.emd2(a, a, M=ot.dist(real.to_numpy()... | 4,765 | 44.826923 | 156 | py |
dswgan-paper | dswgan-paper-main/gan_estimation/gan_robust.py | import ldw_gan
import pandas as pd
import numpy as np
import multiprocessing
from multiprocessing import active_children
from joblib import Parallel, delayed
num_cores = multiprocessing.cpu_count()
print(num_cores)
# first redo with the original data
epochs=5000
batch=4096
output = "data/generated/robustness/"
datapa... | 1,834 | 39.777778 | 127 | py |
dswgan-paper | dswgan-paper-main/data/original_data/merge_data.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 10:20:16 2019
@author: jonas
"""
import pandas as pd
exp = pd.read_feather("exp_merged.feather")
cps = pd.read_feather("cps_controls.feather")
psid = pd.read_feather("psid_controls.feather")
cps = pd.concat((exp.loc[exp.t==1], cps), ignore_ind... | 468 | 23.684211 | 62 | py |
dswgan-paper | dswgan-paper-main/monotonicity_penalty/monotonicity.py | import wgan
import pandas as pd
import torch
import numpy as np
import torch.nn.functional as F
from matplotlib import pyplot as plt
########################################
# setup
########################################
df = pd.read_feather("data/original_data/cps_merged.feather").drop("u75",1).drop("u74",1)
df = ... | 7,429 | 41.701149 | 160 | py |
HC-MGAN | HC-MGAN-main/fmnist.py | import argparse
import os
import sys
from utils.data import create_dataloader, merge_dataloaders
from tree.tree import Node, grow_tree_from_root
import torch
parser = argparse.ArgumentParser()
#main config
parser.add_argument('--dataset_path', type=str, default='data',
metavar='', help='Path fo... | 5,985 | 64.065217 | 202 | py |
HC-MGAN | HC-MGAN-main/sop.py | import argparse
import os
import sys
from utils.data import create_dataloader, merge_dataloaders
from tree.tree import Node, grow_tree_from_root
import torch
parser = argparse.ArgumentParser()
#main config
parser.add_argument('--dataset_path', type=str, default='data',
metavar='', help='Path f... | 5,968 | 63.880435 | 202 | py |
HC-MGAN | HC-MGAN-main/mnist.py | import argparse
import os
import sys
from utils.data import create_dataloader, merge_dataloaders
from tree.tree import Node, grow_tree_from_root
import torch
parser = argparse.ArgumentParser()
#omain config
parser.add_argument('--dataset_path', type=str, default='data',
metavar='', help='Path ... | 5,984 | 63.354839 | 202 | py |
HC-MGAN | HC-MGAN-main/models/models_32x32.py | import argparse
import os
from torch.autograd import Variable
import torch.nn as nn
import torch
from models.utils import verify_string_args, linear_block, Reshape, convT_block, conv_block
class Generator(nn.Module):
def __init__(self,
architecture = 'cnn',
nf=128,
... | 5,899 | 39.972222 | 225 | py |
HC-MGAN | HC-MGAN-main/models/models_general.py | import torch.nn as nn
import torch.nn.functional as F
import torch
class GeneratorSet(nn.Module):
def __init__(self, *gens):
super(GeneratorSet, self).__init__()
modules = nn.ModuleList()
for gen in gens:
modules.append(gen)
self.paths = modules
def forward... | 2,298 | 29.25 | 70 | py |
HC-MGAN | HC-MGAN-main/models/utils.py | from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
def get_seq_model_shapes(seq_model, input_shape, seq_model_name = 'seq_model'):
input_tensor = torch.zeros(*input_shape)
output = input_tensor
print("\n{} Layers:\n".format(seq_model_name))
for i... | 2,061 | 33.949153 | 116 | py |
HC-MGAN | HC-MGAN-main/models/gan.py | #torch imports
from torch.autograd import Variable
import torch
import numpy as np
class GAN:
def __init__(self,
gen_set,
disc,
clasf,
feature_layers,
optimizer_G,
optimizer_D,
optimizer_C,
... | 12,909 | 42.177258 | 143 | py |
HC-MGAN | HC-MGAN-main/models/models_28x28.py | import argparse
import os
from torch.autograd import Variable
import torch.nn as nn
import torch
from models.utils import verify_string_args, linear_block, Reshape, convT_block, conv_block
class Generator(nn.Module):
def __init__(self,
architecture = 'cnn',
nf=128,
... | 5,274 | 37.786765 | 225 | py |
HC-MGAN | HC-MGAN-main/models/__init__.py | 0 | 0 | 0 | py | |
HC-MGAN | HC-MGAN-main/tree/tree.py | import torch
from tree.refinement import refinement
from tree.raw_split import raw_split
import numpy as np
import copy
import os
from utils.soft_cluster import view_global_tree_logs, show, view_global_tree_logs
from utils.others import save_log_text, remove_bold_from_string, print_save_log, get_log_heading
class Nod... | 9,572 | 49.920213 | 184 | py |
HC-MGAN | HC-MGAN-main/tree/refinement.py | #basic imports
import argparse
import os
import numpy as np
import math
import shutil
import time
import datetime
import copy
import sys
#torch imports
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torchvision import datase... | 24,678 | 52.417749 | 182 | py |
HC-MGAN | HC-MGAN-main/tree/raw_split.py | #basic imports
import argparse
import os
import numpy as np
import math
import shutil
import time
import datetime
import copy
import sys
#torch imports
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torchvision import datase... | 20,482 | 49.575309 | 182 | py |
HC-MGAN | HC-MGAN-main/utils/others.py | import os
import math
import torch
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torchvision import datasets
import torch
from models.gan import GAN
def sum_dicts(dict_a, dict_b):
assert(dict_a.keys() == dict_b.keys())
return {k:dict_a[k]+dict_b[k] for k,v... | 3,956 | 34.648649 | 122 | py |
HC-MGAN | HC-MGAN-main/utils/data.py | import os
import math
import torch
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torchvision import datasets
from torch.utils.data import Dataset
import torch
class MyDataset(Dataset):
def __init__(self, dataset):
self.dataset = dataset
self.t... | 3,721 | 46.113924 | 137 | py |
HC-MGAN | HC-MGAN-main/utils/soft_cluster.py | import os
import numpy as np
import math
import matplotlib.pyplot as plt
import torch
import seaborn as sn
import pandas as pd
import numpy as np
import math
from sklearn import metrics
import sklearn
import scipy
import scipy.optimize as opt
import matplotlib.pyplot as plt
import torchvision.transforms as transforms... | 13,406 | 46.042105 | 176 | py |
DKVMN | DKVMN-main/evaluation/run.py | """
Usage:
run.py [options]
Options:
--length=<int> max length of question sequence [default: 50]
--questions=<int> num of question [default: 100]
--lr=<float> learning rate [default: 0.001]
--bs=<int> batch siz... | 3,566 | 34.67 | 118 | py |
DKVMN | DKVMN-main/evaluation/eval.py | import tqdm
import torch
import logging
import os
from sklearn import metrics
logger = logging.getLogger('main.eval')
def __load_model__(ckpt):
'''
ckpt: Path of the checkpoint
return: Checkpoint dict
'''
if os.path.isfile(ckpt):
checkpoint = torch.load(ckpt)
print("Successfully loa... | 1,882 | 35.921569 | 130 | py |
DKVMN | DKVMN-main/evaluation/__init__.py | 0 | 0 | 0 | py | |
DKVMN | DKVMN-main/evaluation/checkpoint/__init__.py | 0 | 0 | 0 | py | |
DKVMN | DKVMN-main/evaluation/log/__init__.py | 0 | 0 | 0 | py | |
DKVMN | DKVMN-main/data/readdata.py | import numpy as np
import itertools
from sklearn.model_selection import KFold
class DataReader():
def __init__(self, train_path, test_path, maxstep, num_ques):
self.train_path = train_path
self.test_path = test_path
self.maxstep = maxstep
self.num_ques = num_ques
def getData(s... | 2,351 | 43.377358 | 92 | py |
DKVMN | DKVMN-main/data/dataloader.py | import torch
import torch.utils.data as Data
from .readdata import DataReader
#assist2015/assist2015_train.txt assist2015/assist2015_test.txt
#assist2017/assist2017_train.txt assist2017/assist2017_test.txt
#assist2009/builder_train.csv assist2009/builder_test.csv
def getDataLoader(batch_size, num_of_questions, max_st... | 1,089 | 50.904762 | 78 | py |
DKVMN | DKVMN-main/data/__init__.py | 0 | 0 | 0 | py | |
DKVMN | DKVMN-main/model/memory.py | import torch
from torch import nn
class DKVMNHeadGroup(nn.Module):
def __init__(self, memory_size, memory_state_dim, is_write):
super(DKVMNHeadGroup, self).__init__()
""""
Parameters
memory_size: scalar
memory_state_dim: scalar
is_write: ... | 5,209 | 41.704918 | 117 | py |
DKVMN | DKVMN-main/model/model.py | import torch
import torch.nn as nn
from model.memory import DKVMN
class MODEL(nn.Module):
def __init__(self, n_question, batch_size, q_embed_dim, qa_embed_dim, memory_size, final_fc_dim):
super(MODEL, self).__init__()
self.n_question = n_question
self.batch_size = batch_size
self.... | 3,932 | 44.206897 | 129 | py |
DKVMN | DKVMN-main/model/__init__.py | 0 | 0 | 0 | py | |
probabilistic-ensemble | probabilistic-ensemble-main/noise_mnist_utils.py | import tensorflow as tf
import tensorflow_probability as tfp
import os
import numpy as np
tfd = tfp.distributions
def normal_parse_params(params, min_sigma=0.0):
"""
将输入拆分成两份, 分别代表 mean 和 std.
min_sigma 是对 sigma 最小值的限制
"""
n = params.shape[0]
d = params.shape[-1] # channel
... | 1,087 | 33 | 91 | py |
probabilistic-ensemble | probabilistic-ensemble-main/baseline_train.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
from ensemble_model import BaselineModel
from noise_mnist_utils import normal_parse_params, rec_log_prob
import pickle
tfd = tfp.distributions
config = tf.ConfigProto()
config.gpu_options.allow_growth = True... | 6,002 | 34.732143 | 121 | py |
probabilistic-ensemble | probabilistic-ensemble-main/baseline_generate.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
from ensemble_model import BaselineModel
from noise_mnist_utils import normal_parse_params, rec_log_prob
tfd = tfp.distributions
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.enable_eag... | 4,805 | 31.255034 | 105 | py |
probabilistic-ensemble | probabilistic-ensemble-main/ensemble_model.py | import numpy as np
import tensorflow as tf
from noise_mnist_utils import normal_parse_params, rec_log_prob
layers = tf.keras.layers
tf.enable_eager_execution()
class ResBlock(tf.keras.Model):
"""
Usual full pre-activation ResNet bottleneck block.
"""
def __init__(self, outer_dim, inner_dim):
... | 6,326 | 38.055556 | 107 | py |
probabilistic-ensemble | probabilistic-ensemble-main/__init__.py | 0 | 0 | 0 | py | |
wind_system | wind_system-main/Server/test.py | import numpy as np
x = np.linspace(1,1,201)
y = np.random.random(201)
header = "FAN DATA\n"
header += "PWM x15, TACHO x15"
with open('FAN_data.dat', 'wb') as f: #w-writing mode, b- binary mode
np.savetxt(f, [], header=header)
for i in range(201):
data = np.column_stack((x[i],y[i]))
np.savetxt... | 368 | 23.6 | 69 | py |
wind_system | wind_system-main/Server/server.py | import random
import socket
import struct
import time
DEBUG = True
FANDATA_FMT = "hhhhhhhhhh"
fan_ip = [ '192.168.1.101','192.168.1.102', '192.168.1.103', '192.168.1.104', '192.168.1.105','192.168.1.106','192.168.1.107','192.168.1.108','192.168.1.109','192.168.1.110','192.168.1.111','192.168.1.112','192.168.1.113','1... | 3,122 | 27.390909 | 254 | py |
wind_system | wind_system-main/Server/server_gui.py | import random
import socket
import struct
import time
import numpy as np
from tkinter import *
#sudo apt-get install python-tk
# global variable
fan_value = 0
pwmValues = " ";
rpmValues = " ";
DEBUG = True
FANDATA_FMT = "HHHHHHHHHH"
fan_ip = [ '192.168.1.101','192.168.1.102', '192.168.1.103', '192.168.1.104', '192... | 5,336 | 24.782609 | 254 | py |
wind_system | wind_system-main/Tests/test.py | # import socket
#
# def send(data, port=50000, addr='239.192.1.100'):
# """send(data[, port[, addr]]) - multicasts a UDP datagram."""
# # Create the socket
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# # Make the socket multicast-aware, and set TTL.
# s.setsockopt(soc... | 2,301 | 36.737705 | 118 | py |
wind_system | wind_system-main/Tests/send_and_listen.py | import socket
# print(socket.gethostname())
HOST = '' # '169.254.179.148' # '192.168.0.177' # '169.254.255.255'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect((HOST, PORT))
print("Binded!")
while True:
print("while...")
rcv_data, rcv_addr = sock.... | 379 | 20.111111 | 67 | py |
finer | finer-main/run_experiment.py | import click
import os
import logging
from configurations.configuration import Configuration
from finer import FINER
logging.getLogger('tensorflow').setLevel(logging.ERROR)
logging.getLogger('transformers').setLevel(logging.ERROR)
LOGGER = logging.getLogger(__name__)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.envir... | 2,062 | 32.819672 | 110 | py |
finer | finer-main/finer.py | import itertools
import logging
import os
import time
import re
import datasets
import numpy as np
import tensorflow as tf
import wandb
from copy import deepcopy
from tqdm import tqdm
from gensim.models import KeyedVectors
from seqeval.metrics import classification_report
from seqeval.scheme import IOB2
from tensorflo... | 33,261 | 42.881266 | 138 | py |
finer | finer-main/models/callbacks.py | import logging
import numpy as np
import itertools
from tqdm import tqdm
from seqeval.metrics.sequence_labeling import precision_recall_fscore_support
from tensorflow.keras.callbacks import Callback, EarlyStopping
from configurations import Configuration
LOGGER = logging.getLogger(__name__)
class ReturnBestEarlyS... | 5,967 | 39.053691 | 104 | py |
finer | finer-main/models/transformer_bilstm.py | import tensorflow as tf
import numpy as np
from transformers import AutoTokenizer, TFAutoModel
from tf2crf import CRF
class TransformerBiLSTM(tf.keras.Model):
def __init__(
self,
model_name,
n_classes,
dropout_rate=0.1,
crf=False,
n_layers=1... | 5,047 | 29.409639 | 112 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.