[英]Generate one hot encodings from dict values
我试图根据字典字符创建一个热数组:首先,我创建了一个具有行X列(3x7)的numpy零,然后搜索每个字符的ID并将“ 1”分配给numpy数组。
我的目标是为每个字符分配一个热阵列。 “ 1”表示“存在”,“ 0”表示“不存在”。 这里我们有3个字符,所以我们应该有3行,而7列用作字典中的字符。
但是,我收到一条错误消息,指出“ TypeError:只有整数标量数组可以转换为标量索引”。 有人可以帮我吗? 谢谢
为了不让大家误解我的字典:
这是我创建dic的方法:
sent = ["a", "b", "c", "d", "e", "f", "g"]
aaa = len(sent)
aa = {x:i for i,x in enumerate(sent)}
我的代码:
import numpy as np
sentences = ["b", "c", "e"]
a = {}
for xx in sentences:
a[xx] = aa[xx]
a = {"b":1, "c":2, "e":4}
aa =len(a)
for x,y in a.items():
aa = np.zeros((aa,aaa))
aa[y] = 1
print(aa)
当前错误:
TypeError: only integer scalar arrays can be converted to a scalar index
我的预期输出:
[[0. 1. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0.]]
------->因为它的字典,所以索引排列应该不同,并且数组中的“ 1”是一个虚拟对象,这样我就可以显示期望的输出。
(内联注释。)
# Sort and extract the indices.
idx = sorted(a.values())
# Initialise a matrix of zeros.
aa = np.zeros((len(idx), max(idx) + 1))
# Assign 1 to appropriate indices.
aa[np.arange(len(aa)), idx] = 1
print (aa)
array([[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1.]])
numpy.eye
idx = sorted(a.values())
eye = np.eye(max(idx) + 1)
aa = eye[idx]
print (aa)
array([[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1.]])
一种热编码将样本视为序列,其中序列的每个元素都是词汇表中的索引,指示该元素(例如单词还是字母)是否在样本中。 例如,如果您的词汇是小写字母,那么工作猫的一键编码可能看起来像:
[1, 0., 1, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 1, 0., 0., 0., 0., 0., 0.]
指示此单词包含字母c
, a
和t
。
要进行一键编码,您需要做两件事,即查找具有所有可能值的词汇表(使用单词时,这就是为什么矩阵会变得如此大的原因,因为词汇量很大!)。 但是,如果对小写字母进行编码,则只需26。
然后,您通常将样本表示为词汇表中的索引。 因此这组单词可能看起来像这样:
#bag, cab, fad
sentences = np.array([[1, 0, 6], [2, 0, 1], [5, 0, 3]])
当您进行一次热编码时,您将获得3 x 26的矩阵:
vocab = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#bag, cab, fad
sentences = np.array([[1, 0, 6], [2, 0, 1], [5, 0, 3]])
def onHot(sequences, dimension=len(vocab)):
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1
return results
onHot(sentences)
这样就产生了一个带有26个字母的词汇表的单热编码样本,准备将其馈送到神经网络:
array([[1., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[1., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
我的解决方案以及未来的读者:
我为“已发送”列表构建字典:
sent = ["a", "b", "c", "d", "e", "f", "g"]
aaa = len(sent)
aa = {x:i for i,x in enumerate(sent)}
然后我根据字典找到自己句子的索引,并为这些句子分配数值。
import numpy as np
sentences = ["b", "c", "e"]
a = {}
for xx in sentences:
a[xx] = aa[xx]
a = {"b":1, "c":2, "e":4}
aa =len(a)
我从“ a”的新赋值中提取索引:
index = []
for x,y in a.items():
index.append(y)
然后,我为a中的这些提取索引创建另一个numpy数组。
index = np.asarray(index)
现在,我创建numpy零以存储每个字符的存在:
new = np.zeros((aa,aaa))
new[np.arange(aa), index] = 1
打印(新)
输出:
[[0. 1. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0.]]
这是使用sklearn.preprocessing的另一个
线很长,差别不大。 我不知道为什么,但产生了类似的结果。
import numpy as np
from sklearn.preprocessing import OneHotEncoder
sent = ["a", "b", "c", "d", "e", "f", "g"]
aaa = len(sent)
aa = {x:i for i,x in enumerate(sent)}
sentences = ["b", "c", "e"]
a = {}
for xx in sentences:
a[xx] = aa[xx]
a = {"a":0, "b":1, "c":2, "d":3, "e":4, "f":5, "g":6}
aa =len(a)
index = []
for x,y in a.items():
index.append([y])
index = np.asarray(index)
enc = OneHotEncoder()
enc.fit(index)
print(enc.transform([[1], [2], [4]]).toarray())
输出量
[[0. 1. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0.]]
我喜欢将OneHotEncoder
的LabelEncoder
与OneHotEncoder
sklearn
。
import sklearn.preprocessing
import numpy as np
texty_data = np.array(["a", "c", "b"])
le = sklearn.preprocessing.LabelEncoder().fit(texty_data)
integery_data = le.transform(texty_data)
ohe = sklearn.preprocessing.OneHotEncoder().fit(integery_data.reshape((-1,1)))
onehot_data = ohe.transform(integery_data.reshape((-1,1)))
存储稀疏,所以很方便。 您还可以使用LabelBinarizer
简化此过程:
import sklearn.preprocessing
import numpy as np
texty_data = np.array(["a", "c", "b"])
lb = sklearn.preprocessing.LabelBinarizer().fit(texty_data)
onehot_data = lb.transform(texty_data)
print(onehot_data, lb.inverse_transform(onehot_data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.