如何在字符级别对句子进行热编码?

2024-06-02 09:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个句子转换成一个热向量数组。 这些向量将是字母表的一个热门代表。 如下所示:

"hello" # h=7, e=4 l=11 o=14

会变成

^{pr2}$

不幸的是,来自sklearn的OneHotEncoder没有作为输入字符串。在


Tags: 字符串hello代表数组sklearn向量字母表句子
3条回答

对于熊猫,你可以使用警察局的傻瓜通过传递一个分类序列:

import pandas as pd
import string
low = string.ascii_lowercase

pd.get_dummies(pd.Series(list(s)).astype('category', categories=list(low)))
Out: 
   a  b  c  d  e  f  g  h  i  j ...  q  r  s  t  u  v  w  x  y  z
0  0  0  0  0  0  0  0  1  0  0 ...  0  0  0  0  0  0  0  0  0  0
1  0  0  0  0  1  0  0  0  0  0 ...  0  0  0  0  0  0  0  0  0  0
2  0  0  0  0  0  0  0  0  0  0 ...  0  0  0  0  0  0  0  0  0  0
3  0  0  0  0  0  0  0  0  0  0 ...  0  0  0  0  0  0  0  0  0  0
4  0  0  0  0  0  0  0  0  0  0 ...  0  0  0  0  0  0  0  0  0  0

[5 rows x 26 columns]

只需将传递字符串中的字母与给定的字母表进行比较:

def string_vectorizer(strng, alphabet=string.ascii_lowercase):
    vector = [[0 if char != letter else 1 for char in alphabet] 
                  for letter in strng]
    return vector

请注意,使用自定义字母表(例如“defbcazk”,列将按每个元素在原始列表中出现的顺序排列)。在

string_vectorizer('hello')的输出:

^{pr2}$

这是递归神经网络中的一个常见任务,tensorflow中有一个专门用于此目的的函数,如果你愿意的话。在

In [24]: alphabets = {'a' : 0, 'b': 1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':6, 'h':7, 'i':8, 'j':9, 'k':10, 'l':11, 'm':12, 'n':13, 'o':14}

In [25]: idxs = [alphabets[ch] for ch in 'hello']

In [26]: idxs
Out[26]: [7, 4, 11, 11, 14]

# @divakar's approach
In [153]: idxs = np.fromstring("hello",dtype=np.uint8)-97

In [13]: one_hot = tf.one_hot(idxs, 26, dtype=tf.uint8)

In [14]: sess = tf.InteractiveSession()

In [15]: one_hot.eval()
Out[15]: 
array([[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)

相关问题 更多 >