-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_tweets.py
73 lines (54 loc) · 2.07 KB
/
generate_tweets.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
71
72
73
import os
import random
import pandas as pd
import numpy as np
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # supress tensorflow console logging
from keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
import tensorflow as tf
from pickle import dump, load
TRAIN_LEN = 25
MODEL_PATH = "epochLSTM.h5"
TOKENIZER_PATH = "epochTK"
SEQUENCE_PATH = "epochSequece"
def gen_text(model, tokenizer, seq_len, seed_text, num_gen_words):
"""
Generates new text based on the seed text received
Keyword arguments:
model -- trained model used to predict words
tokenizer -- trained tokenizer
seq_len -- lenght of the seed text
seed_text -- inital text to generate predictions from
num_gen_words -- how many new words should be predicted
"""
output_text = []
input_text = seed_text
for i in range(num_gen_words):
# Take the input text string and encode it to a sequence
encoded_text = tokenizer.texts_to_sequences([input_text])[0]
pad_encoded = pad_sequences([encoded_text], maxlen=seq_len, truncating="pre")
# Predict Class Probabilities for each word
pred_word_ind = np.argmax(model.predict(pad_encoded), axis=-1)[0]
pred_word = tokenizer.index_word[pred_word_ind]
# Update the sequence of input text (shifting one over with the new word)
input_text += " " + pred_word
output_text.append(pred_word)
return " ".join(output_text)
def main():
# Load Objects
model = load_model(MODEL_PATH)
tokenizer = load(open(TOKENIZER_PATH, "rb"))
text_sequences = load(open(SEQUENCE_PATH, "rb"))
# Picks seed text randomly
random.seed(os.urandom(3123131))
random_pick = random.randint(0, len(text_sequences))
random_seed_text = text_sequences[random_pick]
seed_text = " ".join(random_seed_text)
print("Seed Text: ", ''.join(seed_text))
# Generates new text
gen_txt = gen_text(
model, tokenizer, TRAIN_LEN, seed_text=seed_text, num_gen_words=31
)
print("Generated Text: ", gen_txt)
if __name__ == "__main__":
main()