Feature Extraction
Indonesian
hanzceo commited on
Commit
660ebfd
·
verified ·
1 Parent(s): 2b206ec

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +11 -0
  2. model.py +57 -0
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PurpleBoW
2
+
3
+ A very simple implementation of Bag-of-Words for those learning about Natural Language Processing.
4
+
5
+ ## About BoW
6
+
7
+ BoW is a simple count algorithm used in old spam email detection and search engine.
8
+ Essentially, we can train a model to remember a set of words we call ordered vocabulary to later count each words from a paragraph or sentence.
9
+ The resulting "prediction" is a vector of ordered counts of those words and their position doesn't matter.
10
+ This is quite good for simple detection, like spam emails which contains a lot of "quick", "win", or "prizes" word.
11
+ However, when it comes to positional meaning BoW performs very poorly. It's like instructing a gold fish to climb a coconut tree.
model.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+
3
+ ds_train = load_dataset("ShoAnn/legalqa_klinik_hukumonline", split="train")
4
+ ds_test = load_dataset("ShoAnn/legalqa_klinik_hukumonline", split="test")
5
+
6
+ def gen(rows):
7
+ sentences = []
8
+ for question in rows["question"]:
9
+ stripped = ''.join(c.lower() for c in question if c.isalpha() or c == ' ')
10
+ sentences.append(stripped)
11
+ return dict(sentence1=sentences)
12
+
13
+ ds_train = ds_train.map(gen, batched=True, remove_columns=ds_train.column_names)
14
+ ds_test = ds_test.map(gen, batched=True, remove_columns=ds_test.column_names)
15
+
16
+ class Model:
17
+ def __init__(self):
18
+ self.vocab = dict()
19
+
20
+ @property
21
+ def features(self):
22
+ return list(self.vocab.keys())
23
+
24
+ def train(self, ds):
25
+ for row in ds:
26
+ sentence = row["sentence1"]
27
+ words = list(filter(lambda x: x, sentence.split()))
28
+
29
+ for word in words:
30
+ if word not in self.vocab:
31
+ self.vocab[word] = 0
32
+ print(f"Vocab size: {len(self.vocab)}", end='\r')
33
+ print()
34
+
35
+ def bag(self, sentence):
36
+ counter = self.vocab.copy()
37
+
38
+ # sanitation
39
+ sanitized = ''.join(c for c in sentence if c.isalpha() or c == ' ')
40
+ words = list(filter(lambda x: x, sanitized.split()))
41
+
42
+ for word in words:
43
+ if word not in counter:
44
+ continue
45
+ counter[word] = counter[word] + 1
46
+
47
+ return list(counter.values())
48
+
49
+
50
+ # usage
51
+ PurpleBoW = Model()
52
+ PurpleBoW.train(ds_train)
53
+
54
+ excerpts = ds_test[:5]["sentence1"]
55
+ for e in excerpts:
56
+ bag = PurpleBoW.bag(e)
57
+ print(e, '->', bag)