【发布时间】: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