-
-
Notifications
You must be signed in to change notification settings - Fork 46.9k
add similarity_search.py in machine_learning #3864
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
40a6503
add similarity_search.py in machine_learning
SteveKimSR 09caa3b
fix pre-commit test, apply feedback
SteveKimSR 7ce2cce
apply feedback
SteveKimSR f38fb3e
apply feedback
SteveKimSR ebfe05a
apply feedback
SteveKimSR 2d2c6b8
# doctest: +NORMALIZE_WHITESPACE
cclauss 9637de7
Update machine_learning/similarity_search.py
cclauss 6f7c9ce
placate flake8
cclauss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
""" | ||
Similarity Search : https://en.wikipedia.org/wiki/Similarity_search | ||
Similarity search is a search algorithm for finding the nearest vector from | ||
vectors, used in natural language processing. | ||
In this algorithm, it calculates distance with euclidean distance and | ||
returns a list containing two data for each vector: | ||
1. the nearest vector | ||
2. distance between the vector and the nearest vector (float) | ||
""" | ||
import math | ||
|
||
import numpy as np | ||
|
||
|
||
def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: | ||
""" | ||
Calculates euclidean distance between two data. | ||
:param input_a: ndarray of first vector. | ||
:param input_b: ndarray of second vector. | ||
:return: Euclidean distance of input_a and input_b. By using math.sqrt(), | ||
result will be float. | ||
|
||
>>> euclidean(np.array([0]), np.array([1])) | ||
1.0 | ||
>>> euclidean(np.array([0, 1]), np.array([1, 1])) | ||
1.0 | ||
>>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) | ||
1.0 | ||
""" | ||
return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) | ||
|
||
|
||
def similarity_search(dataset: np.ndarray, value_array: np.ndarray) -> list: | ||
""" | ||
:param dataset: Set containing the vectors. Should be ndarray. | ||
:param value_array: vector/vectors we want to know the nearest vector from dataset. | ||
:return: Result will be a list containing | ||
1. the nearest vector | ||
2. distance from the vector | ||
|
||
>>> dataset = np.array([[0], [1], [2]]) | ||
>>> value_array = np.array([[0]]) | ||
>>> similarity_search(dataset, value_array) | ||
[[[0], 0.0]] | ||
|
||
>>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) | ||
>>> value_array = np.array([[0, 1]]) | ||
>>> similarity_search(dataset, value_array) | ||
[[[0, 0], 1.0]] | ||
|
||
>>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) | ||
>>> value_array = np.array([[0, 0, 1]]) | ||
>>> similarity_search(dataset, value_array) | ||
[[[0, 0, 0], 1.0]] | ||
|
||
>>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) | ||
>>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) | ||
>>> similarity_search(dataset, value_array) | ||
[[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] | ||
|
||
These are the errors that might occur: | ||
|
||
1. If dimensions are different. | ||
For example, dataset has 2d array and value_array has 1d array: | ||
>>> dataset = np.array([[1]]) | ||
>>> value_array = np.array([1]) | ||
>>> similarity_search(dataset, value_array) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 | ||
|
||
2. If data's shapes are different. | ||
For example, dataset has shape of (3, 2) and value_array has (2, 3). | ||
We are expecting same shapes of two arrays, so it is wrong. | ||
>>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) | ||
>>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) | ||
>>> similarity_search(dataset, value_array) | ||
Traceback (most recent call last): | ||
... | ||
ValueError: Wrong input data's shape... dataset : 2, value_array : 3 | ||
|
||
3. If data types are different. | ||
When trying to compare, we are expecting same types so they should be same. | ||
If not, it'll come up with errors. | ||
>>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) | ||
>>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) | ||
>>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE | ||
Traceback (most recent call last): | ||
... | ||
TypeError: Input data have different datatype... | ||
dataset : float32, value_array : int32 | ||
""" | ||
|
||
if dataset.ndim != value_array.ndim: | ||
raise ValueError( | ||
f"Wrong input data's dimensions... dataset : {dataset.ndim}, " | ||
f"value_array : {value_array.ndim}" | ||
) | ||
|
||
try: | ||
if dataset.shape[1] != value_array.shape[1]: | ||
raise ValueError( | ||
f"Wrong input data's shape... dataset : {dataset.shape[1]}, " | ||
f"value_array : {value_array.shape[1]}" | ||
) | ||
except IndexError: | ||
if dataset.ndim != value_array.ndim: | ||
raise TypeError("Wrong shape") | ||
|
||
if dataset.dtype != value_array.dtype: | ||
raise TypeError( | ||
f"Input data have different datatype... dataset : {dataset.dtype}, " | ||
f"value_array : {value_array.dtype}" | ||
) | ||
|
||
answer = [] | ||
|
||
for value in value_array: | ||
dist = euclidean(value, dataset[0]) | ||
vector = dataset[0].tolist() | ||
|
||
for dataset_value in dataset[1:]: | ||
temp_dist = euclidean(value, dataset_value) | ||
|
||
if dist > temp_dist: | ||
dist = temp_dist | ||
vector = dataset_value.tolist() | ||
|
||
answer.append([vector, dist]) | ||
|
||
return answer | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.