【问题标题】:One hot encoding sentences一个热门编码句子
【发布时间】:2019-07-06 10:08:38
【问题描述】:

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

%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))

返回:

[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]

正如所见,稀疏向量是小句子的返回值。看来编码发生在字符级别而不是单词级别?如何正确地在单词下面进行热编码?

我认为编码应该是? :

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

【问题讨论】:

  • 它没有进行字符编码,它只是将一个列表展平为一个 numpy 数组。 [np.array(one_hot_encoded_df[s]) for s in s1.split(' ')][array([1, 0, 0, 0], dtype=uint8), array([0, 0, 0, 1], dtype=uint8), array([0, 0, 0, 0], dtype=uint8), array([0, 1, 0, 0], dtype=uint8), array([1, 0, 0, 0], dtype=uint8)] 出现,然后随后的 for 循环只获取这些单独的数组并将它们附加到单个数组中,这就是您获得当前答案的方式。

标签: python machine-learning one-hot-encoding


【解决方案1】:

字符级编码

这是因为循环:

  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]))

正确的 one-hot 编码

这个循环

  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,以获得 one-hot 编码向量:

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'确认

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 2023-03-18
    • 2015-08-02
    • 2017-11-05
    • 2021-09-11
    • 2017-09-22
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多