Skip to content
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

Create Vectorizer #1053

Merged
merged 1 commit into from
Jan 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions Vectorizer/You-Now-Who/Vectorizer
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

class CustomCountVectorizer {
constructor(lowercase = true, tokenPattern = /\b\w+\b/g) {
this.lowercase = lowercase;
this.tokenPattern = tokenPattern;
this.vocabulary = {};
}

fit(documents) {
this.vocabulary = {};
for (const doc of documents) {
let docText = doc;
if (this.lowercase) {
docText = doc.toLowerCase();
}
const tokens = docText.match(this.tokenPattern);
// console.log(tokens[0])
for (const token of tokens) {
if (!(token in this.vocabulary)) {
this.vocabulary[token] = Object.keys(this.vocabulary).length;
}
}
}
}

transform(documents) {
if (Object.keys(this.vocabulary).length === 0) {
throw new Error("You must fit the vectorizer before transforming data.");
}

const transformedData = [];

for (const doc of documents) {
let docText = doc;
if (this.lowercase) {
docText = doc.toLowerCase();
}
const tokens = docText.match(this.tokenPattern);

const docVector = Array.from({ length: Object.keys(this.vocabulary).length }, () => 0);

for (const token of tokens) {
if (token in this.vocabulary) {
const tokenIdx = this.vocabulary[token];
docVector[tokenIdx]++;
}
}

transformedData.push(docVector);
}

return transformedData;
}
}
Loading