实现对文本的简单one-hot编码
生活随笔
收集整理的這篇文章主要介紹了
实现对文本的简单one-hot编码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
one-hot編碼是將標記轉換為向量的最常用、最基本方法。下面分別講講字符級的one-hot編碼和單詞級的one-hot編碼。
單詞級的one-hot編碼
import numpy as npsamples = ['The cat sat on the mat.', 'The dog ate my homework.'] # 初始數據,本例中是一個句子,當然也可以是一篇文章token_index = {} # 構建數據中所有標記的索引 for sample in samples:for word in sample.split(): # 用split方法對樣本進行分詞,實際應用中,可能還需要考慮到標點符號if word not in token_index:token_index[word] = len(token_index) + 1 #為每個唯一單詞指定唯一索引,注意我們沒有為索引編號0指定單詞max_length = 10 # 對樣本進行分詞,只考慮樣本前max_length單詞results = np.zeros((len(samples), max_length, max(token_index.values()) + 1)) # 將結果保存到results中 for i, sample in enumerate(samples):for j, word in list(enumerate(sample.split()))[:max_length]:index = token_index.get(word)results[i, j, index] = 1.字符級的one-hot編碼
import stringsamples = ['The cat sat on the mat.', 'The dog ate my homework.'] characters = string.printable # 所有可打印的ASCII字符 token_index = dict(zip(characters, range(1, len(characters) + 1)))max_length = 50 results = np.zeros((len(samples), max_length, max(token_index.values()) + 1)) for i, sample in enumerate(samples):for j, character in enumerate(sample[:max_length]):index = token_index.get(character)results[i, j, index] = 1.當然,Keras也自帶了實現one-hot編碼的方式:
from keras.preprocessing.text import Tokenizersamples = ['The cat sat on the mat.', 'The dog ate my homework.']tokenizer = Tokenizer(num_words=1000) # i創建一個分詞器(tokenizer),設置為只考慮前1000個最常見的單詞tokenizer.fit_on_texts(samples) # 構建索引單詞sequences = tokenizer.texts_to_sequences(samples) # 將字符串轉換為整數索引組成的列表one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary') #可以直接得到one-hot二進制表示。這個分詞器也支持除# one-hot編碼外其他向量化模式word_index = tokenizer.word_index # 得到單詞索引 print('Found %s unique tokens.' % len(word_index))更多精彩內容,歡迎關注我的微信公眾號:數據瞎分析
總結
以上是生活随笔為你收集整理的实现对文本的简单one-hot编码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 可视化卷及神经网络热力图
- 下一篇: Keras方法进行词嵌入