对Tensorflow 分词器texts_to_matrix的理解

在实现上,这个函数是调用了sequences_to_matrix,为了便于理解使用texts_to_matrix作为分析。毕竟单词比数字更直观。
对于下面的单词组:

texts=[['hello','world'],
		['hello','Jim','hello','Rose'],
		['home']
]

texts是一个二维数组,可以看作是文章的集合。如果我们要得到hello在每篇文章中的出现次数,要怎么处理?
显然texts_to_matrix是可以完成这个功能的。但是问题是如何生成参数是个问题。简单的输入[[‘hello’]]是得不到想要的结果的。这里要输入的是hello这个单词在每篇文章是否出现,如果出现就加入到数组中,代码如下:

text_hello=[]
for text in texts:
    t=[]
    for word in text:
        if word=='hello':
            t.append('hello')
    text_hello.append(t)

用此数组text_hello生成hello的矩阵就可以了。单纯的输入一个[[‘hello’]]是无法得到正确的结果的。完整的程序如下:

from tensorflow.keras.preprocessing.text import Tokenizer

texts=[['hello','world'],
		['hello','Jim','hello','Rose'],
		['home']
]
text_hello=[]
for text in texts:
    t=[]
    for word in text:
        if word=='hello':
            t.append('hello')
    text_hello.append(t)
print(text_hello)
tok = Tokenizer()
tok.fit_on_texts(texts)
print(tok.texts_to_matrix(text_hello,mode='count'))

结果如下:

[['hello'], ['hello', 'hello'], []]
[[0. 1. 0. 0. 0. 0.]
 [0. 2. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0.]]

需要注意的第一列的0是保留的,在处理的时候可以去掉。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值