一热编码语句

One hot encoding sentences

这里是我的一次编码实现:

%reset -f

import numpy as np 
import pandas as pd

sentences = []
s1 = 'this is sentence 1'
s2 = 'this is sentence 2'

sentences.append(s1)
sentences.append(s2)

def get_all_words(sentences) : 

  unf = [s.split(' ') for s in sentences]

  all_words = []

  for f in unf : 
    for f2 in f : 
      all_words.append(f2)

  return all_words



def get_one_hot(s , s1 , all_words) : 
  flattened = []
  one_hot_encoded_df = pd.get_dummies(list(set(all_words)))
  for a in [np.array(one_hot_encoded_df[s]) for s in s1.split(' ')] : 
    for aa in a : 
      flattened.append(aa)

  return flattened

all_words = get_all_words(sentences)

print(get_one_hot(sentences , s1 , all_words))

print(get_one_hot(sentences , s2 , all_words))

这个returns:

[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]

可以看出,对于小句子来说,稀疏向量是 returns。编码似乎发生在字符级别而不是单词级别?如何正确地对下面的单词进行热编码?

我认为编码应该是? :

s1 -> 1, 1, 1, 1
s2 -> 1, 1, 1, 0

字符级编码

这是因为循环:

  for f in unf : 
    for f2 in f : 
      all_words.append(f2)

f2 正在循环字符串 f 的字符。实际上,您可以将整个函数重写为:

def get_all_words(sentences) :
  unf = [s.split(' ') for s in sentences]
  return list(set([word for sen in unf for word in sen]))

正确的单热编码

这个循环

  for a in [np.array(one_hot_encoded_df[s]) for s in s1.split(' ')] : 
    for aa in a : 
      flattened.append(aa)

实际上是在制作一个很长的向量。让我们看看 one_hot_encoded_df = pd.get_dummies(list(set(all_words))):

的输出
   1  2  is  sentence  this
0  0  1   0         0     0
1  0  0   0         0     1
2  1  0   0         0     0
3  0  0   1         0     0
4  0  0   0         1     0

上面的循环正在从该数据框中选取相应的列并附加到输出 flattened。我的建议是简单地利用 pandas 功能,允许您对几列进行子集化,而不是求和,然后裁剪到 0 或 1,以获得单热编码向量:

def get_one_hot(s , s1 , all_words) :
  flattened = []
  one_hot_encoded_df = pd.get_dummies(list(set(all_words)))
  return one_hot_encoded_df[s1.split(' ')].T.sum().clip(0,1).values

输出将是:

[0 1 1 1 1]
[1 1 0 1 1]

分别为你的两个句子。这是解释这些的方法:从 one_hot_encoded_df 数据帧的行索引,我们知道我们使用 0 表示 2,1 表示 this,2 表示 1,等等。所以输出 [0 1 1 1 1] 表示词袋中除了 2 之外的所有项目,你可以用输入 'this is sentence 1'

来确认