MinHash, LSH, LSH Forest, Weighted MinHash, HyperLogLog, HyperLogLog++, LSH Ensemble

Overview

datasketch: Big Data Looks Small

datasketch gives you probabilistic data structures that can process and search very large amount of data super fast, with little loss of accuracy.

This package contains the following data sketches:

Data Sketch Usage
MinHash estimate Jaccard similarity and cardinality
Weighted MinHash estimate weighted Jaccard similarity
HyperLogLog estimate cardinality
HyperLogLog++ estimate cardinality

The following indexes for data sketches are provided to support sub-linear query time:

Index For Data Sketch Supported Query Type
MinHash LSH MinHash, Weighted MinHash Jaccard Threshold
MinHash LSH Forest MinHash, Weighted MinHash Jaccard Top-K
MinHash LSH Ensemble MinHash Containment Threshold

datasketch must be used with Python 2.7 or above and NumPy 1.11 or above. Scipy is optional, but with it the LSH initialization can be much faster.

Note that MinHash LSH and MinHash LSH Ensemble also support Redis and Cassandra storage layer (see MinHash LSH at Scale).

Install

To install datasketch using pip:

pip install datasketch

This will also install NumPy as dependency.

To install with Redis dependency:

pip install datasketch[redis]

To install with Cassandra dependency:

pip install datasketch[cassandra]

To install with Scipy for faster MinHashLSH initialization:

pip install datasketch[scipy]
Comments
  • Redis backend for datasketch LSH

    Redis backend for datasketch LSH

    Summary

    We have been using datasketch extensively in data-driven applications (primarily the MinHashLSH class). The existing implementation requires all data to be stored in memory, which is a severe limitation for very large datasets. We add support for a Redis backend. Default behavior remains in-memory storage.

    Changes

    • Redis backend for MinHashLSH
    • Insertion session for bulk insertion (reduces network calls when inserting with a Redis backend)
    • Functionality to view LSH bucket sizes (useful for diagnosis/debugging)
    • Accompanying docs and tests

    Examples

    For examples, see the additions to the documentation.

    opened by ae-foster 25
  • Add Cassandra storage layer

    Add Cassandra storage layer

    This is a storage layer that uses Cassandra as a backend. It is optimized to take into account Cassandra internals and its (intrinsic) limitations (see for example how all the keys are retrieved and how the list abstraction is implemented). I have also added a new batch of tests to both TestMinHashLSH and TestWeightedMinHashLSH. Since Cassandra is required (Cassandra is not mocked) they can be enabled by flipping the DO_TEST_CASSANDRA variable.

    opened by ostefano 18
  • Implement #123 arbitrary Mongo URL & collection name

    Implement #123 arbitrary Mongo URL & collection name

    I have also updated the documentation a bit.

    The purpose of the function AsyncIOMotorClient.get_default_database is to allow for the Mongo URL to define a database. If the URL contains a database, that database in the URL will be used, otherwise, the calculated database name is used. As for get_collection, I changed it for consistency only.

    I wanted to update the unit tests, but they were skipped… and when I tried to un-skip them everything failed spetacularly. I'm not sure what to do about that.

    Cheers!

    opened by ekevoo 14
  • Easy computation of all duplicates?

    Easy computation of all duplicates?

    Thanks for this library!

    One question: Is there an easy way to get all pairs from a LSH? In other words, instead of a query for a single minhash, I need all pairs of records inside a same bucket.

    I tried to dive into the code, but I didn't understand very well how hashranges/hashtables work. What I need is similar to candidate_duplicates of this other implementation: https://mattilyra.github.io/2017/05/23/document-deduplication-with-lsh.html

    opened by fjsj 14
  • Performance improvements

    Performance improvements

    I've made some performance improvements in the MinHash class and added a helper method for bulk computation.

    1. Precasting _mersenne_prime and _max_hash, they don't need to be cast multiple times.
    2. I've modified the update method to accept a list of bytes so hash values can be computed in batches. This avoids using for loops in python space and packs all those operations into the numpy calls once. Only caveat here is that the matrix operations use more memory and you should do chunking if you're dealing with huge sets.
    3. The bulk helper removes unnecessary initialization overhead of the permutations and initial hashvalues. They are computed once then passed on to new MinHash objects as they are produced.

    These changes give some pretty nice performance improvements, up to 3X for updates, and anywhere from 5-25X for bulk computing. See my benchmark gist here

    opened by Sinusoidal36 10
  • AsyncMinhashLSH doesn't use index key with mongodb backend, and hence is very slow.

    AsyncMinhashLSH doesn't use index key with mongodb backend, and hence is very slow.

    We'd struggled with AsyncMinhashLSH's query performance, eventually finding out it wasn't using the default collection index key ('_id'), and instead querying by it's 'key' field. (see: here )

    This can either be fixed by inserting into the collections with primary key '_id', or else creating indices on the 'key' field for all collections in the database.

    For anyone looking for the quickfix solution, simply run:

    db.lsh_...._bucket_#.createIndex( { key: -1 } )

    on each of the buckets and key collections in the database. We found performance went from 11 seconds/ query to >1ms/ query pretty much instantly.

    I believe this should be added to the documentation somewhere, or fixed in the code (although it'd break existing databases). I'd volunteer to do either!

    opened by oisincar 8
  • add ability to set storage basename

    add ability to set storage basename

    If you are connecting to a redis database and you lose the reference to the connection, you will lose reference to all data in your hash and you also lose the ability to remove it. By having the ability to set the base name, you can alway reference the same keys no matter if you create a new connection or use the old one.

    opened by KevinMann13 8
  • how to restore minhashes from MinHashLSH with redis backend?

    how to restore minhashes from MinHashLSH with redis backend?

    I what to find duplicates,so I need pop a hash then compare left hashes.

    or should I make a copy of original data to redis? or just not use the redis storge wait the dataset feed up then use MinHashLSH

    opened by bung87 8
  • Persistent storage on MongoDB

    Persistent storage on MongoDB

    Hi guys,

    Question, I'd like to store a MinHashLSH on a Mongo-db instance. I've seen you have Redis & Cassandra as storage-types in the code; is there an easy way for me to store in on mongo as well?

    Greets Tb

    opened by blah-crusader 7
  • Combining/Storing LSH with different thresholds

    Combining/Storing LSH with different thresholds

    Hi,

    First of all thanks for this amazing package. I have two LSH, one optimized with a threshold of 0.65 and the other with a threshold of 0.55. I found the results from both these LSH are relevant to me, and I would finally take a union of the results of both of these, and get my duplicate contents.

    In order to store both LSH, I'm using Redis caching mechanism, but later I will have to call both the LSH, run individually and take the union of the results.

    Is there any way I could optimize so that I could do the same with only one LSH if possible or some method to create a special type of indexes in Redis such that I don't have to call the LSH's Individually. This would help me save Memory and Computational Time.

    opened by thakur-nandan 7
  • Question: Setting Expiry Time for Entries in Redis LSH?

    Question: Setting Expiry Time for Entries in Redis LSH?

    Hi,

    First of all thanks for this great library :)

    I wanted to know if there is any way to set an expiry time for entries being added into an LSH connected to Redis? Or any way to keep a default expiry time for all keys?

    Should I instead set a maxmemory policy for my Redis with an allkeys-lru or allkeys-random eviction policy? Is this recommended or will it cause issues with the LSH?

    Regards, Spandan

    opened by SpandanThakur 7
  • Support numpy>=1.20.0

    Support numpy>=1.20.0

    numpy.int was only ever an alias for the built-in, and is now deprecated from version 1.20.0

    See: https://numpy.org/doc/stable/release/1.20.0-notes.html#using-the-aliases-of-builtin-types-like-np-int-is-deprecated

    opened by joehalliwell 0
  • Given a minHash instance or minHash LSH , How to find most unsimilar instance with an existed minHash LSH?

    Given a minHash instance or minHash LSH , How to find most unsimilar instance with an existed minHash LSH?

    In API document , we can learn how to find approximate neighbours with Jaccard similarity more than threshold . On the other hand, how to find most unsimilar instance. Further, given a minHash LSH which initialized by thousands of plain text - set A, and given other thousands of plain text - set B, how to discover most unsimilar text of set B with set A , or how to discover text of set B which jaccard similarity less than threshold . Is there as possible as fast solution to deal with this problem ? Thanks !

    opened by loulianzhang 2
  • Getting `pymongo.errors.ExecutionTimeout`  for using more than 1 instance of AsyncMinHashLSH

    Getting `pymongo.errors.ExecutionTimeout` for using more than 1 instance of AsyncMinHashLSH

    I have a use case where i have to store min hash of (n) different categories of file and the query them. For example if i have documents of category A and I want to store all of them in one db and then query at later point.

    I am initializing this in a microservice as (fastapi) as follows

    @app.on_event("startup")
    async def startup_event():
        LSHService.lsh_js, LSHService.lsh_css, LSHService.lsh_html, = await asyncio.gather(
            *[
                await AsyncMinHashLSH(
                    storage_config={
                        **_storage,
                        "basename": "category-a".encode(),
                    },
                    threshold=0.9,
                    num_perm=256,
                ),
                await AsyncMinHashLSH(
                    storage_config={
                        **_storage,
                        "basename": "category-b".encode(),
                    },
                    threshold=0.9,
                    num_perm=256,
                ),
                await AsyncMinHashLSH(
                    storage_config={
                        **_storage,
                        "basename": "category-b".encode(),
                    },
                    threshold=0.9,
                    num_perm=256,
                ),
            ]
        )
    

    If i initialize like this i get
    Getting pymongo.errors.ExecutionTimeout Error

    However If i just maintain 1 object then I dont get any error.

    What can I do mitigate this? Thanks in advance

    opened by RonaldRegan69 3
  • Question: Why getting a min-hash for a single sample is possible?

    Question: Why getting a min-hash for a single sample is possible?

    Say if we have three documents A, B and C. Each document might contains different words.

    According to the document of data sketch.MinHash, we can get a min-hash for A with

    minxish = Minhash(num_perm=128) minhash.update(A.encode('utf-8')) vector = minhash.digest()

    But isn't that we need to create a vocabulary consisting of all words from A, B and C before getting the vector?

    opened by bdeng3 2
Releases(v1.5.8)
  • v1.5.8(Aug 21, 2022)

    What's Changed

    • Add GitHub URL for PyPi by @andriyor in https://github.com/ekzhu/datasketch/pull/179
    • Support asyncio redis by @long2ice in https://github.com/ekzhu/datasketch/pull/185
    • Fix name construction for all values of b by @SenadI in https://github.com/ekzhu/datasketch/pull/190

    New Contributors

    • @andriyor made their first contribution in https://github.com/ekzhu/datasketch/pull/179
    • @long2ice made their first contribution in https://github.com/ekzhu/datasketch/pull/185
    • @SenadI made their first contribution in https://github.com/ekzhu/datasketch/pull/190

    Full Changelog: https://github.com/ekzhu/datasketch/compare/v1.5.7...v1.5.8

    Source code(tar.gz)
    Source code(zip)
  • v1.5.7(Feb 4, 2022)

    What's Changed

    • Unable to create multiple lsh indices each one in its own keyspace - issue #171 by @ronassa in https://github.com/ekzhu/datasketch/pull/172

    New Contributors

    • @ronassa made their first contribution in https://github.com/ekzhu/datasketch/pull/172

    Full Changelog: https://github.com/ekzhu/datasketch/compare/v1.5.6...v1.5.7

    Source code(tar.gz)
    Source code(zip)
  • v1.5.6(Dec 27, 2021)

  • v1.5.5(Dec 16, 2021)

    What's Changed

    • Adding minhash_many to WeightedMinHashGenerator. by @jroose-jv in https://github.com/ekzhu/datasketch/pull/165
    • Add query buffer by @hguhlich in https://github.com/ekzhu/datasketch/pull/167

    New Contributors

    • @jroose-jv made their first contribution in https://github.com/ekzhu/datasketch/pull/165
    • @hguhlich made their first contribution in https://github.com/ekzhu/datasketch/pull/167

    Full Changelog: https://github.com/ekzhu/datasketch/compare/v1.5.4...v1.5.5

    Source code(tar.gz)
    Source code(zip)
  • v1.5.4(Dec 4, 2021)

    What's Changed

    • Fixes #146; MinhashLSH creates mongo index key. by @oisincar in https://github.com/ekzhu/datasketch/pull/148
    • Add redis_buffer configuration. by @QthCN in https://github.com/ekzhu/datasketch/pull/152
    • minhash: Get rid of deprecation warning by @xkubov in https://github.com/ekzhu/datasketch/pull/156

    New Contributors

    • @oisincar made their first contribution in https://github.com/ekzhu/datasketch/pull/148
    • @QthCN made their first contribution in https://github.com/ekzhu/datasketch/pull/152
    • @xkubov made their first contribution in https://github.com/ekzhu/datasketch/pull/156

    Full Changelog: https://github.com/ekzhu/datasketch/compare/1.5.2...v1.5.4

    Source code(tar.gz)
    Source code(zip)
  • 1.5.2(Dec 15, 2020)

    • Performance improvement for MinHash's update method.
    • Make MinHash updates 4.5X faster by using update_batch method for bulk update on MinHash. [See API doc].(http://ekzhu.com/datasketch/documentation.html#datasketch.MinHash.update_batch)
    • Further performance gain by using bulk generation of MinHash using MinHash.bulk or MinHash.generator. See API doc and pull request.
    • Optional compression for MinHash LSH index by hashing the bucket key produced by MinHashLSH._H. See pull request. This leads to saving of memory/storage space used by the index.

    Thank you @Sinusoidal36!

    Source code(tar.gz)
    Source code(zip)
  • v1.5.0(Nov 26, 2019)

    • Minor bug fixes
    • Cassandra storage layer, thank @ostefano! Now you can specify the Cassandra config just like the Redis one.
    from datasketch import MinHashLSH
    
    lsh = MinHashLSH(
        threashold=0.5, num_perm=128, storage_config={
            'type': 'cassandra',
            'cassandra': {
                'seeds': ['127.0.0.1'],
                'keyspace': 'lsh_test',
                'replication': {
                    'class': 'SimpleStrategy',
                    'replication_factor': '1',
                },
                'drop_keyspace': False,
                'drop_tables': False,
            }
        }
    )
    
    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Jan 6, 2019)

    Now support hashfunc parameter for MinHash and HyperLogLog. The old parameter hashobj is removed.

    # Let's use MurmurHash3.
    import mmh3
    
    # We need to define a new hash function that outputs an integer that
    # can be encoded in 32 bits.
    def _hash_func(d):
        return mmh3.hash32(d)
    
    # Use this function in MinHash constructor.
    m = MinHash(hashfunc=_hash_func)
    
    Source code(tar.gz)
    Source code(zip)
  • v.1.3.0(Dec 27, 2018)

  • v1.2.10(Nov 2, 2018)

    • Adding batch removal functionality for Async MinHashLSH
    • Because Redis does not support async operation, removed Redis support from Async MinHashLSH

    For details see Pull #70 Thanks @aastafiev for the contribution.

    Source code(tar.gz)
    Source code(zip)
  • v1.2.9(Oct 22, 2018)

  • v1.2.7(Jul 27, 2018)

    • Added Asynchronous MinHash LSH module. Thanks @aastafiev!
    • Added ability to set the base name in storage config. Base name is used as the prefix for generating keys in the underlying storage (e.g., Redis). This change allows client to "reconnect" to an existing LSH index in the storage through its base name.
    Source code(tar.gz)
    Source code(zip)
  • v1.2.6(Jul 21, 2018)

  • v1.2.5(Nov 21, 2017)

  • v1.2.4(Nov 8, 2017)

  • v1.2.3(Sep 8, 2017)

  • v1.2.0(Mar 31, 2017)

  • v1.1.3(Mar 26, 2017)

    MinHash now uses Numpy's random number generator instead of Python's built-in random. This makes MinHash generate consistent hash values across different Python versions.

    The side-effect is that now MinHash created before version 1.1.3 won’t work (i.e., jaccard, merge and union) correctly with those created after.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Mar 15, 2017)

    • LeanMinHash is a subclass of MinHash. It uses less memory and allows faster (de)serialization. See documentation for details.
    • Removed serialize, deserialize, and bytesize methods from MinHash. These are supported in LeanMinHash instead.
    • Serialized MinHash objects before this version will not be deserialized properly. To migrate see here.
    • Documentation now have its own website!
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Feb 12, 2017)

    After nearly 2 years working on this project on-and-off, the API is now stable, and the features of MinHash-related sketches are completed.

    I will continue to add more data sketches and indexes.

    Source code(tar.gz)
    Source code(zip)
  • v0.2.6(Jan 7, 2017)

    • MinHash LSH Forest implementation and benchmark using synthetic data
    • Improve existing MinHash LSH benchmark using synthetic data for more tunable data distributions
    • Improve MinHash and LSH performance
    Source code(tar.gz)
    Source code(zip)
  • v0.2.4(Jul 10, 2016)

  • v0.2.3(Apr 12, 2016)

  • v0.2.1(Apr 12, 2016)

Born-Infeld (BI) for AI: Energy-Conserving Descent (ECD) for Optimization

Born-Infeld (BI) for AI: Energy-Conserving Descent (ECD) for Optimization This repository contains the code for the BBI optimizer, introduced in the p

G. Bruno De Luca 5 Sep 06, 2022
RIM: Reliable Influence-based Active Learning on Graphs.

RIM: Reliable Influence-based Active Learning on Graphs. This repository is the official implementation of RIM. Requirements To install requirements:

Wentao Zhang 4 Aug 29, 2022
Lipstick ain't enough: Beyond Color-Matching for In-the-Wild Makeup Transfer (CVPR 2021)

Table of Content Introduction Datasets Getting Started Requirements Usage Example Training & Evaluation CPM: Color-Pattern Makeup Transfer CPM is a ho

VinAI Research 248 Dec 13, 2022
ktrain is a Python library that makes deep learning and AI more accessible and easier to apply

Overview | Tutorials | Examples | Installation | FAQ | How to Cite Welcome to ktrain News and Announcements 2020-11-08: ktrain v0.25.x is released and

Arun S. Maiya 1.1k Jan 02, 2023
Official PyTorch implementation of our AAAI22 paper: TransMEF: A Transformer-Based Multi-Exposure Image Fusion Framework via Self-Supervised Multi-Task Learning. Code will be available soon.

Official-PyTorch-Implementation-of-TransMEF Official PyTorch implementation of our AAAI22 paper: TransMEF: A Transformer-Based Multi-Exposure Image Fu

117 Dec 27, 2022
3D dataset of humans Manipulating Objects in-the-Wild (MOW)

MOW dataset [Website] This repository maintains our 3D dataset of humans Manipulating Objects in-the-Wild (MOW). The dataset contains 512 images in th

Zhe Cao 28 Nov 06, 2022
[EMNLP 2021] MuVER: Improving First-Stage Entity Retrieval with Multi-View Entity Representations

MuVER This repo contains the code and pre-trained model for our EMNLP 2021 paper: MuVER: Improving First-Stage Entity Retrieval with Multi-View Entity

24 May 30, 2022
Train a deep learning net with OpenStreetMap features and satellite imagery.

DeepOSM Classify roads and features in satellite imagery, by training neural networks with OpenStreetMap (OSM) data. DeepOSM can: Download a chunk of

TrailBehind, Inc. 1.3k Nov 24, 2022
領域を指定し、キーを入力することで画像を保存するツールです。クラス分類用のデータセット作成を想定しています。

image-capture-class-annotation 領域を指定し、キーを入力することで画像を保存するツールです。 クラス分類用のデータセット作成を想定しています。 Requirement OpenCV 3.4.2 or later Usage 実行方法は以下です。 起動後はマウスクリック4

KazuhitoTakahashi 5 May 28, 2021
DualGAN-tensorflow: tensorflow implementation of DualGAN

ICCV paper of DualGAN DualGAN: unsupervised dual learning for image-to-image translation please cite the paper, if the codes has been used for your re

Jack Yi 252 Nov 10, 2022
[CVPR 2021] MetaSAug: Meta Semantic Augmentation for Long-Tailed Visual Recognition

MetaSAug: Meta Semantic Augmentation for Long-Tailed Visual Recognition (CVPR 2021) arXiv Prerequisite PyTorch = 1.2.0 Python3 torchvision PIL argpar

51 Nov 11, 2022
ColBERT: Contextualized Late Interaction over BERT (SIGIR'20)

Update: if you're looking for ColBERTv2 code, you can find it alongside a new simpler API, in the branch new_api. ColBERT ColBERT is a fast and accura

Stanford Future Data Systems 637 Jan 08, 2023
This repository is for our paper Exploiting Scene Graphs for Human-Object Interaction Detection accepted by ICCV 2021.

SG2HOI This repository is for our paper Exploiting Scene Graphs for Human-Object Interaction Detection accepted by ICCV 2021. Installation Pytorch 1.7

HT 10 Dec 20, 2022
This repository is for Contrastive Embedding Distribution Refinement and Entropy-Aware Attention Network (CEDR)

CEDR This repository is for Contrastive Embedding Distribution Refinement and Entropy-Aware Attention Network (CEDR) introduced in the following paper

phoenix 3 Feb 27, 2022
BuildingNet: Learning to Label 3D Buildings

BuildingNet This is the implementation of the BuildingNet architecture described in this paper: Paper: BuildingNet: Learning to Label 3D Buildings Arx

16 Nov 07, 2022
FEDn is an open-source, modular and ML-framework agnostic framework for Federated Machine Learning

FEDn is an open-source, modular and ML-framework agnostic framework for Federated Machine Learning (FedML) developed and maintained by Scaleout Systems. FEDn enables highly scalable cross-silo and cr

Scaleout 75 Nov 09, 2022
PaddlePaddle GAN library, including lots of interesting applications like First-Order motion transfer, wav2lip, picture repair, image editing, photo2cartoon, image style transfer, and so on.

English | 简体中文 PaddleGAN PaddleGAN provides developers with high-performance implementation of classic and SOTA Generative Adversarial Networks, and s

6.4k Jan 09, 2023
PyTorch implementation for Convolutional Networks with Adaptive Inference Graphs

Convolutional Networks with Adaptive Inference Graphs (ConvNet-AIG) This repository contains a PyTorch implementation of the paper Convolutional Netwo

Andreas Veit 176 Dec 07, 2022
Bayesian Deep Learning and Deep Reinforcement Learning for Object Shape Error Response and Correction of Manufacturing Systems

Bayesian Deep Learning for Manufacturing 2.0 (dlmfg) Object Shape Error Response (OSER) Digital Lifecycle Management - In Process Quality Improvement

Sumit Sinha 30 Oct 31, 2022
A modular domain adaptation library written in PyTorch.

A modular domain adaptation library written in PyTorch.

Kevin Musgrave 225 Dec 29, 2022