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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
| ''' referrences: https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html https://blog.csdn.net/PIPIXIU/article/details/81016974 dataset: http://www.manythings.org/anki/ '''
from tensorflow.python.keras.layers import Input, LSTM, Dense from tensorflow.python.keras.models import Model import pandas as pd import numpy as np
def create_model(n_input, n_output, n_units): encoder_input = Input(shape=(None, n_input)) encoder = LSTM(n_units, return_state=True) _, encoder_h, encoder_c = encoder(encoder_input) encoder_state = [encoder_h, encoder_c]
decoder_input = Input(shape=(None, n_output)) decoder = LSTM(n_units, return_sequences=True, return_state=True) decoder_output, _, _ = decoder(decoder_input, initial_state=encoder_state) decoder_dense = Dense(n_output, activation='softmax') decoder_output = decoder_dense(decoder_output)
model = Model([encoder_input, decoder_input], decoder_output)
encoder_infer = Model(encoder_input, encoder_state)
decoder_state_input_h = Input(shape=(n_units,)) decoder_state_input_c = Input(shape=(n_units,)) decoder_state_input = [decoder_state_input_h, decoder_state_input_c] decoder_infer_output, decoder_infer_state_h, decoder_infer_state_c = decoder(decoder_input, initial_state=decoder_state_input)
decoder_infer_state = [decoder_infer_state_h, decoder_infer_state_c] decoder_infer_output = decoder_dense(decoder_infer_output)
decoder_infer = Model([decoder_input] + decoder_state_input, [decoder_infer_output] + decoder_infer_state)
return model, encoder_infer, decoder_infer
def predict_chinese(source, encoder_inference, decoder_inference, n_steps, features): state = encoder_inference.predict(source) predict_seq = np.zeros((1, 1, features)) predict_seq[0, 0, target_dict['\t']] = 1
output = '' for i in range(n_steps): yhat, h, c = decoder_inference.predict([predict_seq] + state)
char_index = np.argmax(yhat[0, -1, :]) char = target_dict_reverse[char_index] output += char
state = [h, c] predict_seq = np.zeros((1, 1, features)) predict_seq[0, 0, char_index] = 1
if char == '\n': break return output
NUM_SAMPLES = 2000 BATCH_SIZE = 64 EPOCH = 200 N_UNITS = 256
if __name__ == '__main__':
data_path = 'cmn.txt'
df = pd.read_table(data_path, header=None).iloc[:NUM_SAMPLES, :] df.columns = ['inputs', 'targets'] df['targets'] = df['targets'].apply(lambda x: '\t' + x + '\n')
input_texts = df.inputs.values.tolist() target_texts = df.targets.values.tolist() input_characters = sorted(list(set(df.inputs.unique().sum()))) target_characters = sorted(list(set(df.targets.unique().sum())))
INUPT_SEQ_LENGTH = max([len(i) for i in input_texts]) OUTPUT_SEQ_LENGTH = max([len(i) for i in target_texts]) INPUT_FEATURE_LENGTH = len(input_characters) OUTPUT_FEATURE_LENGTH = len(target_characters)
encoder_input = np.zeros((NUM_SAMPLES, INUPT_SEQ_LENGTH, INPUT_FEATURE_LENGTH)) decoder_input = np.zeros((NUM_SAMPLES, OUTPUT_SEQ_LENGTH, OUTPUT_FEATURE_LENGTH)) decoder_output = np.zeros((NUM_SAMPLES, OUTPUT_SEQ_LENGTH, OUTPUT_FEATURE_LENGTH))
input_dict = {char: index for index, char in enumerate(input_characters)} input_dict_reverse = {index: char for index, char in enumerate(input_characters)} target_dict = {char: index for index, char in enumerate(target_characters)} target_dict_reverse = {index: char for index, char in enumerate(target_characters)}
for seq_index, seq in enumerate(input_texts): for char_index, char in enumerate(seq): encoder_input[seq_index, char_index, input_dict[char]] = 1
for seq_index, seq in enumerate(target_texts): for char_index, char in enumerate(seq): decoder_input[seq_index, char_index, target_dict[char]] = 1.0 if char_index > 0: decoder_output[seq_index, char_index - 1, target_dict[char]] = 1.0
model_train, encoder_infer, decoder_infer = create_model(INPUT_FEATURE_LENGTH, OUTPUT_FEATURE_LENGTH, N_UNITS) model_train.compile(optimizer='rmsprop', loss='categorical_crossentropy') model_train.fit([encoder_input, decoder_input], decoder_output, batch_size=BATCH_SIZE, epochs=EPOCH, validation_split=0.2)
for i in range(100, 200): test = encoder_input[i:i + 1, :, :] out = predict_chinese(test, encoder_infer, decoder_infer, OUTPUT_SEQ_LENGTH, OUTPUT_FEATURE_LENGTH) print(input_texts[i]) print(out)
|