【问题标题】:Keras Multiclass Classification (Dense model) - Confusion Matrix IncorrectKeras 多类分类(密集模型) - 混淆矩阵不正确
【发布时间】:2020-01-18 11:08:51
【问题描述】:

我有一个带标签的数据集。最后一列 (78) 包含 4 种攻击类型。以下代码混淆矩阵对于两种类型的攻击都是正确的。任何人都可以帮助修改 keras 多类攻击检测和纠正的代码以获得正确的混淆矩阵吗?以及正确的精度代码,FPR,多类的TPR。谢谢。

import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from keras.utils.np_utils import to_categorical

dataset_original = pd.read_csv('./XYZ.csv')

# Dron NaN value from Data Frame
dataset = dataset_original.dropna()


# data cleansing
X = dataset.iloc[:, 0:78]
print(X.info())
print(type(X))
y = dataset.iloc[:, 78] #78 is labeled column contains 4 anomaly type
print(y)


# encode the labels to 0, 1 respectively
print(y[100:110])
encoder = LabelEncoder()
y = encoder.fit_transform(y)
print([y[100:110]])

# Split the dataset now
XTrain, XTest, yTrain, yTest = train_test_split(X, y, test_size=0.2, random_state=0)


# feature scaling
scalar = StandardScaler()
XTrain = scalar.fit_transform(XTrain)
XTest = scalar.transform(XTest)


# modeling
model = Sequential()
model.add(Dense(units=16, kernel_initializer='uniform', activation='relu', input_dim=78))
model.add(Dense(units=8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))
model.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(XTrain, yTrain, batch_size=1000, epochs=10)


history = model.fit(XTrain, yTrain, batch_size=1000, epochs=10, verbose=1, validation_data=(XTest, 
yTest))


yPred = model.predict(XTest)
yPred = [1 if y > 0.5 else 0 for y in yPred]
matrix = confusion_matrix(yTest, yPred)`enter code here`
print(matrix)
accuracy = (matrix[0][0] + matrix[1][1]) / (matrix[0][0] + matrix[0][1] + matrix[1][0] + matrix[1][1])
print("Accuracy: " + str(accuracy * 100) + "%")

【问题讨论】:

    标签: keras neural-network deep-learning multiclass-classification


    【解决方案1】:

    如果我理解正确,您正在尝试解决目标标签属于 4 种不同攻击的多类分类问题。因此,您应该使用具有 4 个单元而不是 1 个单元的输出密集层和“softmax”激活函数(不是“sigmoid”激活)。此外,在编译模型时,您应该使用“categorical_crossentropy”损失代替“binary_crossentropy”。 此外,通过此设置,将 argmax 应用于预测结果(每个测试样本有 4 个类别概率值),您将获得最终的标签/类别。


    [编辑] 您的混淆矩阵和高精度表明您正在使用不平衡的数据集。可能有非常多的样本来自第 0 类,而很少有样本来自剩余的 3 类。要处理此问题,您可能需要应用加权样本或过采样/欠采样方法。

    【讨论】:

    • 您好,非常感谢您的回复。你完全理解我的期望。我已听从您的建议,我收到了 1 个关于混淆矩阵矩阵 = 混淆矩阵(yTest,yPred),ValueError:分类指标无法处理多类和连续多输出目标的混合的错误,请您检查错误以解决问题。谢谢
    • 使用这个新设置,您不需要在 yPred 上应用阈值,而是使用 argmax。还要确保confusion_matrix中yPred和yTest的形状相同。
    • 感谢您的回复。我是 keras 的新手。如果您有时间,请您合作编写或修改最后几行以设置混淆矩阵的argmax?
    • 您可以尝试使用 y = keras.utils.to_categorical(y, num_classes=4) 而不是使用 y = encoder.fit_transform (因为我以前没有使用过),而对于混淆矩阵,请尝试以下操作:矩阵 = 混淆矩阵(yTest.argmax(axis=1), yPred.argmax(axis=1))
    • numpy.AxisError: 轴 1 超出维度 1 数组的范围
    猜你喜欢
    • 2019-05-26
    • 2018-11-27
    • 2021-07-28
    • 2021-10-30
    • 2021-11-11
    • 2018-12-19
    • 2018-04-09
    • 2018-10-21
    • 2019-10-20
    相关资源
    最近更新 更多