簡體   English   中英

如何將文本數據集(問答)加載到 numpy 數組中以訓練 keras 模型

[英]How to load Text Dataset (question and answer) into numpy array for training a keras model

我有一個包含以下形式的問題和答案數據集

[question...]?\t[answer...].

示例

Do you like pizza?     Yes its delicious.
...                    

現在我想用它訓練一個 keras 模型。 但是當我加載它時,我不能把它變成一個 numpy 數組,因為句子的長度不一樣。

input_textout_text 中,我將問題和答案存儲為這樣的拆分詞:

[["Do", "you", "like", "pizza", "?"] 
 [ ... ]]

這是我的代碼的一部分。 (我也用自制函數把單詞轉成向量)

X_data = []
Y_data = []

for i in range(len(input_text)):
    xdata = []
    ydata = []
    xdata = xdata+[wordtovec(word,wrdvecdic) for word in input_text[i]]
    for i in range(len(input_text[i])):
        ydata.append([0 for i in range(300)])

    xdata.append([0 for i in range(300)])
    ydata.append([0 for i in range(300)])

    ydata = ydata+[wordtovec(word, wrdvecdic) for word in out_text[i]]
    for i in range(len(out_text[i])):
        xdata.append([0 for i in range(300)])

    X_data.append(xdata)
    Y_data.append(ydata)

X_data = np.array(X_data)
Y_data = np.array(Y_data)

也許可以展示如何執行此操作或提供指向類似數據集示例的鏈接以及如何將其加載到 keras 的 numpy 數組中。

感謝您的回復。

我不知道有任何專門關於 QA 的教程,但在Tensorflow 官方網站上有一個關於相關問題的很好的教程。

由於我們的訓練數據必須是相同的長度,我們通常使用填充函數來標准化長度。 例如:

from tensorflow.python.keras.preprocessing.sequence import pad_sequences
from tensorflow.python.keras.preprocessing.text import Tokenizer

question = ['thi is test', 'this is another test 2']
answers = ['i am answer', 'second answer is here']

tknizer = Tokenizer()
tknizer.fit_on_texts(question + answers)
question = tknizer.texts_to_sequences(question)
answer = tknizer.texts_to_sequences(answer)
question = pad_sequences(question, value=0, padding='post', maxlen=20)
answer = pad_sequences(answer, value=0, padding='post', maxlen=20)

print(question)

輸出:

[[4 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [5 1 6 2 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

在上面的例子中,我們假設最大長度是 20。超過 20 的序列被截斷,以便它們適合所需的長度,而短於 20 的序列在末尾填充 0。

現在,您可以將預處理后的數據輸入 Keras:

inps1 = Input(shape=(20,))
inps2 = Input(shape=(20,))
embedding = Embedding(10000, 100)
emb1 = embedding(inps1)
emb2 = embedding(inps2)
# ... rest of the network
pred = Dense(100,'softmax')(prev_layer)
model = Model(inputs=[inps1, inps2],outputs=pred)
model.compile('adam', 'categorical_crossentropy')
model.fit([question, answer], labels, batch_size=128, epoch=100)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM