repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
GAN-STEM-Conv2MultiSlice | GAN-STEM-Conv2MultiSlice-master/pix2pix/pix2pixGray.py | from __future__ import print_function, division
import scipy
#from keras.datasets import mnist
#from keras_contrib.layers.normalization import InstanceNormalization
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from ... | 18,816 | 39.729437 | 148 | py |
LSTA | LSTA-master/main_rgb.py | from __future__ import print_function, division
from attentionModel import *
from spatial_transforms import (Compose, ToTensor, CenterCrop, Scale, Normalize, MultiScaleCornerCrop,
RandomHorizontalFlip)
from tensorboardX import SummaryWriter
from makeDataset import *
import sys
import arg... | 13,449 | 41.698413 | 131 | py |
LSTA | LSTA-master/resNetNew.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/r... | 7,689 | 31.175732 | 87 | py |
LSTA | LSTA-master/attentionModel.py | import resNetNew
from torch.autograd import Variable
from MyConvLSTACell import *
class attentionModel(nn.Module):
def __init__(self, num_classes=51, mem_size=512, c_cam_classes=1000):
super(attentionModel, self).__init__()
self.num_classes = num_classes
self.resNet = resNetNew.resnet34(Tr... | 1,669 | 48.117647 | 114 | py |
LSTA | LSTA-master/test_rgb.py | from __future__ import print_function, division
from attentionModel import *
from spatial_transforms import (Compose, ToTensor, CenterCrop, Scale, Normalize, MultiScaleCornerCrop,
RandomHorizontalFlip)
from tensorboardX import SummaryWriter
from makeDataset import *
import sys
import arg... | 4,491 | 39.107143 | 131 | py |
LSTA | LSTA-master/makeDataset.py | import os
import torch
from torch.utils.data import Dataset
from PIL import Image
import numpy as np
import random
class makeDataset(Dataset):
def __init__(self, dataset, labels, numFrames, spatial_transform=None, seqLen=30,
train=True, mulSeg=False, numSeg=1, fmt='.jpg', mode='train'):
""... | 1,597 | 33 | 91 | py |
LSTA | LSTA-master/MyConvLSTACell.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class MyConvLSTACell(nn.Module):
def __init__(self, input_size, memory_size, c_cam_classes=100, kernel_size=3,
stride=1, padding=1, zero_init=False):
super(MyConvLSTACell, self).__init__()
self.input_size = input_s... | 7,249 | 45.774194 | 116 | py |
LSTA | LSTA-master/spatial_transforms.py | import random
import math
import numbers
import collections
import numpy as np
import torch
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
class Compose(object):
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects):... | 13,813 | 31.734597 | 121 | py |
AutoCAT | AutoCAT-main/src/models/dnn_model.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from typing import Dict, List, Tuple
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
from ray.rllib.models import Mod... | 4,084 | 36.477064 | 88 | py |
AutoCAT | AutoCAT-main/src/models/transformer_model.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from typing import Dict, List, Tuple
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
from ray.rllib.models import Mod... | 4,470 | 36.889831 | 77 | py |
AutoCAT | AutoCAT-main/src/models/backbone.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.append(os.path.dirname(os.path.dirname(os.path.absp... | 2,768 | 32.768293 | 76 | py |
AutoCAT | AutoCAT-main/src/models/dnn.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import torch
import torch.nn as nn
import torch.nn.functional as F
class ResidualBlock(nn.Module):
def __init__(self, dim: int) -> None:
... | 1,521 | 29.44 | 73 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_example_multicore_largel3.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.11
Function: An example rllib training script
'''
from random import random
import sys
import os
###sys.path.appen... | 3,186 | 30.87 | 95 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_example.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.11
Function: An example rllib training script
'''
from random import random
import sys
import os
###sys.path.appen... | 2,755 | 30.318182 | 95 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_example_multicore_flush.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.11
Function: An example rllib training script
'''
from random import random
import sys
import os
###sys.path.appen... | 3,239 | 30.764706 | 95 | py |
AutoCAT | AutoCAT-main/src/rllib/test_custom_policy_diversity_works.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# using ray 1.92 to run
# python 3.9
from ray.rllib.agents.ppo.ppo_torch_policy import PPOTorchPolicy
from ray.rllib.agents.a3c.a3c_torch_policy impo... | 19,897 | 38.558648 | 185 | py |
AutoCAT | AutoCAT-main/src/rllib/cache_query_env.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.12
Usage: wrapper for cachequery that interact with the gym environment
the observation space and action space sho... | 10,303 | 38.478927 | 160 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_agent_blacklist.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# look at https://github.com/ray-project/ray/blob/ea2bea7e309cd60457aa0e027321be5f10fa0fe5/rllib/examples/custom_env.py#L2
#from CacheSimulator.src.gy... | 8,329 | 42.385417 | 122 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_reveal_action.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.10
Function: Add one reveal action so that the agent has to explicit reveal the secret,
once the secret is reveale... | 6,095 | 35.945455 | 114 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_example_multicore_largel2.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.11
Function: An example rllib training script
'''
from random import random
import sys
import os
###sys.path.appen... | 3,186 | 30.87 | 95 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_guessability.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.10
Description:
split the agent into two different agent
P1: just generate the sequence but not the guess
P2: ... | 14,432 | 40.474138 | 152 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_example_multicore.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
Author: Mulong Luo
Date: 2022.7.11
Function: An example rllib training script
'''
from random import random
import sys
import os
###sys.path.appen... | 3,184 | 30.85 | 95 | py |
AutoCAT | AutoCAT-main/src/rllib/run_gym_rllib_simd.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
'''
CacheSimulatorSIMDWrapper
wraps multiple environment with different initialization into a single env
'''
#from msilib.schema import DuplicateFile
... | 9,661 | 40.114894 | 134 | py |
AutoCAT | AutoCAT-main/src/rlmeta/sample_cchunter.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
import os
import sys
from typing import Dict, Optional, Sequence, Union
import hydra
from omegaconf import DictConfig, OmegaConf
imp... | 5,516 | 28.821622 | 79 | py |
AutoCAT | AutoCAT-main/src/rlmeta/sample_cchunter_textbook.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
import os
import sys
from typing import Dict, Optional, Sequence, Union
import hydra
from omegaconf import DictConfig, OmegaConf
imp... | 5,675 | 29.191489 | 81 | py |
AutoCAT | AutoCAT-main/src/rlmeta/train_ppo_cchunter.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import copy
import logging
import os
import time
import hydra
from omegaconf import DictConfig, OmegaConf
import torch
import torch.multiprocessing ... | 5,617 | 36.205298 | 77 | py |
AutoCAT | AutoCAT-main/src/rlmeta/sample_attack.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
from typing import Dict, Optional
import hydra
from omegaconf import DictConfig, OmegaConf
import torch
import torch.nn
import rlme... | 3,914 | 28.659091 | 79 | py |
AutoCAT | AutoCAT-main/src/rlmeta/cache_ppo_mlp_model.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import sys
from typing import Dict, List, Tuple
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import rlm... | 2,350 | 30.77027 | 78 | py |
AutoCAT | AutoCAT-main/src/rlmeta/model_utils.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from typing import Any, Dict, Optional
import torch
import torch.nn as nn
from cache_ppo_mlp_model import CachePPOMlpModel
from cache_ppo_lstm_model... | 1,126 | 28.657895 | 73 | py |
AutoCAT | AutoCAT-main/src/rlmeta/plot_cchunter.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# script for plotting figure on paper
import logging
from typing import Dict
#import hydra
#import torch
#import torch.nn
import os
import sys
sys... | 36,087 | 21.153468 | 461 | py |
AutoCAT | AutoCAT-main/src/rlmeta/train_ppo_attack.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import copy
import logging
import os
import time
import hydra
from omegaconf import DictConfig, OmegaConf
import torch
import torch.multiprocessing ... | 5,600 | 36.34 | 77 | py |
AutoCAT | AutoCAT-main/src/rlmeta/cache_ppo_transformer_model.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import sys
from typing import Dict, List, Tuple
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import rlm... | 4,143 | 34.118644 | 78 | py |
AutoCAT | AutoCAT-main/src/rlmeta/sample_cyclone.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
from typing import Dict, Optional, Sequence
import hydra
from omegaconf import DictConfig, OmegaConf
import numpy as np
import torc... | 4,357 | 28.053333 | 79 | py |
AutoCAT | AutoCAT-main/src/rlmeta/train_ppo_cyclone.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import copy
import logging
import os
import time
import hydra
from omegaconf import DictConfig, OmegaConf
import torch
import torch.multiprocessing ... | 5,612 | 36.172185 | 77 | py |
AutoCAT | AutoCAT-main/src/rlmeta/sample_cyclone_textbook.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import logging
import os
import sys
from typing import Dict, Optional, Sequence, Union
import hydra
from omegaconf import DictConfig, OmegaConf
imp... | 5,143 | 26.508021 | 80 | py |
AutoCAT | AutoCAT-main/src/rlmeta/cache_ppo_lstm_model.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import sys
from typing import Dict, List, Tuple
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import rlm... | 4,131 | 32.322581 | 78 | py |
AutoCAT | AutoCAT-main/src/rlmeta/cyclone_svm_trainer.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Author: Mulong Luo
# date: 2022.6.28
# usage: to train the svm classifier of cycloen by feeding
# the date from TextbookAgent as malicious traces
... | 8,416 | 35.437229 | 140 | py |
second.pytorch | second.pytorch-master/second/script_server.py | from second.pytorch.train import train, evaluate
from google.protobuf import text_format
from second.protos import pipeline_pb2
from pathlib import Path
from second.utils import config_tool, model_tool
import datetime
from second.data.all_dataset import get_dataset_class
def _div_up(a, b):
return (a + b - 1) // b
... | 9,949 | 42.832599 | 100 | py |
second.pytorch | second.pytorch-master/second/script.py | from second.pytorch.train import train, evaluate
from google.protobuf import text_format
from second.protos import pipeline_pb2
from pathlib import Path
from second.utils import config_tool
def train_multi_rpn_layer_num():
config_path = "./configs/car.lite.config"
model_root = Path.home() / "second_test" # d... | 1,594 | 32.93617 | 76 | py |
second.pytorch | second.pytorch-master/second/kittiviewer/viewer.py | import io as sysio
import json
import os
import pickle
import sys
import time
from functools import partial
from pathlib import Path
import datetime
import fire
import matplotlib.pyplot as plt
import numba
import numpy as np
import OpenGL.GL as pygl
import pyqtgraph.opengl as gl
import skimage
from matplotlib.backends.... | 68,112 | 41.838365 | 120 | py |
second.pytorch | second.pytorch-master/second/kittiviewer/backend/main.py | """This backend now only support lidar. camera is no longer supported.
"""
import base64
import datetime
import io as sysio
import json
import pickle
import time
from pathlib import Path
import fire
import torch
import numpy as np
import skimage
from flask import Flask, jsonify, request
from flask_cors import CORS
fr... | 8,121 | 34.313043 | 118 | py |
second.pytorch | second.pytorch-master/second/data/dataset.py | import pathlib
import pickle
import time
from functools import partial
import numpy as np
from second.core import box_np_ops
from second.core import preprocess as prep
from second.data import kitti_common as kitti
REGISTERED_DATASET_CLASSES = {}
def register_dataset(cls, name=None):
global REGISTERED_DATASET_CL... | 3,922 | 33.716814 | 95 | py |
second.pytorch | second.pytorch-master/second/pytorch/inference.py | from pathlib import Path
import numpy as np
import torch
import torchplus
from second.core import box_np_ops
from second.core.inference import InferenceContext
from second.builder import target_assigner_builder, voxel_builder
from second.pytorch.builder import box_coder_builder, second_builder
from second.pytorch.mod... | 3,452 | 39.623529 | 92 | py |
second.pytorch | second.pytorch-master/second/pytorch/train.py | import copy
import json
import os
from pathlib import Path
import pickle
import shutil
import time
import re
import fire
import numpy as np
import torch
from google.protobuf import text_format
import second.data.kitti_common as kitti
import torchplus
from second.builder import target_assigner_builder, voxel_builder
f... | 26,138 | 38.365964 | 117 | py |
second.pytorch | second.pytorch-master/second/pytorch/core/ghm_loss.py | #####################
# THIS LOSS IS NOT WORKING!!!!
#####################
"""
The implementation of GHM-C and GHM-R losses.
Details can be found in the paper `Gradient Harmonized Single-stage Detector`:
https://arxiv.org/abs/1811.05181
Copyright (c) 2018 Multimedia Laboratory, CUHK.
Licensed under the MIT License (se... | 5,148 | 39.226563 | 104 | py |
second.pytorch | second.pytorch-master/second/pytorch/core/losses.py | """Classification and regression loss functions for object detection.
Localization losses:
* WeightedL2LocalizationLoss
* WeightedSmoothL1LocalizationLoss
Classification losses:
* WeightedSigmoidClassificationLoss
* WeightedSoftmaxClassificationLoss
* BootstrappedSigmoidClassificationLoss
"""
from abc import ABC... | 18,114 | 38.988962 | 101 | py |
second.pytorch | second.pytorch-master/second/pytorch/core/box_torch_ops.py | import math
from functools import reduce
import numpy as np
import torch
from torch import stack as tstack
import torchplus
from torchplus.tools import torch_to_np_dtype
from second.core.non_max_suppression.nms_gpu import (nms_gpu_cc, rotate_iou_gpu,
rotate_nms_g... | 18,421 | 34.70155 | 101 | py |
second.pytorch | second.pytorch-master/second/pytorch/core/box_coders.py | import torch
from second.core.box_coders import BevBoxCoder, GroundBox3dCoder
from second.pytorch.core import box_torch_ops
class GroundBox3dCoderTorch(GroundBox3dCoder):
def encode_torch(self, boxes, anchors):
return box_torch_ops.second_box_encode(boxes, anchors, self.vec_encode,
... | 1,598 | 40 | 79 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/voxelnet.py | import time
from enum import Enum
from functools import reduce
import contextlib
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
import torchplus
from second.pytorch.core import box_torch_ops
from second.pytorch.core.losses import (WeightedSigmoidClassificationLoss,
... | 37,009 | 43.64415 | 119 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/resnet.py | import spconv
from torch import nn
from torch.nn import functional as F
from torchplus.nn import Empty, GroupNorm, Sequential
def conv3x3(in_planes, out_planes, stride=1, indice_key=None):
"""3x3 convolution with padding"""
return spconv.SubMConv3d(
in_planes,
out_planes,
kernel_size=... | 3,059 | 26.567568 | 77 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/middle.py | import time
import numpy as np
import spconv
import torch
from torch import nn
from torch.nn import functional as F
from second.pytorch.models.resnet import SparseBasicBlock
from torchplus.nn import Empty, GroupNorm, Sequential
from torchplus.ops.array_ops import gather_nd, scatter_nd
from torchplus.tools import chan... | 25,183 | 38.166407 | 100 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/rpn.py | import time
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet
from torchplus.nn import Empty, GroupNorm, Sequential
from torchplus.tools import change_default_args
REGISTERED_RPN_CLASSES = {}
def register_rpn(cls, name=None):
global R... | 20,512 | 37.703774 | 87 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/net_multi_head.py | import time
from enum import Enum
from functools import reduce
import contextlib
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from second.pytorch.models.voxelnet import register_voxelnet, VoxelNet
from second.pytorch.models import rpn
class SmallObjectHead(nn.Module):
... | 8,065 | 44.570621 | 120 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/pointpillars.py | """
PointPillars fork from SECOND.
Code written by Alex Lang and Oscar Beijbom, 2018.
Licensed under MIT License [see LICENSE].
"""
import torch
from torch import nn
from torch.nn import functional as F
from second.pytorch.models.voxel_encoder import get_paddings_indicator, register_vfe
from second.pytorch.models.mid... | 19,857 | 40.631027 | 117 | py |
second.pytorch | second.pytorch-master/second/pytorch/models/voxel_encoder.py | import time
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchplus.nn import Empty, GroupNorm, Sequential
from torchplus.tools import change_default_args
REGISTERED_VFE_CLASSES = {}
def register_vfe(cls, name=None):
global REGISTERED_VFE_CLASSES
if name is N... | 10,090 | 38.417969 | 87 | py |
second.pytorch | second.pytorch-master/second/pytorch/builder/lr_scheduler_builder.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 3,518 | 36.83871 | 118 | py |
second.pytorch | second.pytorch-master/second/pytorch/builder/input_reader_builder.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 2,448 | 30 | 80 | py |
second.pytorch | second.pytorch-master/second/pytorch/builder/box_coder_builder.py | import numpy as np
from second.protos import box_coder_pb2
from second.pytorch.core.box_coders import (BevBoxCoderTorch,
GroundBox3dCoderTorch)
def build(box_coder_config):
"""Create optimizer based on config.
Args:
optimizer_config: A Optimizer proto me... | 969 | 32.448276 | 98 | py |
second.pytorch | second.pytorch-master/second/pytorch/builder/second_builder.py | # Copyright 2017 yanyan. 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 or agree... | 6,589 | 48.179104 | 89 | py |
second.pytorch | second.pytorch-master/second/pytorch/builder/optimizer_builder.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 3,431 | 33.32 | 110 | py |
second.pytorch | second.pytorch-master/second/pytorch/builder/losses_builder.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 6,226 | 31.602094 | 80 | py |
second.pytorch | second.pytorch-master/second/pytorch/utils/__init__.py | import time
import contextlib
import torch
@contextlib.contextmanager
def torch_timer(name=''):
torch.cuda.synchronize()
t = time.time()
yield
torch.cuda.synchronize()
print(name, "time:", time.time() - t) | 229 | 19.909091 | 41 | py |
second.pytorch | second.pytorch-master/torchplus/tools.py | import functools
import inspect
import sys
from collections import OrderedDict
import numba
import numpy as np
import torch
def get_pos_to_kw_map(func):
pos_to_kw = {}
fsig = inspect.signature(func)
pos = 0
for name, info in fsig.parameters.items():
if info.kind is info.POSITIONAL_OR_KEYWORD:... | 1,607 | 27.210526 | 70 | py |
second.pytorch | second.pytorch-master/torchplus/metrics.py | import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class Scalar(nn.Module):
def __init__(self):
super().__init__()
self.register_buffer('total', torch.FloatTensor([0.0]))
self.register_buffer('count', torch.FloatTensor([0.0]))
def forward(self, scalar... | 10,431 | 35.992908 | 80 | py |
second.pytorch | second.pytorch-master/torchplus/__init__.py | from . import train
from . import nn
from . import metrics
from . import tools
from .tools import change_default_args
from torchplus.ops.array_ops import scatter_nd, gather_nd
| 177 | 21.25 | 57 | py |
second.pytorch | second.pytorch-master/torchplus/nn/functional.py | import torch
def one_hot(tensor, depth, dim=-1, on_value=1.0, dtype=torch.float32):
tensor_onehot = torch.zeros(
*list(tensor.shape), depth, dtype=dtype, device=tensor.device)
tensor_onehot.scatter_(dim, tensor.unsqueeze(dim).long(), on_value)
return tensor_onehot
| 286 | 34.875 | 71 | py |
second.pytorch | second.pytorch-master/torchplus/nn/__init__.py | from torchplus.nn.functional import one_hot
from torchplus.nn.modules.common import Empty, Sequential
from torchplus.nn.modules.normalization import GroupNorm
| 159 | 39 | 57 | py |
second.pytorch | second.pytorch-master/torchplus/nn/modules/common.py | import sys
from collections import OrderedDict
import torch
from torch.nn import functional as F
class Empty(torch.nn.Module):
def __init__(self, *args, **kwargs):
super(Empty, self).__init__()
def forward(self, *args, **kwargs):
if len(args) == 1:
return args[0]
elif len(... | 2,880 | 30.659341 | 80 | py |
second.pytorch | second.pytorch-master/torchplus/nn/modules/normalization.py | import torch
class GroupNorm(torch.nn.GroupNorm):
def __init__(self, num_channels, num_groups, eps=1e-5, affine=True):
super().__init__(
num_groups=num_groups,
num_channels=num_channels,
eps=eps,
affine=affine)
| 273 | 23.909091 | 72 | py |
second.pytorch | second.pytorch-master/torchplus/train/checkpoint.py | import json
import logging
import os
import signal
from pathlib import Path
import torch
class DelayedKeyboardInterrupt(object):
def __enter__(self):
self.signal_received = False
self.old_handler = signal.signal(signal.SIGINT, self.handler)
def handler(self, sig, frame):
self.signal_... | 6,655 | 36.60452 | 79 | py |
second.pytorch | second.pytorch-master/torchplus/train/optim.py | from collections import defaultdict, Iterable
import torch
from copy import deepcopy
from itertools import chain
from torch.autograd import Variable
required = object()
def param_fp32_copy(params):
param_copy = [
param.clone().type(torch.cuda.FloatTensor).detach() for param in params
]
for param ... | 4,081 | 35.774775 | 87 | py |
second.pytorch | second.pytorch-master/torchplus/train/fastai_optim.py | from collections import Iterable, defaultdict
from copy import deepcopy
from itertools import chain
import torch
from torch import nn
from torch._utils import _unflatten_dense_tensors
from torch.autograd import Variable
from torch.nn.utils import parameters_to_vector
bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.Bat... | 11,480 | 34.65528 | 108 | py |
second.pytorch | second.pytorch-master/torchplus/train/learning_schedules.py | """PyTorch edition of TensorFlow learning schedule in tensorflow object
detection API.
"""
import numpy as np
from torch.optim.optimizer import Optimizer
class _LRSchedulerStep(object):
def __init__(self, optimizer, last_step=-1):
if not isinstance(optimizer, Optimizer):
raise TypeError('{} is ... | 7,996 | 35.35 | 79 | py |
second.pytorch | second.pytorch-master/torchplus/train/learning_schedules_fastai.py | import numpy as np
import math
from functools import partial
import torch
class LRSchedulerStep(object):
def __init__(self, fai_optimizer, total_step, lr_phases, mom_phases):
self.optimizer = fai_optimizer
self.total_step = total_step
self.lr_phases = []
for i, (start, lambda_func... | 5,671 | 35.127389 | 79 | py |
second.pytorch | second.pytorch-master/torchplus/train/__init__.py | from torchplus.train.checkpoint import (latest_checkpoint, restore,
restore_latest_checkpoints,
restore_models, save, save_models,
try_restore_latest_checkpoints)
from torchplus.train.common import cr... | 388 | 54.571429 | 74 | py |
second.pytorch | second.pytorch-master/torchplus/ops/array_ops.py | import ctypes
import math
import time
import torch
def scatter_nd(indices, updates, shape):
"""pytorch edition of tensorflow scatter_nd.
this function don't contain except handle code. so use this carefully
when indice repeats, don't support repeat add which is supported
in tensorflow.
"""
ret... | 1,061 | 33.258065 | 84 | py |
SPTM | SPTM-master/src/common/register_test_setups.py | DATA_PATH = '../../data/'
class TestSetup:
def __init__(self,
dir,
wad,
memory_buffer_lmp,
goal_lmps,
maps,
exploration_map,
goal_locations,
goal_names,
box):
self.wad = DATA_PAT... | 13,019 | 39.560748 | 69 | py |
SPTM | SPTM-master/src/common/resnet.py | #!/usr/bin/env python
#taken from https://github.com/raghakot/keras-resnet/blob/master/resnet.py
from __future__ import division
import six
from keras.models import Model
from keras.layers import (
Input,
Activation,
Dense,
Flatten
)
from keras.layers.core import Lambda
from keras.layers.merge import ... | 13,060 | 38.459215 | 109 | py |
SPTM | SPTM-master/src/common/util.py | #!/usr/bin/env python
import cPickle
import cv2
import numpy as np
import h5py
from vizdoom import *
import math
import os
import os.path
import sys
import random
import scipy.misc
from constants import *
from video_writer import *
import cv2
import os
import cPickle
import numpy as np
np.random.seed(DEFAULT_RANDOM_S... | 7,338 | 32.976852 | 95 | py |
SPTM | SPTM-master/src/test/test_setup.py | import sys
sys.path.append('..')
from common import *
from vizdoom import *
import cv2
import numpy as np
np.random.seed(TEST_RANDOM_SEED)
import keras
import random
random.seed(TEST_RANDOM_SEED)
def test_setup(wad):
game = doom_navigation_setup(TEST_RANDOM_SEED, wad)
wait_idle(game, WAIT_BEFORE_START_TICS)
retu... | 570 | 23.826087 | 73 | py |
SPTM | SPTM-master/src/test/navigator.py | from sptm import *
def check_if_close(first_point, second_point):
if ((first_point[0] - second_point[0]) ** 2 +
(first_point[1] - second_point[1]) ** 2 <= GOAL_DISTANCE_ALLOWANCE ** 2):
return True
else:
return False
class Navigator:
def __init__(self, exploration_model_directory):
self.explor... | 8,430 | 38.397196 | 161 | py |
SPTM | SPTM-master/src/test/sptm.py | from test_setup import *
import os.path
from numpy import mean
from numpy import median
import networkx as nx
from trajectory_plotter import *
def load_keras_model(number_of_input_frames, number_of_actions, path, load_method=resnet.ResnetBuilder.build_resnet_18):
result = load_method((number_of_input_frames * NET_... | 15,363 | 42.036415 | 158 | py |
SPTM | SPTM-master/src/train/resave_weights.py | from train_setup import *
# necessary because of keras issues
# with loading more than one model at the same time
if __name__ == '__main__':
if sys.argv[1] == 'action':
model = keras.models.load_model(ACTION_MODEL_PATH)
model.save_weights(ACTION_MODEL_WEIGHTS_PATH)
elif sys.argv[1] == 'edge':
model = k... | 460 | 31.928571 | 54 | py |
SPTM | SPTM-master/src/train/train_edge_predictor.py | from train_setup import *
def data_generator():
game = doom_navigation_setup(DEFAULT_RANDOM_SEED, TRAIN_WAD)
while True:
x_result = []
y_result = []
for episode in xrange(EDGE_EPISODES):
game.set_doom_map(MAP_NAME_TEMPLATE % random.randint(MIN_RANDOM_TEXTURE_MAP_INDEX,
... | 3,720 | 45.5125 | 110 | py |
SPTM | SPTM-master/src/train/train_action_predictor.py | from train_setup import *
def data_generator():
game = doom_navigation_setup(DEFAULT_RANDOM_SEED, TRAIN_WAD)
game.set_doom_map(MAP_NAME_TEMPLATE % random.randint(MIN_RANDOM_TEXTURE_MAP_INDEX,
MAX_RANDOM_TEXTURE_MAP_INDEX))
game.new_episode()
yield_count = ... | 2,813 | 42.292308 | 116 | py |
SPTM | SPTM-master/src/train/train_setup.py | import sys
sys.path.append('..')
from common import *
# limit memory usage
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = TRAIN_MEMORY_FRACTION
set_session(tf.Session(config=config))
def setup_training_pat... | 796 | 35.227273 | 103 | py |
AGES | AGES-master/resnet.py | import torch
import torch.nn as nn
from torch.hub import load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'res... | 10,067 | 35.478261 | 106 | py |
AGES | AGES-master/bgm.py | from sagan import *
import torchvision.models as models
from resnet import *
import torch.nn.init as init
class ResEncoder(nn.Module):
r'''ResNet Encoder
Args:
latent_dim: latent dimension
arch: network architecture. Choices: resnet - resnet50, resnet18
dist: encoder distribution. Cho... | 20,262 | 37.376894 | 127 | py |
AGES | AGES-master/utils.py | import numpy as np
import os
import torch
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import TensorDataset, DataLoader
def draw_recon(x, x_recon):
x_l, x_recon_l = x.tolist(), x_recon.tolist()
result = [None] * (len(x_l) + len(x_recon_l))
result[::2] ... | 4,189 | 40.078431 | 121 | py |
AGES | AGES-master/sagan.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import spectral_norm
from torch.nn.init import orthogonal_
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d:
orthogonal_(m.weight)
m.bias.... | 15,117 | 35.254197 | 137 | py |
AGES | AGES-master/train.py | import sys
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
from torch.utils.data import TensorDataset, DataLoader
import argparse
import matplotlib.pyplot as plt
from bgm import *... | 14,270 | 40.485465 | 120 | py |
submodlib | submodlib-master/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 2,861 | 30.450549 | 79 | py |
grabnel | grabnel-master/src/train_model.py | """Code to train a graph classifier model.
To be used to train any model except for the GraphUNet in the paper.
See train_gunet.py for the script to train Graph UNet.
"""
import argparse
import os
from copy import deepcopy
from os.path import join
import pandas as pd
import torch
import torch.optim as optim
from atta... | 4,358 | 37.236842 | 116 | py |
grabnel | grabnel-master/src/train_gunet.py | import sys
sys.path.append('../')
sys.path.append('./src/models/gunet')
import argparse
import random
import time
import torch
import numpy as np
from src.models.gunet.network import GNet
from src.models.gunet.trainer import Trainer
from src.models.gunet.utils.data_loader import FileLoader
from src.models.gunet.config... | 1,909 | 31.372881 | 102 | py |
grabnel | grabnel-master/src/evaluate_model.py | """Code to evaluate a graph classifier model."""
import argparse
import os
from os.path import join
import pandas as pd
import torch
from attack.data import Data, ERData
from attack.utils import (classification_loss, correct_predictions,
get_dataset_split, get_device, setseed)
from models.ut... | 4,450 | 39.463636 | 124 | py |
grabnel | grabnel-master/src/attack/genetic.py | """Genetic algorithm attack."""
from copy import deepcopy
import dgl
import numpy as np
import pandas as pd
import scipy
import torch
from .base_attack import BaseAttack
from .utils import correct_predictions, population_graphs, random_sample_flip, random_sample_rewire_swap, get_allowed_nodes_k_hop, extrapolate_break... | 14,484 | 49.121107 | 152 | py |
grabnel | grabnel-master/src/attack/randomattack.py | """Random attack."""
from copy import deepcopy
import dgl
import numpy as np
import pandas as pd
import torch
from .base_attack import BaseAttack
from .utils import correct_predictions, random_sample_rewire_swap, random_sample_flip, population_graphs, extrapolate_breakeven
class RandomFlip(BaseAttack):
def __i... | 4,924 | 49.255102 | 157 | py |
grabnel | grabnel-master/src/attack/base_attack.py | import dgl
import pandas as pd
import torch
class BaseAttack:
def __init__(self, classifier, loss_fn):
"""Base adversarial attack model
Args:
classifier: The pytorch classifier to attack.
loss_fn: The loss function, this will be maximised by an attacker.
"""
... | 1,290 | 35.885714 | 118 | py |
grabnel | grabnel-master/src/attack/utils.py | import random
import dgl
import networkx as nx
import numpy as np
import torch
import torch.nn as nn
from copy import deepcopy
def find_n_hop_neighbour(graph: dgl.DGLGraph, node_idx: int, n_hop: int, undirected=True,
exclude_self=True) -> torch.Tensor:
"""
Given a node index, finds i... | 19,512 | 41.144708 | 124 | py |
grabnel | grabnel-master/src/attack/data.py | """
Using the convention of having an a, b, c dataset used in ReWatt.
Dataset a is used for training a model, the method training_dataloaders returns two dataloaders created by splitting
dataset a. The first dataloader is for training and the other for validation
Dataset b is used for training the adversarial attack ... | 14,300 | 43.551402 | 119 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.