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 |
|---|---|---|---|---|---|---|
TapNet | TapNet-master/miniImageNet_TapNet/utils/model_TapNet_ResNet12.py | import cupy as cp
import numpy as np
import chainer
import chainer.links as L
import chainer.functions as F
from chainer import cuda
from utils.rank_nullspace import nullspace_gpu
class TapNet(object):
def __init__(self, nb_class_train, nb_class_test, input_size, dimension,
n_shot, gpu=-1):
... | 12,091 | 34.253644 | 123 | py |
TapNet | TapNet-master/miniImageNet_TapNet/data/__init__.py | 1 | 0 | 0 | py | |
acl-anthology-helper | acl-anthology-helper-master/toy.py | 0 | 0 | 0 | py | |
acl-anthology-helper | acl-anthology-helper-master/src/__init__.py | 0 | 0 | 0 | py | |
acl-anthology-helper | acl-anthology-helper-master/src/modules/anthology_sqlite.py | """
@Reference"
使用SQLite
https://www.liaoxuefeng.com/wiki/1016959663602400/1017801751919456
Python自带的Sqlite支持shell命令行交互模式吗?
https://www.zhihu.com/question/62897833/answer/559922232
"""
import os
import sqlite3
from logging import DEBUG
from src.modules.retriever import Retriever
from src.modules.logger import MyLogger
... | 3,073 | 32.78022 | 108 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/papers.py | """
@Desc:
"""
from tqdm import tqdm
import requests
from bs4 import BeautifulSoup as Soup
from .logger import MyLogger
from src.common.string_tools import StringTools
class Paper(object):
def __init__(self, title, year, url, authors=[], abstrat="", conf_content="", venue=""):
self.title = title
s... | 7,445 | 36.606061 | 110 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/retriever.py | """
@Desc:
"""
import requests
from logging import DEBUG
from src.modules.constants import CACHE_DIR
from src.modules.conferences import Anthology
from src.modules.papers import PaperList
from src.modules.statistics import Statistics as stats
from src.modules.statistics import Stat
from src.modules.logger import MyLog... | 3,827 | 38.463918 | 108 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/constants.py | """
@Desc:
"""
CACHE_DIR = './cache'
class DBConsts(object):
ANTHOLOGY_DB = 'anthology.db'
CONF_TABLE = 'conference'
PAPER_TABLE = 'paper'
class ConfConsts(object):
ACL_EVENTS = "ACL Events"
NON_ACL_EVENTS = "NON-ACL Events"
| 249 | 14.625 | 37 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/parallel_downloader.py | """
@reference:
Python 3 爬虫|第4章:多进程并发下载
https://madmalls.com/blog/post/multi-process-for-python3/
并行有诸多限制:
1.设计并行下载类的时候不能引入带锁的东西(如logging)
2.如果子任务报异常需要设计处理handler
"""
from logging import Logger, DEBUG
import os
import requests
from src.modules.logger import MyLogger
from src.modules.papers import Paper, PaperList
from... | 2,153 | 36.789474 | 89 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/downloader.py | """
@reference:
python下载文件的三种方法
https://www.jianshu.com/p/e137b03a1cd2
"""
from logging import DEBUG
import os
import requests
from tqdm import tqdm
from src.modules.logger import MyLogger
from src.modules.papers import Paper, PaperList
from src.common.string_tools import StringTools
from src.common.file_tools import ... | 2,540 | 34.291667 | 106 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/logger.py | """
@Desc:
Rrinting log to both screen and files.
@Reference:
https://xnathan.com/2017/03/09/logging-output-to-screen-and-file/
"""
import logging
import os
from logging import Logger
from logging import NOTSET
class MyLogger(Logger):
def __init__(self, name, level=NOTSET, log_path=''):
super(MyLogger, s... | 1,479 | 29.204082 | 129 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/conferences.py | """
@Desc:
"""
import requests
import json
import itertools
from tqdm import tqdm
from bs4 import BeautifulSoup as Soup
from .logger import MyLogger
from .constants import ConfConsts
from src.common.serialization_tools import MyEncoder
class Conference(object):
def __init__(self, name, label, link):
self.... | 5,098 | 32.993333 | 117 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/anthology_mysql.py | """
@Reference:
"""
import os
import itertools
import pymysql
from tqdm import tqdm
from logging import DEBUG
from src.modules.constants import CACHE_DIR
from src.modules.retriever import Retriever
from src.modules.logger import MyLogger
from src.modules.constants import DBConsts
from src.configuration.mysql_cfg impor... | 6,803 | 40.487805 | 117 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/statistics.py | """
@Desc:
"""
import json
class Stat(object):
def __init__(self, name):
self.name = name
self._attrs = dict() # collect anything needed
def attrs(self):
return self._attrs
def add_attr(self, key, val):
self._attrs[key] = val
return self
def __repr__(self):
... | 1,006 | 20.891304 | 55 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/cache.py | """
@reference:
python dict 保存为pickle格式
https://blog.csdn.net/rosefun96/article/details/90633786
"""
import os
import pickle
import json
from logging import DEBUG
from src.modules.logger import MyLogger
class Cache(object):
def __init__(self, name, local_dir='./cache', logger=None):
self._name = name
... | 3,280 | 29.663551 | 99 | py |
acl-anthology-helper | acl-anthology-helper-master/src/modules/__init__.py | from .constants import *
from .retriever import Retriever | 57 | 28 | 32 | py |
acl-anthology-helper | acl-anthology-helper-master/src/common/database_tools.py | from src.modules.papers import Paper, PaperList
class MySQLTools(object):
@classmethod
def dict_to_paper(cls, result: dict):
paper = Paper(
title=result['title'],
year=result['year'],
url=result['url'],
authors=result['authors'].split(', '),
a... | 671 | 28.217391 | 53 | py |
acl-anthology-helper | acl-anthology-helper-master/src/common/string_tools.py | class StringTools(object):
@classmethod
def match(cls, one: str, two: str):
return one.lower() == two.lower()
@classmethod
def contain(cls, text: str, keyword: str):
return keyword.lower() in text.lower()
@classmethod
def multi_or_contain(cls, text: str, keywords: list):
... | 1,121 | 27.769231 | 92 | py |
acl-anthology-helper | acl-anthology-helper-master/src/common/file_tools.py | import os
class FileTools(object):
@classmethod
def info_to_file(cls, info, local_path: str):
with open(local_path, 'w', encoding='utf-8') as fw:
fw.write(f'{info}')
| 195 | 23.5 | 59 | py |
acl-anthology-helper | acl-anthology-helper-master/src/common/__init__.py | 0 | 0 | 0 | py | |
acl-anthology-helper | acl-anthology-helper-master/src/common/serialization_tools.py | """
@Reference:
https://blog.csdn.net/dou_being/article/details/82290588
https://blog.csdn.net/zywvvd/article/details/106131555
"""
import json
class MyEncoder(json.JSONEncoder):
def default(self, obj):
"""
只要检查到了是bytes类型的数据就把它转为str类型
:param obj:
:return:
"""
try:
... | 434 | 19.714286 | 56 | py |
acl-anthology-helper | acl-anthology-helper-master/tasks/search_paper.py | """
@Desc:
@Reference:
https://github.com/lizhenggan/ABuilder
pip install a-sqlbuilder
"""
import sys
sys.path.insert(0, '') # 在tasks文件夹中可以直接运行程序
from typing import List
import os
from ABuilder.ABuilder import ABuilder
from src.modules.downloader import PaperDownloader
from src.common.file_tools import FileTools
fr... | 1,606 | 28.759259 | 102 | py |
acl-anthology-helper | acl-anthology-helper-master/tasks/database.py | from src.configuration.mysql_cfg import MySQLCFG
class Config(object):
pass
class Proconfig(Config):
pass
class Devconfig(Config):
debug = True
DATABASE_URI = f'mysql+pymysql://{MySQLCFG.USER}:{MySQLCFG.USER}@{MySQLCFG.HOST}:{MySQLCFG.PORT}/{MySQLCFG.DB}'
data_host = MySQLCFG.HOST
data_pass ... | 476 | 18.875 | 115 | py |
acl-anthology-helper | acl-anthology-helper-master/tasks/parallel_download_task.py | """
@Desc:
"""
import sys
sys.path.insert(0, '..') # 在tasks文件夹中可以直接运行程序
import os
from src.modules import Retriever
from src.modules.parallel_downloader import PaperDownloader
class ParallelDownloadTask(object):
@classmethod
def acl_long_download(cls, keyword: str):
conf_content = '2021-acl-long'
... | 1,830 | 33.54717 | 109 | py |
acl-anthology-helper | acl-anthology-helper-master/tasks/basic_task.py | """
@Desc:
@Reference:
https://github.com/lizhenggan/ABuilder
"""
import sys
sys.path.insert(0, '..') # 在tasks文件夹中可以直接运行程序
import os
from ABuilder.ABuilder import ABuilder
from src.modules.downloader import PaperDownloader
from src.modules.papers import Paper, PaperList
from src.modules.anthology_mysql import Antholog... | 2,072 | 29.485294 | 109 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/compare_rnn.py | import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm
from tensorboard.backend.event_processing import event_accumulator
def read_data(load_dir, tag="perf/avg_reward_100"):
events = os.listdir(load_dir)
for event in events:
pat... | 2,697 | 31.506024 | 90 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/viz_featmaps.py | import numpy as np
import matplotlib.pyplot as plt
path = "featmaps/featmaps_7500_5.npy"
featmaps = np.load(path)
rand_idxs = np.random.randint(0,featmaps.shape[1], 5)
for idx in rand_idxs:
featmap = featmaps[0,idx,:,:]
plt.imshow(featmap*0.5+0.5, cmap='gray')
plt.show()
| 289 | 21.307692 | 53 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/main_1d.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from collections import namedtuple
from common.shared_optim import SharedAdam, SharedRMSprop
from ... | 3,414 | 30.915888 | 113 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/plot_training_curve.py | import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm
from tensorboard.backend.event_processing import event_accumulator
def read_data(load_dir, tag="perf/avg_reward_100"):
events = os.listdir(load_dir)
for event in events:
pat... | 1,875 | 26.588235 | 90 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/vis_simple.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from datetime import datetime
from collections import namedtuple
from Harlow_Simple.harlow impo... | 1,850 | 25.826087 | 117 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/plot.py | import os
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
all_rewards = []
base_path = "ckpt"
run_title = "Harlow_Final_LSTM"
n_seeds = 8
n_workers = 8
for seed in range(1, n_seeds+1):
run = run_title + f"_{seed}"
run_rewards = []
for wor... | 1,354 | 29.795455 | 90 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/main_psychlab.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from collections import namedtuple
from common.shared_optim import SharedAdam, SharedRMSprop
from ... | 6,521 | 37.591716 | 114 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/run_episode.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
import deepmind_lab as lab
from tqdm import tqdm
from collections import namedtuple
fr... | 5,563 | 35.605263 | 127 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/main_psychlab_single.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
import deepmind_lab as lab
from tqdm import tqdm
from collections import namedtuple
fr... | 14,014 | 36.573727 | 114 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/pretrain/evaluate.py | import torch as T
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
from utils import get_test_loader
model_urls = {
'cifar10': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar10-d875770b.pth',
'cifar100': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytor... | 3,243 | 36.287356 | 122 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/pretrain/utils.py | """
Create train, valid, test iterators for CIFAR-10 [1].
Easily extended to MNIST, CIFAR-100 and Imagenet.
[1]: https://discuss.pytorch.org/t/feedback-on-pytorch-for-kaggle-competitions/2252/4
"""
import torch
import imageio
import numpy as np
import matplotlib.pyplot as plt
from torchvision import datasets
from to... | 5,546 | 29.646409 | 85 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/pretrain/train.py | import os
import yaml
import argparse
import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
from copy import deepcopy
from torch.utils.tensorboard import SummaryWriter
from utils import get_trai... | 5,955 | 32.088889 | 160 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/common/shared_optim.py | import math
import torch as T
import torch.optim as optim
class SharedAdam(optim.Adam):
"""Implements Adam algorithm with shared states.
"""
def __init__(self,
params,
lr=1e-3,
betas=(0.9, 0.999),
eps=1e-8,
weight_decay... | 4,680 | 35.286822 | 135 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/Harlow_PsychLab/harlow.py | import os
import imageio
import numpy as np
PIXELS_PER_ACTION = 1
class HarlowWrapper:
"""A gym-like wrapper environment for DeepMind Lab.
Attributes:
env: The corresponding DeepMind Lab environment.
max_length: Maximum number of frames
Args:
env (deepmind_lab.Lab): DeepMind Lab environment.
... | 3,639 | 28.12 | 113 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/Harlow_PsychLab/train.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from datetime import datetime
from collections import namedtuple
import deepmind_lab as lab
f... | 10,760 | 31.315315 | 104 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/dnd.py | import torch as T
import torch.nn.functional as F
# constants
ALL_KERNELS = ['cosine', 'l1', 'l2']
ALL_POLICIES = ['1NN']
class DND:
"""The differentiable neural dictionary (DND) class. This enables episodic
recall in a neural network.
notes:
- a memory is a row vector
Parameters
----------
... | 6,304 | 29.756098 | 98 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/ep_lstm.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from abc import ABC, abstractmethod
from dataclasses import dataclass
import numpy as np
import torch as T
from torch import nn
from torch.nn import functional as F
from torch imp... | 3,780 | 26.398551 | 70 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/ep_lstm_cell.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from dataclasses import dataclass
import numpy as np
import torch as T
from torch import nn
from torch import Tensor
from torch.nn import functional as F
# from models.ep_lstm imp... | 5,570 | 28.47619 | 125 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_conv_lstm.py | import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'cifar10': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar10-d875770b.pth',
'cifar100': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar100-3... | 6,009 | 33.94186 | 104 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_dnd_lstm.py | """
A DND-based LSTM based on ...
Ritter, et al. (2018).
Been There, Done That: Meta-Learning with Episodic Recall.
Proceedings of the International Conference on Machine Learning (ICML).
"""
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from models.dnd import DND
from models.... | 3,612 | 27.448819 | 85 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_lstm_simple.py | import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from models.rgu import RGUnit
CELLS = {
'lstm': nn.LSTM,
'gru': nn.GRU,
'rgu': RGUnit
}
class A3C_LSTM(nn.Module):
def __init__(self, input_dim, hidden_size, num_actions, c... | 3,913 | 29.341085 | 88 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/densenet_lstm.py | import numpy as np
import torch as T
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self, freeze = True):
super(Encoder,self).__init__()
original_model = torchvision.models.densenet161(pretrained=True)
self.features = T.nn.Se... | 2,587 | 31.759494 | 82 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_lstm.py | import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class A3C_LSTM(nn.Module):
def __init__(self, config, num_actions):
super(A3C_LSTM, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, 16, kernel_si... | 3,636 | 33.638095 | 88 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/rgu_cell.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from abc import ABC, abstractmethod
from dataclasses import dataclass
import torch as T
from torch import nn
from torch.nn import functional as F
from torch import Tensor
import p... | 5,418 | 26.93299 | 101 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/rgu.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from abc import ABC, abstractmethod
from dataclasses import dataclass
import numpy as np
import torch as T
from torch import nn
from torch.nn import functional as F
from torch imp... | 3,620 | 25.23913 | 75 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/resnet_lstm.py | import numpy as np
import torch as T
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self):
super(Encoder,self).__init__()
original_model = torchvision.models.resnet18(pretrained=False)
self.features = T.nn.Sequential(*list(or... | 1,788 | 30.385965 | 78 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/Harlow_1D/harlow.py | import os
import sys
import imageio
import numpy as np
import matplotlib.pyplot as plt
"""helpers"""
def _binary2int(binary):
return (binary * 2**np.arange(binary.shape[0]-1, -1, -1)).sum()
def _int2binary(decimal, length=10):
return np.array([int(x) for x in format(decimal, f'#0{length+2}b')[2:]])
class... | 6,298 | 29.138756 | 98 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/Harlow_1D/train.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from datetime import datetime
from collections import namedtuple
from Harlow_1D.harlow import H... | 15,561 | 30.502024 | 108 | py |
FEAT | FEAT-master/pretrain.py | import argparse
import os
import os.path as osp
import shutil
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from model.models.classifier import Classifier
from model.dataloader.samplers import CategoriesSampler
from model.utils import pprint, set_gpu, ensure_path, Averager, Timer,... | 9,931 | 42.946903 | 147 | py |
FEAT | FEAT-master/train_fsl.py | import numpy as np
import torch
from model.trainer.fsl_trainer import FSLTrainer
from model.utils import (
pprint, set_gpu,
get_command_line_parser,
postprocess_args,
)
# from ipdb import launch_ipdb_on_exception
if __name__ == '__main__':
parser = get_command_line_parser()
args = postprocess_args(... | 561 | 20.615385 | 48 | py |
FEAT | FEAT-master/model/data_parallel.py | from torch.nn.parallel import DataParallel
import torch
from torch.nn.parallel._functions import Scatter
from torch.nn.parallel.parallel_apply import parallel_apply
def scatter(inputs, target_gpus, chunk_sizes, dim=0):
r"""
Slices tensors into approximately equal chunks and
distributes them across given GP... | 3,764 | 40.373626 | 84 | py |
FEAT | FEAT-master/model/utils.py | import os
import shutil
import time
import pprint
import torch
import argparse
import numpy as np
def one_hot(indices, depth):
"""
Returns a one-hot tensor.
This is a PyTorch equivalent of Tensorflow's tf.one_hot.
Parameters:
indices: a (n_batch, m) Tensor or (m) Tensor.
depth: a scalar. ... | 7,275 | 38.32973 | 166 | py |
FEAT | FEAT-master/model/logger.py | import json
import os.path as osp
import numpy as np
from collections import defaultdict, OrderedDict
from tensorboardX import SummaryWriter
class ConfigEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, type):
return {'$class': o.__module__ + "." + o.__name__}
elif isins... | 1,621 | 35.863636 | 89 | py |
FEAT | FEAT-master/model/__init__.py | 0 | 0 | 0 | py | |
FEAT | FEAT-master/model/trainer/base.py | import abc
import torch
import os.path as osp
from model.utils import (
ensure_path,
Averager, Timer, count_acc,
compute_confidence_interval,
)
from model.logger import Logger
class Trainer(object, metaclass=abc.ABCMeta):
def __init__(self, args):
self.args = args
# ensure_path(
... | 3,407 | 33.77551 | 103 | py |
FEAT | FEAT-master/model/trainer/fsl_trainer.py | import time
import os.path as osp
import numpy as np
import torch
import torch.nn.functional as F
from model.trainer.base import Trainer
from model.trainer.helpers import (
get_dataloader, prepare_model, prepare_optimizer,
)
from model.utils import (
pprint, ensure_path,
Averager, Timer, count_acc, one_ho... | 7,495 | 35.038462 | 132 | py |
FEAT | FEAT-master/model/trainer/__init__.py | 0 | 0 | 0 | py | |
FEAT | FEAT-master/model/trainer/helpers.py | import torch
import torch.nn as nn
import numpy as np
import torch.optim as optim
from torch.utils.data import DataLoader
from model.dataloader.samplers import CategoriesSampler, RandomSampler, ClassSampler
from model.models.protonet import ProtoNet
from model.models.matchnet import MatchNet
from model.models.feat impo... | 6,374 | 38.351852 | 100 | py |
FEAT | FEAT-master/model/networks/dropblock.py | import torch
import torch.nn.functional as F
from torch import nn
from torch.distributions import Bernoulli
class DropBlock(nn.Module):
def __init__(self, block_size):
super(DropBlock, self).__init__()
self.block_size = block_size
def forward(self, x, gamma):
# shape: (bsize, channel... | 2,392 | 37.596774 | 129 | py |
FEAT | FEAT-master/model/networks/convnet.py | import torch.nn as nn
# Basic ConvNet with Pooling layer
def conv_block(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
nn.MaxPool2d(2)
)
class ConvNet(nn.Module):
def __init__(... | 735 | 23.533333 | 59 | py |
FEAT | FEAT-master/model/networks/res12.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from model.networks.dropblock import DropBlock
# This ResNet network was designed following the practice of the following papers:
# TADAM: Task dependent adaptive metric for improved few-shot learning (Oreshkin et al., in NIPS 2018) and
# A Simple Neur... | 4,705 | 36.349206 | 125 | py |
FEAT | FEAT-master/model/networks/WRN28.py | import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import sys
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
def conv_init... | 2,858 | 34.296296 | 98 | py |
FEAT | FEAT-master/model/networks/res18.py | import torch.nn as nn
__all__ = ['resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=Fal... | 5,632 | 28.492147 | 106 | py |
FEAT | FEAT-master/model/models/base.py | import torch
import torch.nn as nn
import numpy as np
class FewShotModel(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
if args.backbone_class == 'ConvNet':
from model.networks.convnet import ConvNet
self.encoder = ConvNet()
elif ar... | 2,434 | 43.272727 | 174 | py |
FEAT | FEAT-master/model/models/graphnet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
import math
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
from itertools import permutations
import scipy.sparse as sp
class GraphConvolution(Module):
... | 6,810 | 37.480226 | 128 | py |
FEAT | FEAT-master/model/models/deepset.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
class DeepSetsFunc(nn.Module):
def __init__(self, z_dim):
super(DeepSetsFunc, self).__init__()
"""
DeepSets Function
"""
self.gen1 = nn.Linear(z_dim, ... | 5,338 | 43.865546 | 117 | py |
FEAT | FEAT-master/model/models/semi_protofeat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
from model.utils import one_hot
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__ini... | 8,560 | 45.781421 | 230 | py |
FEAT | FEAT-master/model/models/protonet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
# Note: As in Protonet, we use Euclidean Distances here, you can change to the Cosine Similarity by replace
# TRUE in line 30 as self.args.use_euclidean
class ProtoNet(FewShotModel):
... | 2,007 | 40.833333 | 137 | py |
FEAT | FEAT-master/model/models/bilstm.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from model.models import FewShotModel
class BidirectionalLSTM(nn.Module):
def __init__(self, layer_sizes, vector_dim):
super(BidirectionalLSTM, self).__init__()
"""
Ini... | 5,746 | 45.723577 | 118 | py |
FEAT | FEAT-master/model/models/classifier.py | import torch
import torch.nn as nn
import numpy as np
from model.utils import euclidean_metric
import torch.nn.functional as F
class Classifier(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
if args.backbone_class == 'ConvNet':
from model.networks... | 1,617 | 32.708333 | 75 | py |
FEAT | FEAT-master/model/models/featstar.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
# No-Reg for FEAT-STAR here
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__... | 4,959 | 37.153846 | 114 | py |
FEAT | FEAT-master/model/models/matchnet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
from model.utils import one_hot
# Note: This is the MatchingNet without FCE
# it predicts an instance based on nearest neighbor rule (not Nearest center mean)
class MatchNet(FewShotModel)... | 2,299 | 40.818182 | 133 | py |
FEAT | FEAT-master/model/models/__init__.py | from model.models.base import FewShotModel
| 43 | 21 | 42 | py |
FEAT | FEAT-master/model/models/feat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature =... | 6,494 | 42.590604 | 119 | py |
FEAT | FEAT-master/model/models/semi_feat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature =... | 6,584 | 42.9 | 119 | py |
FEAT | FEAT-master/model/dataloader/tiered_imagenet.py | from __future__ import print_function
import os
import os.path as osp
import numpy as np
import pickle
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
# Set the appropriate paths of the datasets here.
THIS_PATH = osp.dirname(__file__)
ROOT_PATH... | 4,423 | 35.561983 | 114 | py |
FEAT | FEAT-master/model/dataloader/cub.py | import os.path as osp
import PIL
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
THIS_PATH = osp.dirname(__file__)
ROOT_PATH1 = osp.abspath(osp.join(THIS_PATH, '..', '..', '..'))
ROOT_PATH2 = osp.abspath(osp.join(THIS_PATH, '..', '..'))
IMAGE_PATH = osp... | 4,840 | 38.040323 | 112 | py |
FEAT | FEAT-master/model/dataloader/mini_imagenet.py | import torch
import os.path as osp
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from tqdm import tqdm
import numpy as np
THIS_PATH = osp.dirname(__file__)
ROOT_PATH = osp.abspath(osp.join(THIS_PATH, '..', '..'))
ROOT_PATH2 = osp.abspath(osp.join(THIS_PATH, '..', '..', ... | 4,581 | 36.252033 | 112 | py |
FEAT | FEAT-master/model/dataloader/samplers.py | import torch
import numpy as np
class CategoriesSampler():
def __init__(self, label, n_batch, n_cls, n_per):
self.n_batch = n_batch
self.n_cls = n_cls
self.n_per = n_per
label = np.array(label)
self.m_ind = []
for i in range(max(label) + 1):
ind = np.a... | 2,586 | 27.119565 | 82 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/setup.py | import os
from setuptools import find_packages
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
install_requires = [
"numpy",
"Pillow"
]
setup(
name='ple',
version='0.0.1',
description='PyGame Learning Environment',
classifiers=[
"Intended Audience :: Developers"... | 874 | 24.735294 | 79 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/ple.py | import numpy as np
from PIL import Image # pillow
import sys
import pygame
from .games.base.pygamewrapper import PyGameWrapper
class PLE(object):
"""
ple.PLE(
game, fps=30,
frame_skip=1, num_steps=1,
reward_values={}, force_fps=True,
display_screen=False, add_noop_action=True,... | 11,976 | 27.314421 | 137 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/__init__.py | from .ple import PLE
| 21 | 10 | 20 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/waterworld.py | import pygame
import sys
import math
#import .base
from .base.pygamewrapper import PyGameWrapper
from .utils.vec2d import vec2d
from .utils import percent_round_int
from pygame.constants import K_w, K_a, K_s, K_d
from .primitives import Player, Creep
class WaterWorld(PyGameWrapper):
"""
Based Karpthy's Wate... | 6,382 | 25.595833 | 82 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/raycastmaze.py |
#import .base
from .base.pygamewrapper import PyGameWrapper
import pygame
import numpy as np
import math
from .raycast import RayCastPlayer
from pygame.constants import K_w, K_a, K_d, K_s
class RaycastMaze(PyGameWrapper, RayCastPlayer):
"""
Parameters
----------
init_pos : tuple of int (default: (1,1... | 9,656 | 32.415225 | 161 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/snake.py | import pygame
import sys
import math
#import .base
from .base.pygamewrapper import PyGameWrapper
from pygame.constants import K_w, K_a, K_s, K_d
from .utils.vec2d import vec2d
from .utils import percent_round_int
class Food(pygame.sprite.Sprite):
def __init__(self, pos_init, width, color,
SCRE... | 11,320 | 26.747549 | 148 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/pixelcopter.py | import math
import sys
#import .base
from .base.pygamewrapper import PyGameWrapper
import pygame
from pygame.constants import K_w, K_s
from .utils.vec2d import vec2d
class Block(pygame.sprite.Sprite):
def __init__(self, pos_init, speed, SCREEN_WIDTH, SCREEN_HEIGHT):
pygame.sprite.Sprite.__init__(self)
... | 9,494 | 26.521739 | 101 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/raycast.py | import pdb
import time
import os
import sys
import pygame
import numpy as np
from pygame.constants import K_w, K_a, K_d, K_s
import copy
class RayCastPlayer():
"""
Loosely based on code from Lode's `Computer Graphics Tutorial`_.
.. _Computer Graphics Tutorial: http://lodev.org/cgtutor/raycasting.html
... | 10,881 | 29.914773 | 79 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/puckworld.py | import pygame
import sys
import math
#import .base
from .base.pygamewrapper import PyGameWrapper
from pygame.constants import K_w, K_a, K_s, K_d
from .primitives import Player, Creep
from .utils.vec2d import vec2d
from .utils import percent_round_int
class PuckCreep(pygame.sprite.Sprite):
def __init__(self, po... | 7,591 | 25.921986 | 70 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/primitives.py | import pygame
import math
from .utils.vec2d import vec2d
class Creep(pygame.sprite.Sprite):
def __init__(self,
color,
radius,
pos_init,
dir_init,
speed,
reward,
TYPE,
SCREEN_WID... | 4,703 | 26.83432 | 64 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/pong.py | import math
import sys
import pygame
from pygame.constants import K_w, K_s
from ple.games.utils.vec2d import vec2d
from ple.games.utils import percent_round_int
#import base
from ple.games.base.pygamewrapper import PyGameWrapper
class Ball(pygame.sprite.Sprite):
def __init__(self, radius, speed, rng,
... | 12,840 | 30.243309 | 294 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/__init__.py | try:
from ple.games.doom import Doom
except:
print("Couldn't import doom")
from ple.games.catcher import Catcher
from ple.games.flappybird import FlappyBird
from ple.games.monsterkong import MonsterKong
from ple.games.pixelcopter import Pixelcopter
from ple.games.pong import Pong
from ple.games.puckworld import... | 455 | 31.571429 | 45 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/catcher.py | import sys
import pygame
from .utils import percent_round_int
from ple.games import base
from pygame.constants import K_a, K_d
class Paddle(pygame.sprite.Sprite):
def __init__(self, speed, width, height, SCREEN_WIDTH, SCREEN_HEIGHT):
self.speed = speed
self.width = width
self.SCREEN_WID... | 6,177 | 23.613546 | 74 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/monsterkong/fireball.py | __author__ = 'Erilyth'
import pygame
import math
import os
from .onBoard import OnBoard
'''
This class defines all our fireballs.
A fireball inherits from the OnBoard class since we will use it as an inanimate object on our board.
Each fireball can check for collisions in order to decide when to turn and when they hit... | 5,580 | 40.340741 | 154 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/monsterkong/board.py | __author__ = 'Batchu Vishal'
import pygame
import math
import sys
import os
from .person import Person
from .onBoard import OnBoard
from .coin import Coin
from .player import Player
from .fireball import Fireball
from .monsterPerson import MonsterPerson
class Board(object):
'''
This class defines our gameboa... | 15,293 | 41.960674 | 126 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/ple/games/monsterkong/ladder.py | __author__ = 'Batchu Vishal'
import pygame
from onBoard import OnBoard
'''
This class defines all our ladders in the game.
Currently not much is done here, but we can add features such as ladder climb sounds etc here
'''
class Ladder(OnBoard):
def __init__(self, raw_image, position):
super(Ladder, self... | 518 | 23.714286 | 93 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.