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 |
|---|---|---|---|---|---|---|
pynbody | pynbody-master/pynbody/snapshot/__init__.py | """
snapshot
========
This module implements the :class:`~pynbody.snapshot.SimSnap` class which manages and stores snapshot data.
It also implements the :class:`~pynbody.snapshot.SubSnap` class (and relatives) which
represent different views of an existing :class:`~pynbody.snapshot.SimSnap`.
"""
import copy
import ... | 77,123 | 37.029586 | 208 | py |
pynbody | pynbody-master/pynbody/snapshot/ramses.py | """
ramses
======
Implements classes and functions for handling RAMSES files. AMR cells
are loaded as particles. You rarely need to access this module
directly as it will be invoked automatically via pynbody.load.
For a complete demo on how to use RAMSES outputs with pynbody, look at
the `ipython notebook demo
<htt... | 44,049 | 35.892797 | 172 | py |
pynbody | pynbody-master/pynbody/snapshot/ascii.py | """
ascii
=====
A simple ascii file reader for pynbody
"""
# for py2.5
import os
import numpy as np
from .. import chunk, family, units
from . import SimSnap
_max_buf = 1024 * 512
class AsciiSnap(SimSnap):
def _setup_slices(self, num_lines, take=None):
disk_family_slice = {family.dm: slice(0,n... | 2,656 | 25.57 | 101 | py |
pynbody | pynbody-master/pynbody/snapshot/grafic.py | """
grafic
======
Support for loading grafIC files
"""
import glob
import os
import warnings
import numpy as np
from .. import analysis, chunk, family, units
from ..extern.cython_fortran_utils import FortranFile
from ..util import grid_gen
from . import SimSnap
_float_data_type = 'f'
_int_data_type = 'l'
genic_h... | 8,542 | 35.665236 | 173 | py |
pynbody | pynbody-master/pynbody/analysis/gravity.py | """
gravity
=======
Functions for calculating the gravitational potential and accelerations.
"""
import math
import numpy as np
from .. import array, units
def potential(f, pos_vec, eps=None, unit=None):
"""
Calculates the gravitational potential at the specified position
using all particles in th... | 3,264 | 20.766667 | 72 | py |
pynbody | pynbody-master/pynbody/analysis/decomp.py | """
decomp
======
Tools for bulge/disk/halo decomposition
"""
import logging
import numpy as np
from .. import array, config, filt, util
from . import angmom, profile
logger = logging.getLogger('pynbody.analysis.decomp')
def decomp(h, aligned=False, j_disk_min=0.8, j_disk_max=1.1, E_cut=None, j_circ_from_r=Fal... | 7,135 | 31 | 121 | py |
pynbody | pynbody-master/pynbody/analysis/angmom.py | """
angmom
======
"""
import logging
import numpy as np
from .. import array, config, filt, transformation, units
from . import halo
logger = logging.getLogger('pynbody.analysis.angmom')
def ang_mom_vec(snap):
"""
Return the angular momentum vector of the specified snapshot.
The return units are [m... | 4,132 | 24.83125 | 93 | py |
pynbody | pynbody-master/pynbody/analysis/cosmology.py | """
cosmology
=========
A set of functions for common cosmological calculations.
"""
import math
import numpy as np
numpy = np # alias the alias
from .. import units
from ..configuration import config_parser
_interp_points = int(config_parser.get('general','cosmo-interpolation-points'))
def _a_dot(a, h0, om_m... | 8,982 | 27.791667 | 118 | py |
pynbody | pynbody-master/pynbody/analysis/pkdgrav_cosmo.py | """
pkdgrav_cosmo
=============
Cosmological module from PKDGRAV.
N.B. This code is being shared with skid and the I.C. generator.
**NEEDS DOCUMENTATION**
"""
import math
from scipy.integrate import ode, romberg
class Cosmology:
""" docs placeholder """
EPSCOSMO = 1e-7
def __init__(self, sim=Non... | 11,390 | 31.732759 | 102 | py |
pynbody | pynbody-master/pynbody/analysis/halo.py | """
halo
====
Functions for dealing with and manipulating halos in simulations.
"""
import logging
import math
import numpy as np
from .. import array, config, filt, transformation, units, util
from . import _com, cosmology, profile
logger = logging.getLogger('pynbody.analysis.halo')
def center_of_mass(sim):
... | 16,097 | 32.055441 | 143 | py |
pynbody | pynbody-master/pynbody/analysis/profile.py | """
profile
=======
A set of classes and functions for making profiles of simulation
properties.
"""
import logging
import math
import warnings
from time import process_time
import numpy as np
import pynbody
from .. import array, units, util
logger = logging.getLogger('pynbody.analysis.profile')
class Profile... | 35,084 | 32.70317 | 139 | py |
pynbody | pynbody-master/pynbody/analysis/hifrac.py | """
hifrac
=======
calculates Hydrogen ionization fraction - limited version of ionfrac to make use of CLOUDY HI table
"""
import logging
import os
import numpy as np
from ..array import SimArray
from .interpolate import interpolate3d
logger = logging.getLogger('pynbody.analysis.hifrac')
from pynbody import con... | 2,851 | 31.409091 | 124 | py |
pynbody | pynbody-master/pynbody/analysis/ionfrac.py | """
ionfrac
=======
calculates ionization fractions - NEEDS DOCUMENTATION
"""
import logging
import os
import numpy as np
from pynbody import config
logger = logging.getLogger('pynbody.analysis.ionfrac')
from .interpolate import interpolate3d
def calculate(sim, ion='ovi', mode='old'):
"""
calculate -... | 2,014 | 27.785714 | 74 | py |
pynbody | pynbody-master/pynbody/analysis/hmf.py | """
halo mass function (hmf)
========================
Various halo mass function routines.
"""
import os
import numpy as np
import pynbody
from .. import units, util
from . import cosmology
try:
import scipy
import scipy.interpolate
except ImportError:
pass
import logging
import math
import subproc... | 28,140 | 32.185142 | 277 | py |
pynbody | pynbody-master/pynbody/analysis/luminosity.py | """
luminosity
==========
Calculates luminosities -- NEEDS DOCUMENTATION
"""
import os
import numpy as np
from .. import filt
from .interpolate import interpolate2d
_cmd_lum_file = os.path.join(os.path.dirname(__file__), "cmdlum.npz")
def use_custom_cmd(path):
"""Use a custom set of stellar populations to c... | 6,440 | 29.966346 | 116 | py |
pynbody | pynbody-master/pynbody/analysis/theoretical_profiles.py | """
theoretical_profiles
====================
Functional forms of common profiles (NFW as an example)
"""
import abc
import sys
import numpy as np
# # abc compatiblity with Python 2 *and* 3:
# # https://stackoverflow.com/questions/35673474/using-abc-abcmeta-in-a-way-it-is-compatible-both-with-python-2-7-and-pytho... | 9,415 | 41.414414 | 128 | py |
pynbody | pynbody-master/pynbody/analysis/__init__.py | from . import (
cosmology,
halo,
hifrac,
hmf,
interpolate,
ionfrac,
luminosity,
pkdgrav_cosmo,
profile,
ramses_util,
theoretical_profiles,
)
from .decomp import decomp
from .hmf import halo_mass_function
| 248 | 14.5625 | 35 | py |
pynbody | pynbody-master/pynbody/analysis/ramses_util.py | """
ramses_util
===========
Handy utilities for using RAMSES outputs in pynbody. For a complete
demo on how to use RAMSES outputs with pynbody, have a look at the
`ipython notebook demo
<http://nbviewer.ipython.org/github/pynbody/pynbody/blob/master/examples/notebooks/pynbody_demo-ramses.ipynb>`_
File Conversion
---... | 14,345 | 32.518692 | 119 | py |
pynbody | pynbody-master/pynbody/analysis/interpolate.py | """
interpolate
===========
2D and 3D Interpolation routines written in cython
"""
import numpy as np
from . import _interpolate3d
# this just calls the cython interpolation function, setting the
# interpolation arrays to correct type
def interpolate3d(x, y, z, x_vals, y_vals, z_vals, vals):
"""
Interpol... | 2,170 | 24.541176 | 71 | py |
pynbody | pynbody-master/pynbody/sph/kdtree.py | """
KDTree
======
Provides access to nearest neighbour lists and smoothing lengths.
"""
import logging
import time
import warnings
import numpy as np
from .. import array as ar, config
from . import kdmain
logger = logging.getLogger("pynbody.sph.kdtree")
class KDTree:
"""KDTree used for smoothing."""
P... | 11,385 | 32.886905 | 159 | py |
pynbody | pynbody-master/pynbody/sph/__init__.py | """
sph
===
pynbody SPH rendering module.
This module encompasses Kernel objects, which return C fragments from which
a final C code to perform the rendering is derived.
For most users, the function of interest will be :func:`~pynbody.sph.render_image`.
"""
import copy
import logging
import math
import os
import ... | 33,613 | 32.117241 | 213 | py |
pynbody | pynbody-master/pynbody/halo/legacy.py | import os.path
import numpy as np
from . import Halo, HaloCatalogue
class RockstarIntermediateCatalogue(HaloCatalogue):
"""Reader for Rockstar intermediate catalogues as generated by
Michael Tremmel's tool"""
_halo_type = np.dtype([('id',np.int64),('num_p',np.int64),('indstart',np.int64)])
_part_ty... | 4,867 | 37.944 | 99 | py |
pynbody | pynbody-master/pynbody/halo/ahf.py | import glob
import gzip
import os.path
import re
import warnings
import numpy as np
from .. import config_parser, snapshot, util
from . import DummyHalo, Halo, HaloCatalogue, logger
class AHFCatalogue(HaloCatalogue):
"""
Class to handle catalogues produced by Amiga Halo Finder (AHF).
"""
def __ini... | 30,642 | 38.744488 | 244 | py |
pynbody | pynbody-master/pynbody/halo/subfindhdf.py | import os.path
import warnings
import weakref
import h5py
import numpy as np
from .. import array, config_parser, snapshot, units
from ..snapshot import gadgethdf
from . import Halo, HaloCatalogue
class SubFindHDFSubhaloCatalogue(HaloCatalogue) :
"""
Gadget's SubFind HDF Subhalo catalogue.
Initialized ... | 20,547 | 38.139048 | 121 | py |
pynbody | pynbody-master/pynbody/halo/hop.py | import os.path
import re
import struct
import numpy as np
from . import GrpCatalogue
class HOPCatalogue(GrpCatalogue):
"""A HOP Catalogue as used by Ramses. HOP output files must be in simulation directory, in simulation/hop/ directory
or specified by fname"""
def __init__(self, sim, fname=None):
... | 2,679 | 34.263158 | 120 | py |
pynbody | pynbody-master/pynbody/halo/rockstar.py | import glob
import os.path
import sys
import numpy as np
from .. import util
from . import DummyHalo, Halo, HaloCatalogue
class RockstarCatalogue(HaloCatalogue):
def __init__(self, sim, dummy=False, pathname=None, format_revision=None,
filenames=None, sort=False, **kwargs):
"""Initializ... | 19,938 | 40.36722 | 244 | py |
pynbody | pynbody-master/pynbody/halo/subfind.py | import os.path
import warnings
import weakref
import numpy as np
from .. import units
from ..array import SimArray
from . import Halo, HaloCatalogue
class SubfindCatalogue(HaloCatalogue):
"""Class to handle catalogues produced by the SubFind halo finder.
By default, the FoF groups are imported, but the su... | 15,217 | 51.657439 | 188 | py |
pynbody | pynbody-master/pynbody/halo/__init__.py | """
halo
====
Implements halo catalogue functions. If you have a supported halo
catalogue on disk or a halo finder installed and correctly configured,
you can access a halo catalogue through f.halos() where f is a
SimSnap.
See the `halo tutorial
<http://pynbody.github.io/pynbody/tutorials/halos.html>`_ for some
exam... | 12,393 | 30.377215 | 122 | py |
pynbody | pynbody-master/pynbody/halo/adaptahop.py | import os.path
import re
from typing import Sequence
import numpy as np
from .. import array, units, util
from ..extern.cython_fortran_utils import FortranFile
from . import DummyHalo, Halo, HaloCatalogue, logger
unit_length = units.Unit("Mpc")
unit_vel = units.Unit("km s**-1")
unit_mass = 1e11 * units.Unit("Msol")
... | 18,310 | 33.811787 | 132 | py |
AROPE | AROPE-master/python/Sample_Run.py | # Sample run on BlogCatalog
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
import utils
from eval import Precision_Np
if __name__ == '__main__':
data = pd.read_csv('BlogCatalog.csv')
data = np.array(data) - 1 # change index from 0
N = np.max(np.max(... | 764 | 27.333333 | 91 | py |
AROPE | AROPE-master/python/utils.py |
import numpy as np
from scipy.sparse.linalg import eigs
def Eigen_Reweighting(X,order,coef):
# X: original eigenvalues
# order: order, -1 stands for infinity
# coef: weights, decaying constant if order = -1
# return: reweighted eigenvalues
if order == -1: # infinity
assert len(coef) == 1, 'Eigen_Rewei... | 2,873 | 35.846154 | 112 | py |
AROPE | AROPE-master/python/eval.py |
import numpy as np
def Precision_Np(Matrix_test,Matrix_train,U,V,Np):
# Matrix_test is n x n testing matrix, may overlap with Matrix_train
# Matrix_train is n x n training matrix
# U/V are content/context embedding vectors
# Np: returns Precision@Np for pairwise similarity
N, _ = U.shape
assert N < 30000, 'N... | 1,036 | 46.136364 | 106 | py |
OpusFilter | OpusFilter-master/setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
install_requires = [
"setuptools<=58.0.0", # for pyhash
"opustools",
"beautifulsoup4",
"fasttext",
"graphviz",
"langid",
"matplotlib",
"morfessor",
"fast-mosestokenizer",
"pandas>=1.0.0",
... | 1,930 | 23.443038 | 114 | py |
OpusFilter | OpusFilter-master/opusfilter/segment_hash.py | """Hashing parallel segments"""
import pyhash
import regex
from . import ConfigurationError
class SegmentHasher:
"""Hasher for text segments"""
not_letter = regex.compile(r'[^\p{L}]')
join_char = '\n'
join_char_escaped = r'\n'
def __init__(self, compare='all', method='xx_64', hashseed=0, lowe... | 2,455 | 38.612903 | 103 | py |
OpusFilter | OpusFilter-master/opusfilter/subwords.py | """Subword segmentation"""
import codecs
import functools
import logging
import math
import os
import random
from . import ConfigurationError, PreprocessorABC
from .util import file_open
logger = logging.getLogger(__name__)
LRU_MAX_SIZE = 1000000
class DummySegmentation(PreprocessorABC):
"""Base class for se... | 6,495 | 38.852761 | 119 | py |
OpusFilter | OpusFilter-master/opusfilter/tokenization.py | """Tokenization tools"""
import logging
from . import ConfigurationError
logger = logging.getLogger(__name__)
class DummyTokenizer:
"""Dummy tokenizer"""
@staticmethod
def tokenize(string):
"""Return tokenized version of the input string"""
return string
@staticmethod
def det... | 5,848 | 34.664634 | 107 | py |
OpusFilter | OpusFilter-master/opusfilter/embeddings.py | """Sentence embeddings"""
import collections
import itertools
import logging
import os
import pickle
from tqdm import tqdm
from . import FilterABC, ConfigurationError
from .util import file_open, grouper
logger = logging.getLogger(__name__)
class ParallelNearestNeighbors:
"""Wrapper for sklearn.neighbors.Nea... | 6,064 | 41.711268 | 114 | py |
OpusFilter | OpusFilter-master/opusfilter/classifier.py | """Filter classifier"""
import json
import logging
import collections
import functools
import math
import scipy.optimize
import numpy as np
import pandas as pd
from pandas import json_normalize
import sklearn.linear_model
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score, log_loss
from .uti... | 16,991 | 40.242718 | 110 | py |
OpusFilter | OpusFilter-master/opusfilter/opusfilter.py | """Processor for filter configurations"""
import collections
import copy
import functools
import itertools
import logging
import math
import multiprocessing
import operator
import os
import pickle
import random
import tempfile
from itertools import chain
import json
from tqdm import tqdm
from . import ConfigurationE... | 47,618 | 46.666667 | 122 | py |
OpusFilter | OpusFilter-master/opusfilter/util.py | """Utility functions"""
import bz2
import gzip
import io
import itertools
import logging
import lzma
import os
from tqdm import tqdm
import ruamel.yaml
from . import ConfigurationError
logger = logging.getLogger(__name__)
class FakeList:
"""Implements __getitem__ that returns always the same value"""
de... | 6,307 | 31.515464 | 100 | py |
OpusFilter | OpusFilter-master/opusfilter/word_alignment.py | """Word alignment filtering"""
import json
import logging
import os
import subprocess
import tempfile
from . import FilterABC, OpusFilterRuntimeError
from . import tokenization
from .util import file_open
logger = logging.getLogger(__name__)
EFLOMAL_PATH = os.environ.get('EFLOMAL_PATH')
if EFLOMAL_PATH is None:
... | 9,638 | 43.832558 | 126 | py |
OpusFilter | OpusFilter-master/opusfilter/lm.py | """Language model filtering"""
# pylint: disable=C0103
import argparse
import copy
import itertools
import logging
import math
import os
import tempfile
from . import FilterABC, ConfigurationError, OpusFilterRuntimeError
from .subwords import BPESegmentation, MorfessorSegmentation
from .util import is_file_empty
lo... | 17,573 | 37.794702 | 111 | py |
OpusFilter | OpusFilter-master/opusfilter/__init__.py | """Opusfilter package"""
import abc
import logging
logger = logging.getLogger(__name__)
class OpusFilterError(Exception):
"""OpusFilter error"""
class ConfigurationError(OpusFilterError):
"""Configuration error for OpusFilter"""
class OpusFilterRuntimeError(OpusFilterError):
"""Runtime error for Op... | 2,055 | 26.413333 | 85 | py |
OpusFilter | OpusFilter-master/opusfilter/filters.py | """Corpus filtering"""
import difflib
import itertools
import logging
import math
import os
import string
from typing import Iterator, List, Tuple
import regex
from . import FilterABC, ConfigurationError
from .util import check_args_compability
from .lm import CrossEntropyFilter, CrossEntropyDifferenceFilter, LMClas... | 20,678 | 35.730018 | 122 | py |
OpusFilter | OpusFilter-master/opusfilter/preprocessors.py | """Corpus preprocessing"""
from functools import reduce
from itertools import zip_longest
import logging
import operator
import re
import sentence_splitter
from . import PreprocessorABC, ConfigurationError
from .tokenization import get_tokenize
logger = logging.getLogger(__name__)
class Tokenizer(PreprocessorABC... | 6,082 | 38.75817 | 116 | py |
OpusFilter | OpusFilter-master/opusfilter/pipeline.py | """Filter pipeline"""
import collections
import importlib
import logging
from tqdm import tqdm
from . import filters as filtermodule
from . import preprocessors as preprocessmodule
from . import subwords as subwordsmodule
from .util import grouper
logger = logging.getLogger(__name__)
class FilterPipeline:
""... | 5,782 | 35.601266 | 86 | py |
OpusFilter | OpusFilter-master/tests/test_preprocessors.py | import logging
import unittest
from opusfilter.pipeline import PreprocessorPipeline
from opusfilter.preprocessors import *
try:
import jieba
except ImportError:
logging.warning("Could not import jieba")
UNICODE_WHITESPACE_CHARACTERS = [
"\u0009", # character tabulation
"\u000a", # line feed
"\... | 8,170 | 38.47343 | 89 | py |
OpusFilter | OpusFilter-master/tests/test_filters.py | import logging
import os
import requests
import shutil
import tempfile
import unittest
from opusfilter import ConfigurationError
from opusfilter.filters import *
from opusfilter.util import file_download
class TestLengthFilter(unittest.TestCase):
def test_words(self):
testfilter = LengthFilter(2, 3, 'wo... | 18,865 | 46.047382 | 129 | py |
OpusFilter | OpusFilter-master/tests/test_util.py | import json
import logging
import os
import shutil
import tempfile
import unittest
from opusfilter import ConfigurationError
from opusfilter.util import *
class TestCheckArgsCompability(unittest.TestCase):
def test_value(self):
newvalue = check_args_compability(1, required_types=[int])
self.asse... | 3,195 | 38.95 | 96 | py |
OpusFilter | OpusFilter-master/tests/test_yaml.py | import json
import logging
import os
import shutil
import tempfile
import unittest
from opusfilter.opusfilter import OpusFilter
from opusfilter.util import *
class TestYAML(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tempdir... | 2,188 | 20.048077 | 81 | py |
OpusFilter | OpusFilter-master/tests/test_filter_pipeline.py | import copy
import unittest
from opusfilter.pipeline import FilterPipeline
class TestFilterPipeline(unittest.TestCase):
@classmethod
def setUpClass(self):
self.config = [
{'LengthFilter': {'min_length': 1, 'max_length': 100,
'unit': 'word'}},
{'Len... | 7,761 | 40.731183 | 82 | py |
OpusFilter | OpusFilter-master/tests/test_wordalign_filter.py |
import argparse
import json
import logging
import os
import tempfile
import unittest
from opusfilter import word_alignment, OpusFilterRuntimeError
@unittest.skipIf(os.environ.get('EFLOMAL_PATH') is None, 'EFLOMAL_PATH not defined in environment')
class TestAlignFilter(unittest.TestCase):
def test_scoring(self)... | 6,505 | 43.258503 | 116 | py |
OpusFilter | OpusFilter-master/tests/test_classifier.py | import doctest
import logging
import os
import shutil
import tempfile
import unittest
import json
import pandas as pd
from opusfilter.classifier import *
example_data = [
{"CharacterScoreFilter": [1, 1], "LanguageIDFilter": {"cld2": [1, 1], "langid": [1, 1]}, "LongWordFilter": 1},
{"CharacterScoreFilter": [... | 10,704 | 43.604167 | 126 | py |
OpusFilter | OpusFilter-master/tests/test_opusfilter.py | import copy
import json
import logging
import os
import requests
import shutil
import tempfile
import unittest
from argparse import Namespace
from unittest import mock
from opustools import OpusGet
from opusfilter import ConfigurationError
from opusfilter.opusfilter import OpusFilter, ParallelWrapper
from opusfilter.... | 63,720 | 47.679144 | 127 | py |
OpusFilter | OpusFilter-master/tests/test_segment_hash.py | import itertools
import logging
import unittest
from opusfilter.segment_hash import SegmentHasher
class TestFilterPipeline(unittest.TestCase):
segment = "aa " * 10
segment_different_char = "bb " * 10
segment_different_len = "aa " * 11
segment_duplicate = "aa " * 10
segment_uppercase = "AA " * 10... | 4,749 | 37.617886 | 92 | py |
OpusFilter | OpusFilter-master/tests/test_tokenization.py | import logging
import unittest
from opusfilter import tokenization, ConfigurationError
try:
import jieba
except ImportError:
logging.warning("Could not import jieba")
try:
import MeCab
except ImportError:
logging.warning("Could not import MeCab")
class TestTokenization(unittest.TestCase):
def ... | 4,637 | 44.029126 | 105 | py |
OpusFilter | OpusFilter-master/tests/test_subwords.py | import logging
import tempfile
import unittest
from opusfilter import subwords, ConfigurationError
class TestBPESegmentation(unittest.TestCase):
data = ['koira jahtasi kissaa',
'kissa kiipesi puuhun',
'puu huojui tuulessa',
'koira haukkui maassa ja kissa sähisi puussa',
... | 1,827 | 37.893617 | 109 | py |
OpusFilter | OpusFilter-master/tests/test_lm_filter.py |
import argparse
import logging
import os
import tempfile
import unittest
from opusfilter import lm, subwords, OpusFilterRuntimeError, ConfigurationError
try:
import varikn
except ImportError:
logging.warning("Could not load varikn, language model filtering not supported")
class TestLMTokenizer(unittest.T... | 12,116 | 41.367133 | 131 | py |
OpusFilter | OpusFilter-master/tests/test_embeddings.py | import logging
import os
import pickle
import requests
import shutil
import tempfile
import unittest
from opusfilter import ConfigurationError
from opusfilter.embeddings import *
try:
import laserembeddings
except ImportError:
logging.warning("Could not load laserembeddings, LASER filtering not supported")
... | 3,314 | 38.939759 | 114 | py |
OpusFilter | OpusFilter-master/docs/conf.py | from pkg_resources import get_distribution
from pybtex.style.formatting.unsrt import Style as UnsrtStyle
from pybtex.style.labels import BaseLabelStyle
from pybtex.plugin import register_plugin
# General information about the project.
project = "OpusFilter"
author = "Helsinki-NLP"
language = "en"
# The full version,... | 1,418 | 23.465517 | 65 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/util_for_bert.py | import jieba
import torch
import pandas as pd
from torch.utils.data import DataLoader,Dataset
from gensim.models import word2vec
import json
import re
from how_net import is_sememe
import args
from tqdm import tqdm
from args import *
def load_word_vocab():
path ='data/chinese/bq_corpus/word_vocab.txt'
vocab = ... | 2,812 | 31.333333 | 80 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/hownet_bert.py | import torch
import math
import torch.nn as nn
import torch.optim as optim
import args
from numpy import *
from util_for_bert import *
from tqdm import tqdm_notebook, tqdm
from torch.nn import functional as F
from sklearn import metrics
from torch.optim.lr_scheduler import ExponentialLR, MultiStepLR
import numpy as np
... | 11,154 | 38.556738 | 118 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/Pre-processing.py | import jieba
import torch
import pandas as pd
from torch.utils.data import DataLoader,Dataset
from gensim.models import word2vec
import json
import re
from how_net import is_sememe
import args
from tqdm import tqdm
from args import *
def load_word_vocab():
path ='data/chinese/AFQMC/word_vocab.txt'
vocab = [lin... | 4,059 | 33.40678 | 147 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/util_for_BQ.py | import jieba
import torch
import pandas as pd
from torch.utils.data import DataLoader,Dataset
from gensim.models import word2vec
import json
import re
from how_net import is_sememe
import args
from tqdm import tqdm
from args import *
import pickle
def load_word_vocab():
path ='data/chinese/bq_corpus/word_vocab.txt... | 4,742 | 33.369565 | 112 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/args.py | max_len = 100
embedding_dim = 300
batch_size = 2
hidden_dim = 128
vocab_size = 46682
class_size = 2
dropout = 0.5
epoch = 1000 | 126 | 14.875 | 19 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/how_net.py | import OpenHowNet
import jieba
# OpenHowNet.download()
hownet = OpenHowNet.HowNetDict()
def is_sememe(word1,word2):
result_list = hownet.get_sememes_by_word(word1)
res = []
for i in range(len(result_list)):
for j in result_list[i]['sememes'][:]:
if j.zh not in res:
res.ap... | 1,203 | 27 | 60 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/hownet.py | import torch
import math
import torch.nn as nn
import torch.optim as optim
import args
from numpy import *
from util_for_BQ import *
from tqdm import tqdm_notebook,tqdm
from torch.nn import functional as F
from sklearn import metrics
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def length... | 7,787 | 38.135678 | 127 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/data/chinese/paws-x-zh/123.py | import jieba
import pandas as pd
sent = []
f = f = open('train.txt','r',encoding='utf8')
# f = pd.read_csv('train.tsv',delimiter='\t',header=0).values
ff = f.readlines()
for i in ff:
l = i.split('\t')
sent.append(l[0])
sent.append(l[1])
f = open('test.txt','r',encoding='utf8')
ff = f.readlines()
for i i... | 792 | 19.333333 | 61 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/data/chinese/paws-x-zh/456.py | with open('train_hn.txt','r',encoding='utf8') as f:
hn = f.readlines()
sent1 = []
sent2 = []
label = []
for i in hn:
s = i.rstrip().split('\t')
sent1.append(s[0])
sent2.append(s[1])
label.append(s[2])
f2 = open('train.txt','r',encoding='utf8')
ff = f2.readlines()
for i in ff:
l = i.rstrip().spl... | 554 | 24.227273 | 57 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/data/chinese/bq_corpus/123.py | import jieba
import pandas as pd
sent = []
f = f = open('train.txt','r',encoding='utf8')
# f = pd.read_csv('train.tsv',delimiter='\t',header=0).values
ff = f.readlines()
for i in ff:
l = i.split('\t')
sent.append(l[0])
sent.append(l[1])
f = open('test.txt','r',encoding='utf8')
ff = f.readlines()
for i i... | 792 | 19.333333 | 61 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/data/chinese/AFQMC/json_to_txt.py | import json
ff = open('test.json','r',encoding='utf8')
data = ff.readlines()
ans = []
for i in data:
d = json.loads(i)
sent1 = d['sentence1']
sent2 = d['sentence2']
# label = d['label']
res = sent1 + '\t' + sent2 + '\t'
ans.append(res)
for i in ans:
with open('test.txt','a',encoding='utf8')... | 355 | 21.25 | 52 | py |
sememes_codriven_text_matching | sememes_codriven_text_matching-main/data/chinese/AFQMC/123.py | import jieba
import pandas as pd
sent = []
f = f = open('train.txt','r',encoding='utf8')
# f = pd.read_csv('train.tsv',delimiter='\t',header=0).values
ff = f.readlines()
for i in ff:
l = i.split('\t')
sent.append(l[0])
sent.append(l[1])
f = open('test.txt','r',encoding='utf8')
ff = f.readlines()
for i i... | 792 | 19.333333 | 61 | py |
mmkb | mmkb-master/download-images.py | """
Download and preprocess images for the ImageGraph dataset.
Before running this script, please download the URL lists from
https://github.com/nle-ml/mmkb and unpack. Images will (by defaul) be stored as
`image-graph_images/{freebase-id}/{provider}_{index}.jpg`. All images will be
converted to jpg and rescaled to a ... | 5,660 | 41.56391 | 200 | py |
EOS | EOS-main/cifar_FE.py | import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from sklearn.metrics import accuracy_score
from sklearn.metrics import balanced_accura... | 12,215 | 32.105691 | 96 | py |
EOS | EOS-main/losses.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def focal_loss(input_values, gamma):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return l... | 3,252 | 30.582524 | 101 | py |
EOS | EOS-main/resnet_cifar_FE.py | '''
Properly implemented ResNet for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the web is copy-paste from
torchvision's resnet and has wron... | 5,692 | 31.718391 | 120 | py |
EOS | EOS-main/linear_sm.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn import Parameter
class Lin(nn.Module):
def __init__(self):
super(Lin, self).__init__()
self.linear = nn.Linear(64, 10)
def forward(self, x):
... | 375 | 14.04 | 39 | py |
EOS | EOS-main/EOS.py | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
from sklearn.neighbors import KNeighborsClassifier
np.set_printoptions(precision=7, threshold=20000,suppress=True)
##################################################################
#hyper-parameters
#numbe... | 4,413 | 21.180905 | 74 | py |
EOS | EOS-main/cifar_train_os.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import argparse
import os
import random
import time
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.dat... | 26,091 | 33.65073 | 141 | py |
EOS | EOS-main/utils.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import torch
import shutil
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
class ImbalancedDatasetSampler(to... | 5,820 | 31.519553 | 97 | py |
EOS | EOS-main/cifar_train.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import argparse
import os
import random
import time
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datas... | 25,808 | 35.147059 | 141 | py |
EOS | EOS-main/imbalance_cifar.py | """
code adapted from: https://github.com/kaidic/LDAM-DRW
"""
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import pandas as pd
torch.cuda.manual_seed(0)
class IMBALANCECIFAR10(torchvision.datasets.CIFAR10):
cls_num = 10
torch.cuda.manual_seed(0)
def __init... | 3,529 | 34.3 | 98 | py |
EOS | EOS-main/resnet_cifar.py | '''
code adapted from: https://github.com/kaidic/LDAM-DRW
Properly implemented ResNet for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the we... | 5,614 | 32.622754 | 120 | py |
EOS | EOS-main/reassemble.py | import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from sklearn.metrics import accuracy_score
from losses import LDAMLoss, FocalLoss, AS... | 13,195 | 29.759907 | 96 | py |
knodle-develop | knodle-develop/update_version_from_tag.py | import sys
import re
tag = sys.argv[1]
version_pattern = re.compile("\d+(.\d+)+(.(dev|post)\d+)?")
version = re.search(version_pattern, tag).group()
with open("knodle/version.py", "w") as fp:
fp.writelines([
"# this is an auto-generated file on release\n",
f"__version__ = '{version}'\n"
]) | 316 | 25.416667 | 59 | py |
knodle-develop | knodle-develop/setup.py | import io
import os
import re
from typing import Dict
from setuptools import find_packages
from setuptools import setup
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding="utf-8") as fd:
return re.sub(te... | 1,773 | 30.122807 | 87 | py |
knodle-develop | knodle-develop/examples/utils.py | import os
from typing import Union, List, Tuple
import pandas as pd
import numpy as np
from joblib import load
def read_train_dev_test(
target_path: str, if_dev_data: bool = False
) -> Union[Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray, np.ndarray],
Tuple[pd.DataFrame, No... | 1,721 | 44.315789 | 120 | py |
knodle-develop | knodle-develop/examples/__init__.py | 0 | 0 | 0 | py | |
knodle-develop | knodle-develop/examples/trainer/preprocessing.py | from typing import List, Union, Tuple
from joblib import dump
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from torch.utils.data import TensorDataset
def get_tfidf_features(
train_data: List, test_data: List = None, dev_data: List = None, path_to_cache: str = None,
... | 2,606 | 43.186441 | 112 | py |
knodle-develop | knodle-develop/examples/trainer/__init__.py | 0 | 0 | 0 | py | |
knodle-develop | knodle-develop/examples/trainer/cleanlab/cleanlab_training_tutorial.py | import argparse
import os
import statistics
import sys
import json
from itertools import product
from torch import Tensor, LongTensor
from torch.nn import CrossEntropyLoss
from torch.optim import Adam
from torch.utils.data import TensorDataset
from examples.trainer.preprocessing import get_tfidf_features
from example... | 4,080 | 36.787037 | 120 | py |
knodle-develop | knodle-develop/examples/trainer/simple_auto_trainer/auto_trainer_tutorial.py | import os
from typing import List
from tqdm.auto import tqdm
import joblib
from minio import Minio
import pandas as pd
import numpy as np
import scipy.sparse as sp
import torch
from torch.utils.data import TensorDataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW
from examples... | 3,496 | 29.146552 | 105 | py |
knodle-develop | knodle-develop/examples/trainer/simple_auto_trainer/multi_trainer_tutorial.py | import os
from torch import Tensor
from tqdm.auto import tqdm
import joblib
from minio import Minio
import pandas as pd
import numpy as np
import scipy.sparse as sp
import torch
from torch.utils.data import TensorDataset
from transformers import AdamW
from examples.trainer.preprocessing import get_tfidf_features
fr... | 3,491 | 31.333333 | 105 | py |
knodle-develop | knodle-develop/examples/trainer/simple_auto_trainer/__init__.py | 0 | 0 | 0 | py | |
knodle-develop | knodle-develop/examples/trainer/[WIP]_baseline/baseline_training_example.py | import logging
import os
from torch import Tensor
from torch.optim import SGD
from torch.utils.data import TensorDataset
from knodle.data.download import MinioConnector
from knodle.model.logistic_regression_model import (
LogisticRegressionModel,
)
from examples.ImdbDataset.utils import init_logger
from examples... | 2,507 | 29.962963 | 109 | py |
knodle-develop | knodle-develop/examples/trainer/[WIP]_baseline/bert/__init__.py | 0 | 0 | 0 | py | |
knodle-develop | knodle-develop/examples/trainer/wscrossweigh/wscrossweigh_training_tutorial.py | import argparse
import os
import sys
import joblib
import pandas as pd
from minio import Minio
from torch import Tensor, LongTensor
from torch.optim import Adam
from torch.utils.data import TensorDataset
from tqdm import tqdm
from transformers import DistilBertTokenizer, DistilBertForSequenceClassification, AdamW
from... | 7,220 | 48.122449 | 129 | py |
knodle-develop | knodle-develop/examples/trainer/wscrossweigh/wscrossweigh_training_with_BiLSTM_tutorial.py | import argparse
import os
import sys
from typing import Dict
import numpy as np
import pandas as pd
import torch
from torch import Tensor, LongTensor
from torch.optim import Adam
from torch.utils.data import TensorDataset
from knodle.evaluation.other_class_metrics import score
from knodle.model.bidirectional_lstm_mod... | 8,183 | 40.125628 | 120 | py |
knodle-develop | knodle-develop/examples/trainer/wscrossweigh/__init__.py | 0 | 0 | 0 | py | |
knodle-develop | knodle-develop/examples/data_preprocessing/utils.py | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 5 15:32:31 2021
@author: Emilie
"""
import numpy as np
from typing import Dict
def get_mapping_rules_labels_t(rule2label: Dict, num_classes: int) -> np.ndarray:
""" Function calculates t matrix (rules x labels) using the known correspondence of relations to decisio... | 528 | 32.0625 | 119 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.