在Keras中實現序列生成任務,通常涉及使用循環神經網絡(RNN)或者長短期記憶網絡(LSTM)。以下是一個簡單的示例,演示如何使用LSTM模型生成一個文本序列:
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np
# 準備訓練數據
text = "hello world"
chars = sorted(list(set(text)))
char_to_index = {char: index for index, char in enumerate(chars)}
index_to_char = {index: char for index, char in enumerate(chars)}
seq_length = 3
X_data = []
y_data = []
for i in range(0, len(text) - seq_length):
X_seq = text[i:i + seq_length]
y_seq = text[i + seq_length]
X_data.append([char_to_index[char] for char in X_seq])
y_data.append(char_to_index[y_seq])
X = np.reshape(X_data, (len(X_data), seq_length, 1))
X = X / float(len(chars))
y = np.eye(len(chars))[y_data]
# 構建LSTM模型
model = Sequential()
model.add(LSTM(128, input_shape=(X.shape[1], X.shape[2])))
model.add(Dense(len(chars), activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
# 訓練模型
model.fit(X, y, epochs=100, batch_size=1)
# 生成序列
def generate_text(model, seed_text, length):
generated_text = seed_text
for _ in range(length):
X_seq = np.reshape([char_to_index[char] for char in seed_text], (1, len(seed_text), 1))
X_seq = X_seq / float(len(chars))
pred = model.predict(X_seq, verbose=0)
index = np.argmax(pred)
result = index_to_char[index]
generated_text += result
seed_text = seed_text[1:] + result
return generated_text
seed_text = "hel"
generated_text = generate_text(model, seed_text, 10)
print(generated_text)
在上面的示例中,我們首先準備訓練數據,構建了一個簡單的LSTM模型,然后對模型進行訓練。最后,使用生成函數generate_text()
來生成一個文本序列。您可以根據需要調整模型的結構和參數,以實現更復雜的序列生成任務。