-
Notifications
You must be signed in to change notification settings - Fork 1
/
MLGen.py
71 lines (56 loc) · 1.94 KB
/
MLGen.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
58
59
60
61
62
63
64
65
66
67
68
69
70
import numpy as np
import random
import pickle
import re
import os
import sys
stderr = sys.stderr
sys.stderr = open(os.devnull, 'w')
import keras
sys.stderr = stderr
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
maxlen = 10
with open('./ML model/text_data.txt', 'rb') as fn:
text = fn.read()
text = text.decode()
chars = sorted(list(set(text)))
with open('./ML model/char_indices.pickle', 'rb') as picklein:
char_indices = pickle.load(picklein)
with open('./ML model/indices_char.pickle', 'rb') as picklein:
indices_char = pickle.load(picklein)
def sample(preds, temperature=1.0):
# helper function to sample an index from a probability array
preds = np.asarray(preds).astype('float64')
preds = np.log(preds) / temperature
exp_preds = np.exp(preds)
preds = exp_preds / np.sum(exp_preds)
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas)
def generate_text(length, diversity):
# Get random name
start_index = random.randint(0, len(text) - maxlen - 1)
generated = ''
sentence = text[start_index: start_index + maxlen]
generated += sentence
for i in range(length):
x_pred = np.zeros((1, maxlen, len(chars)))
for t, char in enumerate(sentence):
x_pred[0, t, char_indices[char]] = 1.
preds = model.predict(x_pred, verbose=0)[0]
next_index = sample(preds, diversity)
next_char = indices_char[next_index]
generated += next_char
sentence = sentence[1:] + next_char
return sentence
def generator(num):
names = []
for i in range(num):
randnum = random.randint(0, 50)
names.append(re.sub("[\n (){}?/,.<>:-]", "", generate_text(randnum, 0.5)))
return names
model = keras.models.load_model('./ML model/modelForNames.h5')
if __name__ == "__main__":
# Add . in all the paths if this part is executed.
names = generator(20)
for i in names:
print(i)