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
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/funksvd.py
""" FunkSVD (biased MF). """ import logging import time import pandas as pd import numpy as np import numba as n from . import basic from .mf_common import BiasMFPredictor from .. import util _logger = logging.getLogger(__name__) @n.jitclass([ ('user_features', n.double[:, :]), ('item_features', n.double[...
9,416
29.377419
98
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/mf_common.py
""" Common utilities & implementations for matrix factorization. """ import pathlib import logging import numpy as np import pandas as pd from .. import util from . import Predictor _logger = logging.getLogger(__name__) class MFPredictor(Predictor): """ Common predictor for matrix factorization. Attr...
4,358
27.122581
86
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/als.py
import logging from collections import namedtuple import numpy as np from numba import njit, prange from . import basic from .mf_common import BiasMFPredictor, MFPredictor from ..matrix import sparse_ratings, _CSR from .. import util from ..math.solve import _dposv _logger = logging.getLogger(__name__) Context = na...
11,409
35.222222
100
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/user_knn.py
""" User-based k-NN collaborative filtering. """ from sys import intern import pathlib import logging import pandas as pd import numpy as np from scipy import stats from .. import util, matrix from . import Predictor _logger = logging.getLogger(__name__) class UserUser(Predictor): """ User-user nearest-ne...
7,625
33.506787
99
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/hpf.py
import logging import pandas as pd from .mf_common import MFPredictor _logger = logging.getLogger(__name__) class HPF(MFPredictor): """ Hierarchical Poisson factorization, provided by hpfrec_. .. _hpfrec: https://hpfrec.readthedocs.io/en/latest/ Args: features(int): the number of features...
1,322
24.442308
73
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/__init__.py
""" LensKit algorithms. The `lenskit.algorithms` package contains several example algorithms for carrying out recommender experiments. These algorithm implementations are designed to mimic the characteristics of the implementations provided by the original LensKit Java package. It also provides abstract base classes...
7,065
34.154229
99
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/implicit.py
import logging import inspect import pandas as pd from ..matrix import sparse_ratings from . import Recommender _logger = logging.getLogger(__name__) class BaseRec(Recommender): """ Base class for Implicit-backed recommenders. Args: delegate(implicit.RecommenderBase): The delegate a...
3,209
28.449541
92
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/algorithms/basic.py
""" Basic utility algorithms and combiners. """ import logging from collections.abc import Iterable, Sequence import pandas as pd import numpy as np from .. import check from . import Predictor, Recommender, CandidateSelector _logger = logging.getLogger(__name__) class Bias(Predictor): """ A user-item bia...
11,732
32.144068
100
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/metrics/topn.py
""" Top-N evaluation metrics. """ import numpy as np def precision(recs, truth): """ Compute recommendation precision. """ nrecs = len(recs) if nrecs == 0: return None ngood = recs['item'].isin(truth.index).sum() return ngood / nrecs def recall(recs, truth): """ Compute...
2,864
26.285714
100
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/metrics/__init__.py
""" Metrics for evaluating recommendations. """
48
11.25
39
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/metrics/predict.py
""" Prediction accuracy metrics. """ import numpy as np import pandas as pd def _check_missing(truth, missing): """ Check for missing truth values. Args: truth: the series of truth values missing: what to do with missing values """ if missing == 'error' and truth.isna().any(): ...
1,952
24.038462
77
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/batch/_multi.py
import logging import pathlib import collections import json from copy import copy import pandas as pd from ..algorithms import Predictor from .. import topn, util from ._recommend import recommend from ._predict import predict try: import fastparquet except ImportError: fastparquet = None _logger = logging...
14,040
33.927861
99
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/batch/_recommend.py
import logging import warnings import multiprocessing as mp from multiprocessing.pool import Pool import pandas as pd import numpy as np from ..algorithms import Recommender from .. import util _logger = logging.getLogger(__name__) _rec_context = None class MPRecContext: def __init__(self, algo, candidates, si...
3,470
33.366337
95
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/batch/__init__.py
""" Batch-run predictors and recommenders for evaluation. """ from ._predict import predict from ._recommend import recommend from ._multi import MultiEval
157
18.75
53
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/batch/_predict.py
import logging import multiprocessing as mp from multiprocessing.pool import Pool import pandas as pd from .. import util from .. import crossfold _logger = logging.getLogger(__name__) _rec_context = None class MPRecContext: def __init__(self, algo): self.algo = algo def __enter__(self): g...
3,635
34.300971
89
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/math/solve.py
""" Efficient solver routines. """ import numpy as np import cffi import numba as n from numba.extending import get_cython_function_address __ffi = cffi.FFI() __uplo_U = np.array([ord('U')], dtype=np.int8) __uplo_L = np.array([ord('L')], dtype=np.int8) __trans_N = np.array([ord('N')], dtype=np.int8) __trans_T = np...
3,490
33.564356
91
py
MachineUnlearningPy
MachineUnlearningPy-master/lenskit/math/__init__.py
""" Mathematical helper routines. """
38
8.75
29
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_topn_recall.py
import numpy as np import pandas as pd from pytest import approx from lenskit.topn import recall def _test_recall(items, rel): recs = pd.DataFrame({'item': items}) truth = pd.DataFrame({'item': rel}).set_index('item') return recall(recs, truth) def test_recall_empty_zero(): prec = _test_recall([],...
2,502
25.347368
74
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_batch_sweep.py
import pathlib import json import pickle import pandas as pd import numpy as np from lk_test_utils import ml_pandas, norm_path from lenskit import batch, crossfold as xf from lenskit.algorithms import Predictor from lenskit.algorithms.basic import Bias, Popular from pytest import mark @mark.slow @mark.parametrize...
10,792
30.651026
94
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_check.py
from pytest import raises import numpy as np from lenskit.check import check_value, check_dimension def test_check_value_passes(): check_value(True, "value should be true") # it should complete successfully! def test_check_value_fails(): with raises(ValueError): check_value(False, "value shoul...
1,251
25.638298
63
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_funksvd.py
import logging import pickle from pathlib import Path import lenskit.algorithms.funksvd as svd import pandas as pd import numpy as np from pytest import approx, mark import lk_test_utils as lktu _log = logging.getLogger(__name__) simple_df = pd.DataFrame({'item': [1, 1, 2, 3], 'user': [1...
6,346
29.514423
89
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_batch_predict.py
import pytest import logging from collections import namedtuple import pandas as pd import numpy as np import lk_test_utils as lktu from lenskit.algorithms.basic import Bias import lenskit.batch as lkb _log = logging.getLogger(__name__) MLB = namedtuple('MLB', ['ratings', 'algo']) @pytest.fixture def mlb(): ...
4,039
29.37594
99
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/conftest.py
import logging from pytest import fixture _log = logging.getLogger('lenskit.tests') @fixture(autouse=True) def log_test(request): _log.info('running test %s:%s', request.module.__name__, request.function.__name__) def pytest_collection_modifyitems(items): # add 'slow' to all 'eval' tests for item in it...
552
26.65
87
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_matrix_csr.py
import pickle import numpy as np import scipy.sparse as sps import lenskit.matrix as lm import lk_test_utils as lktu from pytest import mark, approx, raises @mark.parametrize('copy', [True, False]) def test_csr_from_sps(copy): # initialize sparse matrix mat = np.random.randn(10, 5) mat[mat <= 0] = 0 ...
9,667
28.747692
87
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_als_explicit.py
import logging import pickle from lenskit.algorithms import als import pandas as pd import numpy as np from pytest import approx, mark import lk_test_utils as lktu _log = logging.getLogger(__name__) simple_df = pd.DataFrame({'item': [1, 1, 2, 3], 'user': [10, 12, 10, 13], ...
4,743
29.216561
89
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_util.py
import time import re import pathlib import numpy as np import pandas as pd from lenskit import util as lku def test_stopwatch_instant(): w = lku.Stopwatch() assert w.elapsed() > 0 def test_stopwatch_sleep(): w = lku.Stopwatch() time.sleep(0.5) assert w.elapsed() >= 0.45 def test_stopwatch_s...
4,581
20.613208
79
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_implicit.py
import logging import pickle import pandas as pd import numpy as np from pytest import mark try: import implicit have_implicit = True except ImportError: have_implicit = False import lk_test_utils as lktu from lenskit.algorithms.implicit import ALS, BPR from lenskit import util _log = logging.getLogger...
3,075
24.421488
73
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_basic.py
from lenskit.algorithms import basic from lenskit import util as lku import pandas as pd import numpy as np import pickle import lk_test_utils as lktu from pytest import approx simple_df = pd.DataFrame({'item': [1, 1, 2, 3], 'user': [10, 12, 10, 13], 'rating': [4.0...
10,950
28.758152
83
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_topn_analysis.py
from pathlib import Path import logging import numpy as np import pandas as pd from pytest import approx from lenskit.metrics.topn import _dcg from lenskit import topn _log = logging.getLogger(__name__) def test_run_one(): rla = topn.RecListAnalysis() rla.add_metric(topn.precision) rla.add_metric(topn....
4,560
28.425806
83
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_knn_item_item.py
from lenskit import DataWarning import lenskit.algorithms.item_knn as knn from pathlib import Path import logging import os.path import pickle import pandas as pd import numpy as np from scipy import linalg as la import pytest from pytest import approx, mark import lk_test_utils as lktu _log = logging.getLogger(__...
17,725
31.704797
100
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_knn_user_user.py
import lenskit.algorithms.user_knn as knn from pathlib import Path import logging import pickle import pandas as pd import numpy as np from scipy import sparse as sps from pytest import approx, mark import lk_test_utils as lktu _log = logging.getLogger(__name__) ml_ratings = lktu.ml_pandas.renamed.ratings def t...
8,382
29.933579
89
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_batch_recommend.py
import pytest import os import os.path from collections import namedtuple import logging import pandas as pd import numpy as np import lk_test_utils as lktu from lenskit.algorithms.basic import Bias, TopN import lenskit.batch as lkb MLB = namedtuple('MLB', ['ratings', 'algo']) _log = logging.getLogger(__name__) @...
4,975
29.527607
100
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_hpf.py
import logging import pickle from lenskit.algorithms import hpf, basic import pandas as pd import numpy as np from pytest import mark import lk_test_utils as lktu try: import hpfrec have_hpfrec = True except ImportError: have_hpfrec = False _log = logging.getLogger(__name__) simple_df = pd.DataFrame(...
1,341
23.4
77
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_matrix.py
import scipy.sparse as sps import scipy.linalg as sla import numpy as np import lenskit.matrix as lm import lk_test_utils as lktu from pytest import approx def test_sparse_matrix(): ratings = lktu.ml_pandas.renamed.ratings mat, uidx, iidx = lm.sparse_ratings(ratings) assert mat.nrows == len(uidx) ...
1,907
28.353846
60
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_matrix_mkl.py
import numpy as np import scipy.sparse as sps from pytest import mark, approx import lenskit.matrix as lm mkl_ops = lm.mkl_ops() @mark.skipif(mkl_ops is None, reason='MKL not available') def test_mkl_mult_vec(): for i in range(50): m = np.random.randint(5, 100) n = np.random.randint(5, 100) ...
1,193
21.528302
57
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_crossfold.py
import itertools as it import functools as ft import pytest import math import numpy as np import lk_test_utils as lktu import lenskit.crossfold as xf def test_partition_rows(): ratings = lktu.ml_pandas.renamed.ratings splits = xf.partition_rows(ratings, 5) splits = list(splits) assert len(splits) ...
11,496
32.616959
96
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_math_solve.py
import os import numpy as np import scipy.linalg as sla from pytest import approx from lenskit.math.solve import solve_tri, dposv _runs = int(os.environ.get('RAND_TEST_ITERS', 10)) def test_solve_ltri(): for i in range(_runs): size = np.random.randint(5, 50) Af = np.random.randn(size, size) ...
2,527
23.307692
56
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_topn_ndcg.py
import numpy as np import pandas as pd from pytest import approx from lenskit.metrics.topn import _dcg, ndcg import lk_test_utils as lktu def test_dcg_empty(): "empty should be zero" assert _dcg(np.array([])) == approx(0) def test_dcg_zeros(): assert _dcg(np.zeros(10)) == approx(0) def test_dcg_sing...
2,744
28.202128
83
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_als_implicit.py
import logging import pickle from lenskit import topn from lenskit.algorithms import als import pandas as pd import numpy as np from pytest import mark import lk_test_utils as lktu _log = logging.getLogger(__name__) simple_df = pd.DataFrame({'item': [1, 1, 2, 3], 'user': [10, 12, 10, 13]...
3,923
28.283582
73
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_predict_metrics.py
import numpy as np import pandas as pd import os.path from pytest import approx, raises, mark, skip import lenskit.metrics.predict as pm import lk_test_utils as lktu def test_check_missing_empty(): pm._check_missing(pd.Series([]), 'error') # should pass assert True def test_check_missing_has_values():...
5,003
24.927461
91
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_topn_mrr.py
import numpy as np import pandas as pd from pytest import approx from lenskit.topn import recip_rank def _test_rr(items, rel): recs = pd.DataFrame({'item': items}) truth = pd.DataFrame({'item': rel}).set_index('item') return recip_rank(recs, truth) def test_mrr_empty_zero(): rr = _test_rr([], [1, ...
1,189
21.037037
61
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_baselines.py
import lenskit.algorithms.basic as bl from lenskit import util as lku import logging import pickle import pandas as pd import numpy as np from pytest import approx import lk_test_utils as lktu from lk_test_utils import ml_pandas _log = logging.getLogger(__name__) simple_df = pd.DataFrame({'item': [1, 1, 2, 3], ...
8,090
30.119231
93
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/lk_test_utils.py
""" Test utilities for LKPY tests. """ import os import os.path import tempfile import pathlib import logging from contextlib import contextmanager import pandas as pd import pytest _log = logging.getLogger('lktu') ml_dir = os.path.join(os.path.dirname(__file__), '../ml-latest-small') class Renamer: def __ini...
2,954
22.267717
83
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_topn_utils.py
from lenskit import topn from lenskit.algorithms import CandidateSelector import pandas as pd import numpy as np import lk_test_utils as lktu def test_unrated(): ratings = lktu.ml_pandas.renamed.ratings unrate = topn.UnratedCandidates(ratings) cs = unrate(100) items = ratings.item.unique() rate...
1,241
24.346939
55
py
MachineUnlearningPy
MachineUnlearningPy-master/tests/test_topn_precision.py
import numpy as np import pandas as pd from pytest import approx from lenskit.topn import precision def _test_prec(items, rel): recs = pd.DataFrame({'item': items}) truth = pd.DataFrame({'item': rel}).set_index('item') return precision(recs, truth) def test_precision_empty_none(): prec = _test_pre...
2,386
25.522222
73
py
MachineUnlearningPy
MachineUnlearningPy-master/unlearn/visualization.py
import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.read_csv('output_matrix.csv') time_mean = df.groupby("n").mean().values ns = df.groupby("n").mean().index.get_level_values(0) plt.plot(ns,time_mean[:,0],label="native learning") plt.plot(ns,time_mean[:,1],label="unlearn supported learning"...
550
33.4375
100
py
MachineUnlearningPy
MachineUnlearningPy-master/unlearn/basic.py
import sys sys.path.insert(0,'../.') from lenskit import batch, topn, util from lenskit import crossfold as xf from lenskit.algorithms import Recommender, als, item_knn as knn import pandas as pd import matplotlib import time ratings = pd.read_csv('../ml-100k/u.data', sep='\t', names=['user',...
984
21.386364
77
py
MachineUnlearningPy
MachineUnlearningPy-master/doc/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
6,129
31.263158
79
py
GWE
GWE-master/convAE/make_char_feat_dict_nopool.py
import cPickle as pkl import pdb import sys import numpy as np import tensorflow as tf sys.path.insert(0, './models/') from conv_ae_char_nopool import Model checkpoint_filename = './checkpoints/conv_ae_char_nopool.ckpt-100' char_bitmap_dict_pkl_filename = '../data/char_dict.pkl' char_feat_dict_filename = '../data/ch...
1,455
25.472727
77
py
GWE
GWE-master/convAE/tsne_feature_nopool.py
# -*- coding: utf-8 -*- import cPickle as pkl import pdb import sys import numpy as np #from PIL import Image import tensorflow as tf from tsne import bh_sne sys.path.insert(0, './models/') from conv_ae_char_nopool import Model def save_collection_img(img_filename, n_row, n_col, img_size, offset, imgs): image=Ima...
3,809
25.643357
82
py
GWE
GWE-master/convAE/train_conv_ae_char_nopool.py
import cPickle as pkl import pdb import random import sys import time import numpy as np from PIL import Image import tensorflow as tf sys.path.insert(0, './models/') from conv_ae_char_nopool import Model def save_collection_img(img_filename, n_row, n_col, img_size, offset, imgs): image=Image.new("RGB", (n_col*img...
5,361
29.99422
112
py
GWE
GWE-master/convAE/models/conv_ae_char_nopool.py
import os import numpy as np import tensorflow as tf def unpool(updates, ksize=[1, 2, 2, 1]): original_shape = updates.get_shape() original_shape = tuple([i.__int__() for i in original_shape]) new_size = tf.shape(updates)[1:3] new_size *= tf.constant(np.array([ksize[1], ksize[2]]).astype('int32')) ...
14,915
38.356201
108
py
battery-historian
battery-historian-master/scripts/historian.py
#!/usr/bin/python """Legacy Historian script for analyzing Android bug reports.""" # Copyright 2016 Google Inc. 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 # # ht...
52,562
31.87242
167
py
battery-historian
battery-historian-master/scripts/kernel_trace.py
#!/usr/bin/python """Historian script for converting the timestamps in kernel trace to UTC. TO USE: kernel_trace.py --bugreport=<path to bugreport> --trace=<path to trace file> --device=<device type hammerhead/shamu/flounder/flounder_lte> """ # Copyright 2016 Google Inc. All rights reserved. # # Licensed under the...
6,942
29.186957
78
py
3DG-STFM
3DG-STFM-master/train_rgbd_t_s.py
import math import argparse import pprint from distutils.util import strtobool from pathlib import Path from loguru import logger as loguru_logger import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbac...
5,270
41.168
111
py
3DG-STFM
3DG-STFM-master/train_rgb.py
import math import argparse import pprint from distutils.util import strtobool from pathlib import Path from loguru import logger as loguru_logger import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbac...
5,007
40.04918
111
py
3DG-STFM
3DG-STFM-master/test_rgbd.py
import pytorch_lightning as pl import argparse import pprint from loguru import logger as loguru_logger from src.config.default import get_cfg_defaults from src.utils.profiler import build_profiler from src.lightning.data import MultiSceneDataModule, RGBDDataModule from src.lightning.lightning_loftr import PL_LoFTR,P...
2,657
37.521739
111
py
3DG-STFM
3DG-STFM-master/test_rgb.py
import pytorch_lightning as pl import argparse import pprint from loguru import logger as loguru_logger from src.config.default import get_cfg_defaults from src.utils.profiler import build_profiler from src.lightning.data import RGBDataModule from src.lightning.lightning_loftr import PL_LoFTR_RGB def parse_args(): ...
2,622
37.014493
111
py
3DG-STFM
3DG-STFM-master/demo.py
import os import torch import cv2 import numpy as np import matplotlib.cm as cm import matplotlib.colors from src.loftr import default_cfg, LoFTR_RGBD, LoFTR_RGB import matplotlib.pyplot as plt def make_matching_figure( img0, img1, mkpts0, mkpts1, color, kpts0=None, kpts1=None, text=[], dpi=75, path=...
4,874
33.574468
106
py
3DG-STFM
3DG-STFM-master/train_rgbd.py
import math import argparse import pprint from distutils.util import strtobool from pathlib import Path from loguru import logger as loguru_logger import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.loggers import TensorBoardLogger from pytorch_lightning.callbac...
5,134
40.41129
111
py
3DG-STFM
3DG-STFM-master/src/__init__.py
0
0
0
py
3DG-STFM
3DG-STFM-master/src/config/default.py
from yacs.config import CfgNode as CN _CN = CN() ############## ↓ LoFTR Pipeline ↓ ############## _CN.LOFTR = CN() _CN.LOFTR.BACKBONE_TYPE = 'ResNetFPN' _CN.LOFTR.RESOLUTION = (8, 2) # options: [(8, 2), (16, 4)] _CN.LOFTR.FINE_WINDOW_SIZE = 5 # window_size in fine_level, must be odd _CN.LOFTR.FINE_CONCAT_COARSE_...
7,068
40.339181
133
py
3DG-STFM
3DG-STFM-master/src/datasets/sampler.py
import torch from torch.utils.data import Sampler, ConcatDataset class RandomConcatSampler(Sampler): """ Random sampler for ConcatDataset. At each epoch, `n_samples_per_subset` samples will be draw from each subset in the ConcatDataset. If `subset_replacement` is ``True``, sampling within each subset will be ...
4,293
54.051282
164
py
3DG-STFM
3DG-STFM-master/src/datasets/megadepth.py
import os.path as osp import numpy as np import torch import torch.nn.functional as F from torch.utils.data import Dataset from loguru import logger import cv2 from src.utils.dataset import read_megadepth_gray, read_megadepth_depth, read_megadepth_rgb class MegaDepth_RGB_Dataset(Dataset): def __init__(self, ...
12,808
46.6171
129
py
3DG-STFM
3DG-STFM-master/src/datasets/scannet.py
from os import path as osp from typing import Dict from unicodedata import name import numpy as np import torch import torch.utils as utils from numpy.linalg import inv from src.utils.dataset import ( read_scannet_rgb, read_scannet_gray, read_scannet_depth, read_scannet_pose, read_scannet_intrinsic...
11,203
43.995984
130
py
3DG-STFM
3DG-STFM-master/src/lightning/lightning_loftr.py
from collections import defaultdict import pprint from loguru import logger from pathlib import Path import torch import numpy as np import pytorch_lightning as pl from matplotlib import pyplot as plt from src.loftr import LoFTR_RGB,LoFTR_RGBD,LoFTR_RGBD_teacher,LoFTR_RGB_student from src.loftr.utils.supervision imp...
40,636
45.021518
129
py
3DG-STFM
3DG-STFM-master/src/lightning/data.py
import os import math from collections import abc from loguru import logger from torch.utils.data.dataset import Dataset from tqdm import tqdm from os import path as osp from pathlib import Path from joblib import Parallel, delayed import pytorch_lightning as pl from torch import distributed as dist from torch.utils.d...
27,968
44.626427
132
py
3DG-STFM
3DG-STFM-master/src/loftr/__init__.py
from .loftr import LoFTR_RGB,LoFTR_RGBD,LoFTR_RGBD_teacher,LoFTR_RGB_student from .utils.cvpr_ds_config import default_cfg
123
40.333333
76
py
3DG-STFM
3DG-STFM-master/src/loftr/loftr.py
import torch import torch.nn as nn import torch.nn.functional as F from einops.einops import rearrange, repeat from .backbone import build_backbone_rgb,build_backbone_rgbd from .utils.position_encoding import PositionEncodingSine from .loftr_module import LocalFeatureTransformer, FinePreprocess from .utils.coarse_matc...
14,794
45.671924
154
py
3DG-STFM
3DG-STFM-master/src/loftr/backbone/__init__.py
from .resnet_fpn import ResNetFPN_8_2_RGB,ResNetFPN_8_2_RGBD def build_backbone_rgb(config): if config['backbone_type'] == 'ResNetFPN': if config['resolution'] == (8, 2): return ResNetFPN_8_2_RGB(config['resnetfpn']) else: raise ValueError(f"LOFTR.BACKBONE_TYPE {config['backbone_ty...
624
40.666667
89
py
3DG-STFM
3DG-STFM-master/src/loftr/backbone/resnet_fpn.py
import torch.nn as nn import torch.nn.functional as F def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution without padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False) def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with pad...
6,772
33.380711
96
py
3DG-STFM
3DG-STFM-master/src/loftr/loftr_module/linear_attention.py
""" Linear Transformer proposed in "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention" Modified from: https://github.com/idiap/fast-transformers/blob/master/fast_transformers/attention/linear_attention.py """ import torch from torch.nn import Module, Dropout def elu_feature_map(x): re...
2,794
33.085366
117
py
3DG-STFM
3DG-STFM-master/src/loftr/loftr_module/fine_preprocess.py
import torch import torch.nn as nn import torch.nn.functional as F from einops.einops import rearrange, repeat class FinePreprocess(nn.Module): def __init__(self, config): super().__init__() self.config = config self.cat_c_feat = config['fine_concat_coarse_feat'] self.W = self.con...
5,006
43.705357
109
py
3DG-STFM
3DG-STFM-master/src/loftr/loftr_module/transformer.py
import copy import torch import torch.nn as nn from .linear_attention import LinearAttention, FullAttention class LoFTREncoderLayer(nn.Module): def __init__(self, d_model, nhead, attention='linear'): super(LoFTREncoderLayer, self).__init__() self...
3,657
34.514563
105
py
3DG-STFM
3DG-STFM-master/src/loftr/loftr_module/__init__.py
from .transformer import LocalFeatureTransformer from .fine_preprocess import FinePreprocess
93
30.333333
48
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/supervision.py
from math import log from loguru import logger import torch from einops import repeat from kornia.utils import create_meshgrid from .geometry import warp_kpts ############## ↓ Coarse-Level supervision ↓ ############## @torch.no_grad() def mask_pts_at_padded_regions(grid_pt, mask): """For megadepth dataset,...
5,724
36.418301
110
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/cvpr_ds_config.py
from yacs.config import CfgNode as CN def lower_config(yacs_cfg): if not isinstance(yacs_cfg, CN): return yacs_cfg return {k.lower(): lower_config(v) for k, v in yacs_cfg.items()} _CN = CN() _CN.BACKBONE_TYPE = 'ResNetFPN' _CN.RESOLUTION = (8, 2) # options: [(8, 2), (16, 4)] _CN.FINE_WINDOW_SIZE = ...
1,516
29.34
84
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/position_encoding.py
import math import torch from torch import nn class PositionEncodingSine(nn.Module): """ This is a sinusoidal position encoding that generalized to 2-dimensional images """ def __init__(self, d_model, max_shape=(256, 256)): """ Args: max_shape (tuple): for 1/8 featmap, the...
1,235
33.333333
104
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/fine_matching.py
import math import torch import torch.nn as nn from kornia.geometry.subpix import dsnt from kornia.utils.grid import create_meshgrid class FineMatching(nn.Module): """FineMatching with s2d paradigm""" def __init__(self): super().__init__() def forward(self, feat_f0, feat_f1, data): """ ...
5,385
37.471429
113
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/supervision_homography.py
from math import log from loguru import logger import torch from einops import repeat from kornia.utils import create_meshgrid from .geometry import warp_kpts,warp_kpts_homo ############## ↓ Coarse-Level supervision ↓ ############## @torch.no_grad() def mask_pts_at_padded_regions(grid_pt, mask): """For me...
5,957
36.708861
111
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/geometry.py
import torch import cv2 @torch.no_grad() def warp_kpts_homo(kpts0, M): """ Warp kpts0 from I0 to I1 with Homography M Args: kpts0 (torch.Tensor): [N, L, 2] - <x, y>, M (torch.Tensor): Returns: warped_keypoints0 (torch.Tensor): [N, L, 2] <x0_hat, y1_hat> """ #kpts0_long = kpt...
2,838
34.936709
113
py
3DG-STFM
3DG-STFM-master/src/loftr/utils/coarse_matching.py
import torch import torch.nn as nn import torch.nn.functional as F from einops.einops import rearrange INF = 1e9 def mask_border(m, b: int, v): """ Mask borders with value Args: m (torch.Tensor): [N, H0, W0, H1, W1] b (int) v (m.dtype) """ if b <= 0: return m[:, :b...
20,002
41.289641
120
py
3DG-STFM
3DG-STFM-master/src/optimizers/__init__.py
import torch from torch.optim.lr_scheduler import MultiStepLR, CosineAnnealingLR, ExponentialLR def build_optimizer(model, config): name = config.TRAINER.OPTIMIZER lr = config.TRAINER.TRUE_LR if name == "adam": return torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=lr, ...
1,665
35.217391
135
py
3DG-STFM
3DG-STFM-master/src/utils/plotting.py
import bisect import numpy as np import matplotlib.pyplot as plt import matplotlib import os def _compute_conf_thresh(data): dataset_name = data['dataset_name'][0].lower() if dataset_name == 'scannet': thr = 5e-4 elif dataset_name == 'megadepth': thr = 1e-4 else: raise ValueErro...
5,723
35.227848
106
py
3DG-STFM
3DG-STFM-master/src/utils/comm.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ [Copied from detectron2] This file contains primitives for multi-gpu communication. This is useful when doing distributed training. """ import functools import logging import numpy as np import pickle import torch import torch.distributed as di...
7,776
28.236842
100
py
3DG-STFM
3DG-STFM-master/src/utils/dataloader.py
import numpy as np # --- PL-DATAMODULE --- def get_local_split(items: list, world_size: int, rank: int, seed: int): """ The local rank only loads a split of the dataset. """ n_items = len(items) items_permute = np.random.RandomState(seed).permutation(items) if n_items % world_size == 0: padde...
876
35.541667
109
py
3DG-STFM
3DG-STFM-master/src/utils/misc.py
import os import contextlib import joblib from typing import Union from loguru import _Logger, logger from itertools import chain import torch from yacs.config import CfgNode as CN from pytorch_lightning.utilities import rank_zero_only def lower_config(yacs_cfg): if not isinstance(yacs_cfg, CN): return y...
3,512
33.441176
128
py
3DG-STFM
3DG-STFM-master/src/utils/augment.py
import albumentations as A class DarkAug(object): """ Extreme dark augmentation aiming at Aachen Day-Night """ def __init__(self) -> None: self.augmentor = A.Compose([ A.RandomBrightnessContrast(p=0.75, brightness_limit=(-0.6, 0.0), contrast_limit=(-0.5, 0.3)), A.Blur(...
1,578
27.196429
105
py
3DG-STFM
3DG-STFM-master/src/utils/dataset.py
import io from loguru import logger import cv2 import numpy as np import h5py import torch from numpy.linalg import inv import os try: # for internel use only from .client import MEGADEPTH_CLIENT, SCANNET_CLIENT except Exception: MEGADEPTH_CLIENT = SCANNET_CLIENT = None # --- DATA IO --- def load_array_...
8,671
31.479401
111
py
3DG-STFM
3DG-STFM-master/src/utils/metrics.py
import torch import cv2 import numpy as np from collections import OrderedDict from loguru import logger from kornia.geometry.epipolar import numeric from kornia.geometry.conversions import convert_points_to_homogeneous import random # --- METRICS --- def relative_pose_error(T_0to1, R, t, ignore_gt_t_thr=0.0): # a...
16,290
35.042035
119
py
3DG-STFM
3DG-STFM-master/src/utils/profiler.py
import torch from pytorch_lightning.profiler import SimpleProfiler, PassThroughProfiler from contextlib import contextmanager from pytorch_lightning.utilities import rank_zero_only class InferenceProfiler(SimpleProfiler): """ This profiler records duration of actions with cuda.synchronize() Use this in te...
1,199
29
81
py
3DG-STFM
3DG-STFM-master/src/losses/loftr_loss.py
from loguru import logger import torch import torch.nn as nn import torch.nn.functional as F class LoFTRLoss(nn.Module): def __init__(self, config): super().__init__() self.config = config # config under the global namespace self.loss_config = config['loftr']['loss'] self.match_ty...
20,436
46.30787
179
py
3DG-STFM
3DG-STFM-master/configs/loftr/indoor/loftr_ds_dense.py
from src.config.default import _CN as cfg cfg.LOFTR.MATCH_COARSE.MATCH_TYPE = 'dual_softmax' cfg.LOFTR.MATCH_COARSE.SPARSE_SPVS = False cfg.TRAINER.MSLR_MILESTONES = [3, 6, 9, 12, 17, 20, 23, 26, 29]
203
24.5
63
py
3DG-STFM
3DG-STFM-master/configs/loftr/indoor/scannet/loftr_ds_eval.py
""" A config only for reproducing the ScanNet evaluation results. We remove border matches by default, but the originally implemented `remove_border()` has a bug, leading to only two sides of all borders are actually removed. However, the [bug fix](https://github.com/zju3dv/LoFTR/commit/e9146c8144dea5f3cbdd98b225f3e14...
685
41.875
137
py
3DG-STFM
3DG-STFM-master/configs/loftr/outdoor/loftr_ds_dense.py
from src.config.default import _CN as cfg cfg.LOFTR.MATCH_COARSE.MATCH_TYPE = 'dual_softmax' cfg.LOFTR.MATCH_COARSE.SPARSE_SPVS = False cfg.TRAINER.CANONICAL_LR = 8e-3 cfg.TRAINER.WARMUP_STEP = 1875 # 3 epochs cfg.TRAINER.WARMUP_RATIO = 0.1 cfg.TRAINER.MSLR_MILESTONES = [8, 12, 16, 20, 24] # pose estimation cfg.TRA...
461
26.176471
50
py
3DG-STFM
3DG-STFM-master/configs/data/scannet_mini_trainval.py
from configs.data.base import cfg TRAIN_BASE_PATH = "data/scannet_mini/index" cfg.DATASET.TRAINVAL_DATA_SOURCE = "ScanNet" cfg.DATASET.TRAIN_DATA_ROOT = "data/scannet_mini/train" cfg.DATASET.TRAIN_NPZ_ROOT = f"{TRAIN_BASE_PATH}/scene_data/train" cfg.DATASET.TRAIN_LIST_PATH = f"{TRAIN_BASE_PATH}/scene_data/train_list/...
907
49.444444
101
py
3DG-STFM
3DG-STFM-master/configs/data/base.py
""" The data config will be the last one merged into the main config. Setups in data configs will override all existed setups! """ from yacs.config import CfgNode as CN _CN = CN() _CN.DATASET = CN() _CN.TRAINER = CN() # training data config _CN.DATASET.TRAIN_DATA_ROOT = None _CN.DATASET.TRAIN_POSE_ROOT = None _CN.DAT...
949
25.388889
65
py
3DG-STFM
3DG-STFM-master/configs/data/megadepth_trainval_640.py
from configs.data.base import cfg TRAIN_BASE_PATH = "data/megadepth/index" cfg.DATASET.TRAINVAL_DATA_SOURCE = "MegaDepth" cfg.DATASET.TRAIN_DATA_ROOT = "data/megadepth/train" cfg.DATASET.TRAIN_NPZ_ROOT = f"{TRAIN_BASE_PATH}/scene_info_0.1_0.7" cfg.DATASET.TRAIN_LIST_PATH = f"{TRAIN_BASE_PATH}/trainvaltest_list/train_...
1,022
43.478261
107
py
3DG-STFM
3DG-STFM-master/configs/data/scannet_test_1500.py
from configs.data.base import cfg TEST_BASE_PATH = "inference/scannet_test_1500" cfg.DATASET.TEST_DATA_SOURCE = "ScanNet" cfg.DATASET.TEST_DATA_ROOT = "data/scannet/test" cfg.DATASET.TEST_NPZ_ROOT = f"{TEST_BASE_PATH}" cfg.DATASET.TEST_LIST_PATH = f"{TEST_BASE_PATH}/scannet_test.txt" cfg.DATASET.TEST_INTRINSIC_PATH =...
398
32.25
68
py
3DG-STFM
3DG-STFM-master/configs/data/scannet_test_mini.py
from configs.data.base import cfg TEST_BASE_PATH = "data/scannet_mini/index" cfg.DATASET.TEST_DATA_SOURCE = "ScanNet" cfg.DATASET.TEST_DATA_ROOT = "data/scannet_mini/train" cfg.DATASET.TEST_NPZ_ROOT = f"{TEST_BASE_PATH}/scene_data/train" cfg.DATASET.TEST_LIST_PATH = f"{TEST_BASE_PATH}/scene_data/train_list/scannet_al...
437
38.818182
86
py