我做了一些真正快速的东西,应该可以工作。你会看到我有一个看起来很讨厌的单线来预先调整你的限制;但是,如果您只是将限制直接转换为正确的格式,将会容易得多。
本质上,这只是遍历限制列表并与限制进行比较。如果数据样本小于限制,我们将该索引设为 1 并中断。
import random
# str_limits = ['0-17', '55+', '26-35', '46-50', '51-55', '36-45', '18-25']
#
# oneline conditioning for the limit string format
# limits = sorted(list(filter(lambda x: not x.endswith("+"), map(lambda v: v.split("-")[-1], str_limits))))
# limits.append('1000')
# do this instead
limits = sorted([17, 35, 50, 55, 45, 25, 1000])
# sample 100 random datapoints between 0 and 65 for testing
samples = [random.choice(list(range(65))) for i in range(100)]
onehot = [] # this is where we will store our one-hot encodings
for sample in samples:
row = [0]*len(limits) # preallocating a list
for i, limit in enumerate(limits):
if sample <= limit:
row[i] = 1
break
# storing that sample's onehot into a onehot list of lists
onehot.append(row)
for i in range(10):
print("{}: {}".format(onehot[i], samples[i]))
我不确定您的实现细节,但您可能在某些时候忘记将字符串转换为整数。