在神经网络中,我需要将标签转换为一个热编码数组。我有3个标签,它们以列表的形式出现,例如:
labels = ["Synonym", "Antonym", "Not relevant", "Synonym", "Antonym"]
有3个不同的标签,我首先想将它们映射到数字1、2和3,然后从中构建一个热编码向量,例如,对于标签3 –> 0 0 1。我编写的函数生成了一系列数组,这在训练时不起作用。
def label_to_onehot(labels): mapping = {label: i for i, label in enumerate(set(labels))}one_hot = []for label in labels: entry = [0] * len(mapping) entry[mapping[label]] = 1 one_hot.append(entry)return one_hot
这是我得到的结果:
ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 165757 arrays: [array([[0], [0], [1]]), array([[1], [0], [0]]), array([[0], [1],
回答:
Keras期望接收形状为(batch_size, classes)
的numpy数组。但你提供的输入是一个Python列表,它没有shape
属性来获取批次大小和类别数量。因此,尽管大小是正确的,但类型是错误的。
一种可能的解决方案是:其中a是你映射后的索引,c是总类别数。
def one(a, c): out = [] for i in a: entry = [0 for i in range(c)] entry[i] = 1 out.append(entry) return np.array(out)
或者,你也可以使用keras.utils
中的to_categorical
from keras.utils import to_categoricala = to_categorical(a, c)