python - Tensorflow 错误 : "Label IDs must < n_classes", 但我的标签 ID 似乎已经满足此要求

标签 python pandas tensorflow machine-learning scikit-learn

我正在尝试创建一个 Python 3 程序,以使用 Tensorflow 将句子分类。但是,当我尝试运行我的代码时,我遇到了一系列非常冗长的错误。以下错误似乎是我的问题的基础:

InvalidArgumentError: assertion failed: [Label IDs must < n_classes] [Condition x < y did not hold element-wise:x (linear/head/ToFloat:0) = ] [[4][4]1...] [y (linear/head/assert_range/Const:0) = ] 2

我正在使用Scikit-Learn的LabelEncoder()方法创建标签ID,应该满足这个要求;他们的 documentation page说,“0n_classes-1 之间的值编码标签。

我尝试运行的代码是:

import tensorflow as tf
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split


data_df = pd.read_csv('data.csv') #data.csv has 2 columns: "Category", and "Description"

features = data_df.drop('Category', axis=1) #drop Category column
lab_enc = preprocessing.LabelEncoder()
labels = lab_enc.fit_transform(data_df['Category']) #Encode labels with value between 0 and n_classes-1
labels = pd.Series(labels) #pandas_input_func needs the labels in Series format    

features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.3, random_state=101)


description = tf.feature_column.categorical_column_with_hash_bucket('Description', hash_bucket_size=1000)
feat_cols = [description]

input_func = tf.estimator.inputs.pandas_input_fn(x=features_train, y=labels_train, batch_size=100, num_epochs=None, shuffle=True)

model = tf.estimator.LinearClassifier(feature_columns=feat_cols)
model.train(input_fn=input_func, steps=1000)

我正在使用的 data.csv 文件是一小组乱码测试数据: Testing data

对于如何继续,我有点不知所措。我只找到一篇引用类似问题的帖子 here ,但如果我理解正确的话,该用户的问题似乎与我的问题性质不同。

非常感谢任何见解!

最佳答案

试试这个:

# Explicitly specify the number of classes, e.g. 10
model = tf.estimator.LinearClassifier(feature_columns=feat_cols, n_classes=10)

默认值n_classes=2,这在内部意味着tensorflow使用sigmoid交叉熵损失。设置类别数将使其成为 softmax 交叉熵。

关于python - Tensorflow 错误 : "Label IDs must < n_classes", 但我的标签 ID 似乎已经满足此要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019531/

相关文章:

python - 查找数组中某些元素的所有组合

python - 调试方法返回 None

python - 使用字典转换 tensorflow 数组中的元素

tensorflow - Tensorboard 无法获取运行的第一个事件时间戳

python - 用 Python 中的元组值计算两个字典的点积

python - 迭代 pandas DataFrame 中的选择单元格并替换值

python - 将 pd.dataframe 中的部分列替换为具有不同长度的数组

python - 在 DataFrame 中进行分组、求和、排序和选择

python - 选择列值在给定范围之间的行

tensorflow - OpenAI GPT-2 模型与 TensorFlow JS 一起使用