用keras實現單詞級的one-hot編碼
程序员文章站
2022-05-24 09:17:41
...
from keras.preprocessing.text import Tokenizer#導入分詞器
sample = ['The cat sat on the mat.','The dog ate my homework.']
tokenizer = Tokenizer(num_words=1000)#創建一個分詞器,設置為只考慮前1000個最常見的單詞
tokenizer.fit_on_texts(sample)#構建單詞索引
sequences = tokenizer.texts_to_sequences(sample)#將字符串轉換為整數索引組成的列表
one_hot_results = tokenizer.texts_to_matrix(sample,mode='binary')
word_index = tokenizer.word_index#找回單詞索引
print(one_hot_results)
print(one_hot_results.shape)
print(word_index)
print(len(word_index))