在Python TensorFlow中将分类级别转换为独热编码

如果我有一个这样的分类标签

labels = [cat,dog, bird, cow]

现在我想把它转换成独热编码。是否可以使用TensorFlow来实现这样的转换

output_label = [[1 0 0 0]               [0 1 0 0]               [0 0 1 0]               [0 0 0 1]]

回答:

首先,您需要将分类数据转换为数值格式。您可以这样做,例如:

def categorical_to_numerical(labels):    num_labels=[]    for k in labels:        if k == 'cat':            num_labels.append(0)        if k == 'dog':            num_labels.append(1)        if k == 'bird':            num_labels.append(2)        if k == 'cow':            num_labels.append(3)    return num_labelsprint labels// prints ['cat','dog', 'bird', 'cow', 'dog', 'bird'] print categorical_to_numerical(labels)// prints [0, 1, 2, 3, 1, 2]

现在您可以轻松使用TensorFlow内置的tf.one_hot函数:

indices = categorical_to_numerical(labels)detph = 4 // because you have four categories one_hot_labels = tf.one_hot(indices, depth) 

了解更多关于tf.one_hot的信息,请点击这里

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中创建了一个多类分类项目。该项目可以对…

发表回复

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