使用numpy数组列表而不是一个热编码向量

在神经网络中,我需要将标签转换为一个热编码数组。我有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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注