tensorflow--VocabularyProcessor
from tensorflow.contrib import learn
import numpy as np
max_document_length = 4
x_text =[
'This is an apple',
'No,it is a banana',
'it is an orange'
]
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
vocab_processor.fit(x_text)
print(next(vocab_processor.transform(['it is an'])).tolist())
x_index = np.array(list(vocab_processor.fit_transform(x_text)))
print(x_index)
输出结果为:
[6, 2, 3, 0]
[[1 2 3 4]
[5 6 2 7]
[6 2 3 9]]
索引计数直接从x_text的第一行开始,所以This is an apple No it a banana orange对应的索引分别为1 2 3 4 5 6 7 8 9,故x_index输出结果为:
[[1 2 3 4]
[5 6 2 7]
[6 2 3 9]]
如果将vocab_processor.fix(x_text)注释,
from tensorflow.contrib import learn
import numpy as np
max_document_length = 4
x_text =[
'This is an apple',
'No,it is a banana',
'it is an orange'
]
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)
#vocab_processor.fit(x_text)
print(next(vocab_processor.transform(['it is an'])).tolist())
x_index = np.array(list(vocab_processor.fit_transform(x_text)))
print(x_index)
得到结果:
[1, 2, 3, 0]
[[4 2 3 5]
[6 1 2 7]
[1 2 3 9]]
索引计数从vocab_processor.transform(['it is an']) 开始,所以在返回值得第一行输出[1,2,3,0],对于x_text中的全部词的返回结果中This对应的索引为4,is对应的索引为2,an对应的索引为3,apple对应的索引为5,即对于所有的词索引对应于it is an This apple No a banana orange的索引值为1 2 3 4 5 6 7 8 9,所以x_index输出结果为:
[[4 2 3 5]
[6 1 2 7]
[1 2 3 9]]
最终返回的结果都是词在单词表中的索引值