python-3.x - Keras Python 中的分类分类

标签 python-3.x tensorflow scikit-learn keras multiclass-classification

我正在对 5 个类进行多类分类。我在 Keras 中使用 Tensorflow。我的代码是这样的:

# load dataset
dataframe = pandas.read_csv("Data5Class.csv", header=None)
dataset = dataframe.values
# split into input (X) and output (Y) variables
X = dataset[:,0:47].astype(float)
Y = dataset[:,47]
print("Load Data.....")

encoder= to_categorical(Y)

def create_larger():  
    model = Sequential()
    print("Create Dense Ip & HL 1 Model ......")
    model.add(Dense(47, input_dim=47, kernel_initializer='normal',     activation='relu'))
    print("Add Dense HL 2 Model ......")
    model.add(Dense(40, kernel_initializer='normal', activation='relu'))
    print("Add Dense output Model ......")
    model.add(Dense(5, kernel_initializer='normal', activation='sigmoid'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

estimators = []
estimators.append(('rnn', KerasClassifier(build_fn=create_larger, epochs=60,  batch_size=10, verbose=0)))
pipeline = Pipeline(estimators)
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
results = cross_val_score(pipeline, X, encoder, cv=kfold)
print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))

我作为输入的 CSV 文件包含带标签的数据。标签像这样 0, 1, 2, 3, 4 代表 5 个不同的类。

  1. 然后,由于标签已经是整数形式,我是否需要使用 我的代码中的 LabelEncoder() 函数?
  2. 此外,我还使用了 to_categorical(Y) 函数。我应该使用它还是应该将包含这些标签的 Y 变量传递给分类器进行训练?

  3. 我得到这样的错误: 支持的目标类型是:('二进制','多类')。取而代之的是“多标签指示器”。 当我在代码中使用编码器变量时出现此错误 results = cross_val_score(pipeline, X, encoder, cv=kfold) 其中编码器变量表示 to_categorical(Y) 数据。如何解决这个错误?

最佳答案

Keras documentation here 中所述:

Note: when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample). In order to convert integer targets into categorical targets, you can use the Keras utility to_categorical:

from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=None)

因此这意味着您需要在训练前对您的y 使用to_categorical() 方法。但如果 y 已经是整数类型,则无需使用 LabelEncoder。

关于python-3.x - Keras Python 中的分类分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869805/

相关文章:

python - 类 python 中的 IndentationError

python-3.x - Python EasyGUI 模块 : how to change the font

pandas - 箱线图错误: 1 ndim Categorical are not supported at this time

machine-learning - 在 scikit-learn 中使用多标签随机森林没有标签分配的样本

python - 在 sklearn.metrics.plot_confusion_matrix 中抑制科学记数法

python - 当我需要返回值时,exec 返回一个非类型

node.js - 多语言微服务方法

python - TensorFlow MNIST 示例未使用 fully_connected_feed.py 运行

TensorFlow:如何将浮点序列嵌入到固定大小的向量中?

python - 随时随地重新训练 Tensorflow 模型