-
-
Notifications
You must be signed in to change notification settings - Fork 50.2k
Add tfidf #14407
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
Open
yacinemebarki
wants to merge
3
commits into
TheAlgorithms:master
Choose a base branch
from
yacinemebarki:add-tfidf
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add tfidf #14407
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
fdaf4bf
implimenting tfidf using just python and numpy under feature extraction
yacinemebarki f88e0ac
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] eed9873
implimenting tfidf using just python and numpy under feature extraction
yacinemebarki 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,97 @@ | ||
| import numpy as np | ||
|
Check failure on line 1 in machine_learning/feature_extraction/tfidf.py
|
||
| import re | ||
| # to seprate words and normlize it | ||
|
|
||
|
|
||
| def decompose(text): | ||
| text = text.lower() | ||
| text = re.sub(r"[^a-z0-9\s]", "", text) | ||
| text = re.sub(r"\s+", " ", text) | ||
|
|
||
| return text.split() | ||
|
|
||
|
|
||
| # creating tfidf class | ||
| class TfIdfVectorizer: | ||
| def __init__(self): | ||
yacinemebarki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.vocab = None | ||
| self.idf = None | ||
|
|
||
| # these method to compute the tf for each word in given data | ||
| def compute_tf(self, data): | ||
yacinemebarki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| tf = [] | ||
| doc_words = [] | ||
|
|
||
| for document in data: | ||
| words = decompose(document) | ||
|
|
||
| freq = {} # these dictionerie have for each unique words it number of apprition in one sentence | ||
|
|
||
| for word in words: | ||
| freq[word] = freq.get(word, 0) + 1 | ||
|
|
||
| if word not in doc_words: | ||
| doc_words.append(word) | ||
|
|
||
| # calculating tf | ||
|
|
||
| for word in freq: | ||
| freq[word] /= len(words) | ||
|
|
||
| tf.append(freq) | ||
|
|
||
| # computing idf | ||
| idf = {} | ||
|
|
||
| n = len(data) | ||
|
|
||
| for word in doc_words: | ||
| df = sum(1 for doc in tf if word in doc) | ||
| idf[word] = np.log((n + 1) / (1 + df)) + 1 | ||
|
|
||
| self.idf = idf | ||
| tfidf = [] | ||
|
|
||
| self.idf = idf | ||
|
|
||
| # computing tfidf for each word | ||
|
|
||
| for doc_tf in tf: | ||
| vector = [doc_tf.get(word, 0) * idf[word] for word in doc_words] | ||
| tfidf.append(vector) | ||
|
|
||
| self.vocab = doc_words | ||
|
|
||
| return np.array(tfidf, dtype=float) | ||
|
|
||
| def encode(self, data): | ||
yacinemebarki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if self.vocab is None or self.idf is None: | ||
| raise ValueError("You should fit the model first") | ||
|
|
||
| tfidf_matrix = [] | ||
| for doc in data: | ||
| words = decompose(doc) | ||
| freq = {} | ||
|
|
||
| # Count term frequencies for words that exist in the vocabulary | ||
| for word in words: | ||
| if word in self.vocab: | ||
| freq[word] = freq.get(word, 0) + 1 | ||
|
|
||
| # Normalize TF by document length | ||
| for word in freq: | ||
| freq[word] /= len(words) | ||
|
|
||
| # Align vector according to vocab and multiply by IDF | ||
| vector = [freq.get(word, 0) * self.idf[word] for word in self.vocab] | ||
| tfidf_matrix.append(vector) | ||
|
|
||
| return np.array(tfidf_matrix, dtype=float) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| documents = ["the cat sat on the mat", "the dog chased the cat"] | ||
| vectorizer = TfIdfVectorizer() | ||
| tfidf_matrix = vectorizer.compute_tf(documents) | ||
| print("Vocabulary:", vectorizer.vocab) | ||
| print("TF-IDF Matrix:\n", tfidf_matrix) | ||
Oops, something went wrong.
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.