代码
import time
from keras_preprocessing.sequence import pad_sequences
start = time.time()
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
import numpy as np
import tensorflow.keras.layers as layers;
tokenizer = Tokenizer()
data = "Please forgive me for falling in love with you.\n" \
"Forgive me for loving you with all my heart.\n" \
"Forgive me for never wanting to be apart.\n" \
"Two star-crossed lovers in perfect harmony Just give me a chance and you will agree.\n" \
"I was meant for you.\n" \
"And you were meant for me."
print(data)
corpus = data.split("\n")
print("---------------------------------------------------")
print(corpus)
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index)+1
input_seq = []
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1,len(token_list)):
n_gram_seq = token_list[:i+1]
input_seq.append(n_gram_seq)
max_seq_len = max([len(x) for x in input_seq])
input_seq = np.array(pad_sequences(input_seq,maxlen=max_seq_len,padding='pre'))
print("---------------------------------------------------")
print(input_seq)
xs = input_seq[:,:-1]
label = input_seq[:,-1]
ys = tf.keras.utils.to_categorical(label,num_classes=total_words)
model = keras.Sequential()
model.add(layers.Embedding(total_words,240,input_length=max_seq_len-1))
model.add(layers.Bidirectional(layers.LSTM(150)))
model.add(layers.Dense(total_words,activation='softmax'))
adam = keras.optimizers.Adam(lr=0.01)
model.compile(loss="categorical_crossentropy",optimizer=adam,metrics=['accuracy'])
history = model.fit(xs,ys,epochs=50,verbose=1)
test_text = "I want to"
next_words = 20
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences(([test_text]))[0]
token_list = pad_sequences([token_list],maxlen=max_seq_len-1,padding='pre')
predicted = model.predict_classes(token_list,verbose=0)
output_word = ""
for word,index in tokenizer.word_index.items():
if index == predicted:
output_word = word
test_text = (test_text + " " + output_word)
break
print(test_text)
print("共用时:",(time.time()-start),"秒")
效果展示
-
I want to … I want to meant for you with all my heart 我想全心全意为你着想 -
I hate you … I hate you were meant for me for never wanting to be apart 我恨你是我命中注定永远不想分开的 -
I want to eat … I want to eat star crossed lovers in perfect harmony just give me a chance 我想要完美和谐吃着满天星的恋人给我一个机会
|