-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathone_hot_encoding_using_Keras.py
57 lines (46 loc) · 1.31 KB
/
one_hot_encoding_using_Keras.py
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
from keras.preprocessing.text import Tokenizer
from numpy import array
from numpy import argmax
from keras.utils import to_categorical
doc = "Can I eat the Pizza".lower().split()
def using_Tokenizer(doc):
# create the tokenizer
t = Tokenizer()
# fit the tokenizer on the documents
t.fit_on_texts(doc)
# integer encode documents
encoded_docs = t.texts_to_matrix(doc, mode='count')
return encoded_docs
def using_to_categorical(doc):
label_encoder = LabelEncoder()
data = label_encoder.fit_transform(doc)
data = array(data)
# one hot encode
encoded = to_categorical(data)
return encoded
def invert_encoding(row_num):
inverted = label_encoder.inverse_transform([argmax(onehot_encoded[row_num, :])])
return inverted
print ("===using Keras Tokenizer for OneHotEncoding===")
print (using_Tokenizer(doc))
print ()
print ("===using Keras to_categorical for OneHotEncoding===")
print (using_to_categorical(doc))
print ()
print (invert_encoding(int(0)))
"""
OUTPUT:
===using Keras Tokenizer for OneHotEncoding===
[[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 1.]]
===using Keras to_categorical for OneHotEncoding===
[[1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 0. 0. 1.]
[0. 0. 0. 1. 0.]]
['can']
"""