forked from tjdolan121/TextClassifierLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountVectorizer.cpp
More file actions
382 lines (343 loc) · 10.9 KB
/
Copy pathCountVectorizer.cpp
File metadata and controls
382 lines (343 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/**
* @file CountVectorizer.cpp
* @brief Implementation of the CountVectorizer class.
*/
/*++
Revision History:
Date: Jun 28, 2024.
Author: Rajas Chavadekar.
Desc: Created.
--*/
#include "CountVectorizer.h"
using namespace std;
/**
* @brief Default constructor.
*
* Defaults to binary=true, case_sensitive=true, and include_stopwords=true.
*/
CountVectorizer::CountVectorizer()
{
binary = true;
case_sensitive = true;
include_stopwords = true;
this_vectorizer_id = ID_VECTORIZER_COUNT;
}
/**
* @brief Constructor with options.
*
* @param binary_ Boolean flag indicating if binary vectors are used.
* @param case_sensitive_ Boolean flag indicating if case sensitivity is considered.
* @param include_stopwords_ Boolean flag indicating if stop words are included.
*/
CountVectorizer::CountVectorizer(bool binary_, bool case_sensitive_, bool include_stopwords_)
{
binary = binary_;
case_sensitive = case_sensitive_;
include_stopwords = include_stopwords_;
}
/**
* @brief Destructor.
*/
CountVectorizer::~CountVectorizer()
{
}
/**
* @brief Fit the vectorizer on the given dataset.
*
* @param abs_filepath_to_features Absolute file path to the features file.
* @param abs_filepath_to_labels Absolute file path to the labels file.
*/
void CountVectorizer::fit(string abs_filepath_to_features, string abs_filepath_to_labels)
{
ifstream in;
string feature_output;
string label_output;
vector<string> features;
vector<bool> labels;
in.open(abs_filepath_to_features);
if (!in)
{
cout << "ERROR: Cannot open features file.\n";
return;
}
while (getline(in, feature_output))
{
features.push_back(feature_output);
}
in.close();
in.open(abs_filepath_to_labels);
if (!in)
{
cout << "ERROR: Cannot open labels file.\n";
return;
}
while (getline(in, label_output))
{
labels.push_back((bool)std::stoi(label_output));
}
in.close();
unsigned int feature_size = features.size();
if (feature_size != labels.size())
{
cout << "ERROR: Feature dimension is different from label dimension\n";
return;
}
cout << "Fitting CountVectorizer..." << endl;
int perc, prevperc;
for (unsigned int i = 0; i < feature_size; i++)
{
addSentence(features[i], labels[i]);
prevperc = perc;
perc = int(float(i) / feature_size * 100);
if (prevperc != perc)
{
cout << perc << " % done" << endl;
}
}
cout << endl;
}
/**
* @brief Print the dimensions of the CountVectorizer object.
*/
void CountVectorizer::shape()
{
unsigned int wordArraySize = getWordArraySize();
unsigned int sentenceCount = getSentenceCount();
cout << "------------------------------" << endl;
cout << "Current CountVectorizer Shape:" << endl;
cout << "Total unique words: " << to_string(wordArraySize) << endl;
cout << "Documents in corpus: " << to_string(sentenceCount) << endl;
cout << "------------------------------" << endl;
}
/**
* @brief Print a dictionary-like representation of the CountVectorizer object (first 10).
*/
void CountVectorizer::head()
{
int count = 0;
unsigned int wordArraySize = getWordArraySize();
if (wordArraySize > 10)
{
wordArraySize = 10;
}
cout << "------------------------------" << endl;
cout << "Current CountVectorizer Head:" << endl;
for (unsigned int i = 0; i < wordArraySize; i++)
{
for (auto sentence : sentences)
{
if (is_wordInSentence(*sentence, i))
{
count++;
}
}
cout << getWord(i) << ": " << count << endl;
count = 0;
}
cout << "------------------------------" << endl;
}
// ===========================================================|
// ======================HELPERS==============================|
// ===========================================================|
/**
* @brief Check if a word is in the sentence.
*
* @param sentence_ The sentence to check.
* @param idx The index of the word to check.
* @return Integer casted boolean indicating presence of the word.
*/
int CountVectorizer::is_wordInSentence(Sentence sentence_, unsigned int idx)
{
return sentence_.sentence_map.count(idx) ? 1 : 0;
}
/**
* @brief Update the word array with newly discovered words from a sentence.
*
* @param new_sentence_vector The sentence vector containing new words.
*/
void CountVectorizer::pushSentenceToWordArray(vector<string> new_sentence_vector)
{
for (const string& word : new_sentence_vector)
{
if (!ContainsWord(word) && !histogram.count(word))
{
word_array.push_back(word);
word_to_idx[word] = word_array.size() - 1;
}
}
}
/**
* @brief Create a Sentence object from a vector of words.
*
* @param new_sentence_vector The vector of words forming the sentence.
* @param label_ Boolean label for the sentence.
* @return Shared pointer to the created Sentence object.
*/
shared_ptr<Sentence> CountVectorizer::createSentenceObject(vector<string> new_sentence_vector, bool label_)
{
shared_ptr<Sentence> new_sentence(new Sentence);
for (const auto& word : new_sentence_vector)
{
if (histogram.count(word))
{
continue;
}
int idx = word_to_idx[word];
if (new_sentence->sentence_map.count(idx))
{
new_sentence->sentence_map[idx]++;
}
else
{
new_sentence->sentence_map[idx] = 1.0;
}
}
if (binary)
{
for (auto& entry : new_sentence->sentence_map)
{
entry.second = 1.0;
}
}
new_sentence->label = label_;
return new_sentence;
}
/**
* @brief Add a sentence to the CountVectorizer.
*
* @param new_sentence The new sentence to add.
* @param label_ Boolean label for the sentence.
*/
void CountVectorizer::addSentence(string new_sentence, bool label_)
{
vector<string> processedString;
processedString = buildSentenceVector(new_sentence);
pushSentenceToWordArray(processedString);
shared_ptr<Sentence> sentObj = createSentenceObject(processedString, label_);
sentences.push_back(sentObj);
}
/**
* @brief Check if the CountVectorizer already contains the word.
*
* @param word_to_check The word to check.
* @return Boolean indicating if the word is present.
*/
bool CountVectorizer::ContainsWord(const string& word_to_check)
{
return word_to_idx.count(word_to_check) > 0;
}
/**
* @brief Get the feature vector for a given sentence.
*
* @param sentence_words The words of the sentence.
* @return Vector of feature values.
*/
std::vector<double> CountVectorizer::getSentenceFeatures(std::vector<std::string> sentence_words) const
{
std::vector<double> sentence_features(word_array.size(), 0.0);
for (const std::string& word : sentence_words)
{
if (word_to_idx.count(word) > 0)
{
int idx = word_to_idx.at(word);
sentence_features[idx]++;
}
}
return sentence_features;
}
std::vector<double> CountVectorizer::getFrequencies(std::unordered_map<int, double> term_freqs) const
{
std::vector<double> sentence_features(word_array.size(), 0.0);
for (const auto& entry : term_freqs)
{
int term_idx = entry.first;
int term_freq = entry.second;
double tf = term_freq;
sentence_features[term_idx] = tf;
}
return sentence_features;
}
/**
* @brief Save the CountVectorizer model to a file.
*
* @param outFile Output file stream to save the model.
*/
void CountVectorizer::save(std::ofstream& outFile) const
{
outFile.write(reinterpret_cast<const char*>(&vers_info), sizeof(vers_info));
ml_size_t word_array_size = word_array.size();
outFile.write(reinterpret_cast<const char*>(&word_array_size), sizeof(word_array_size));
for (const auto& word : word_array)
{
ml_size_t word_size = word.size();
outFile.write(reinterpret_cast<const char*>(&word_size), sizeof(word_size));
outFile.write(word.data(), word_size);
}
/*
ml_size_t sentence_size = sentences.size();
outFile.write(reinterpret_cast<const char*>(&sentence_size), sizeof(sentence_size));
for (const auto& sentence : sentences)
{
ml_size_t map_size = sentence->sentence_map.size();
outFile.write(reinterpret_cast<const char*>(&map_size), sizeof(map_size));
for (const auto& entry : sentence->sentence_map)
{
outFile.write(reinterpret_cast<const char*>(&entry.first), sizeof(entry.first));
outFile.write(reinterpret_cast<const char*>(&entry.second), sizeof(entry.second));
}
outFile.write(reinterpret_cast<const char*>(&sentence->label), sizeof(sentence->label));
}
*/
outFile.write(reinterpret_cast<const char*>(&binary), sizeof(binary));
outFile.write(reinterpret_cast<const char*>(&case_sensitive), sizeof(case_sensitive));
outFile.write(reinterpret_cast<const char*>(&include_stopwords), sizeof(include_stopwords));
outFile.write(reinterpret_cast<const char*>(&ngrams), sizeof(ngrams));
}
/**
* @brief Load the CountVectorizer model from a file.
*
* @param inFile Input file stream to load the model.
*/
void CountVectorizer::load(std::ifstream& inFile)
{
word_array.clear();
word_to_idx.clear();
sentences.clear();
inFile.read(reinterpret_cast<char*>(&vers_info), sizeof(vers_info));
ml_size_t word_array_size;
inFile.read(reinterpret_cast<char*>(&word_array_size), sizeof(word_array_size));
word_array.resize(word_array_size);
for (ml_size_t i = 0; i < word_array_size; ++i)
{
ml_size_t word_size;
inFile.read(reinterpret_cast<char*>(&word_size), sizeof(word_size));
word_array[i].resize(word_size);
inFile.read(&word_array[i][0], word_size);
word_to_idx[word_array[i]] = i;
}
/*
ml_size_t sentence_size;
inFile.read(reinterpret_cast<char*>(&sentence_size), sizeof(sentence_size));
sentences.resize(sentence_size);
for (ml_size_t i = 0; i < sentence_size; ++i)
{
auto sentence = make_shared<Sentence>();
ml_size_t map_size;
inFile.read(reinterpret_cast<char*>(&map_size), sizeof(map_size));
for (ml_size_t j = 0; j < map_size; ++j)
{
int key;
double value;
inFile.read(reinterpret_cast<char*>(&key), sizeof(key));
inFile.read(reinterpret_cast<char*>(&value), sizeof(value));
sentence->sentence_map[key] = value;
}
inFile.read(reinterpret_cast<char*>(&sentence->label), sizeof(sentence->label));
sentences[i] = sentence;
}
*/
inFile.read(reinterpret_cast<char*>(&binary), sizeof(binary));
inFile.read(reinterpret_cast<char*>(&case_sensitive), sizeof(case_sensitive));
inFile.read(reinterpret_cast<char*>(&include_stopwords), sizeof(include_stopwords));
inFile.read(reinterpret_cast<char*>(&ngrams), sizeof(ngrams));
}