【发布时间】:2018-09-26 22:20:13
【问题描述】:
我正在做 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 个不同的类。
- 那么,由于标签已经是整数形式,我需要使用
我的代码中的
LabelEncoder()函数? 另外,我使用了
to_categorical(Y) 函数。我应该使用它还是应该将包含这些标签的 Y 变量传递给分类器进行训练?我收到如下错误: 支持的目标类型是:('binary', 'multiclass')。取而代之的是“多标签指示器”。 当我在代码中使用编码器变量时发生此错误 results = cross_val_score(pipeline, X, encoder, cv=kfold) 其中编码器变量表示 to_categorical(Y) 数据。如何解决这个错误?
【问题讨论】:
-
无需使用 LabelEncoder()。但是
to_categorical()的使用取决于 Keras 模型中使用的损失函数。显示该代码。 -
是的。我使用了 categorical_crossentropy 损失函数。代码是这样的:model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
-
您不能在 cross_val_score 中使用带有 StratifiedKFold 的 Keras 估计器。您需要为此编写一个自定义交叉验证,其中传递给 StratifiedKFold 的数据应该是原始的
y,然后在拆分后应该用to_categorical()编码并传递给 Keras。
标签: python-3.x tensorflow scikit-learn keras multiclass-classification