我正在对 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 变量传递给分类器进行训练?我得到这样的错误: 支持的目标类型是:('二进制','多类')。取而代之的是“多标签指示器”。 当我在代码中使用编码器变量时出现此错误 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/