【发布时间】:2018-01-29 23:25:06
【问题描述】:
给定可变数量的字符串,我想对它们进行一次热编码,如下例所示:
s1 = 'awaken my love'
s2 = 'awaken the beast'
s3 = 'wake beast love'
# desired result - NumPy array
array([[ 1., 1., 1., 0., 0., 0.],
[ 1., 0., 0., 1., 1., 0.],
[ 0., 0., 1., 0., 1., 1.]])
当前代码:
def uniquewords(*args):
"""Create order-preserved string with unique words between *args"""
allwords = ' '.join(args).split()
return ' '.join(sorted(set(allwords), key=allwords.index)).split()
def encode(*args):
"""One-hot encode the given input strings"""
unique = uniquewords(*args)
feature_vectors = np.zeros((len(args), len(unique)))
for vec, s in zip(feature_vectors, args):
for num, word in enumerate(unique):
vec[num] = word in s
return feature_vectors
问题出在这一行:
vec[num] = word in s
例如,将'wake' in 'awaken my love' 提取为True(这是正确的,但不符合我的需要)并给出以下稍微有点偏离的结果:
print(encode(s1, s2, s3))
[[ 1. 1. 1. 0. 0. 1.]
[ 1. 0. 0. 1. 1. 1.]
[ 0. 0. 1. 0. 1. 1.]]
我见过a solution 使用re,但不知道如何在这里申请。我怎样才能纠正上面的单线? (摆脱嵌套循环也不错,但我不要求进行常规代码编辑,除非有人提供。)
【问题讨论】:
-
word in s未测试'wake' in ['awaken']。它正在测试'wake' in 'awaken'。 -
(好吧,真的是
'wake' in 'awaken my love'或'wake' in 'awaken the beast') -
对字符串的单词集而不是字符串执行
in测试。 -
...什么?不,您已经有了将字符串转换为一组单词的逻辑。只是使用它有点不同。
-
我不是在谈论将集合的
str表示转换回集合。
标签: python python-3.x numpy one-hot-encoding