【问题标题】:Random Forest gets 98% accuracy in training and testing but always predicts the same class otherwise随机森林在训练和测试中获得 98% 的准确率,但总是预测相同的类别
【发布时间】:2021-01-05 21:02:58
【问题描述】:

我已经花了 30 个小时来调试这个单一的问题,这完全没有意义,希望你们中的某个人可以向我展示不同的观点。

问题是我在随机森林中使用我的训练数据帧并获得非常好的准确率 98%-99% 但是当我尝试加载新样本进行预测时。模型总是猜测同一个类。

#  Shuffle the data-frames records. The labels are still attached
df = df.sample(frac=1).reset_index(drop=True)

#  Extract the labels and then remove them from the data
y = list(df['label'])
X = df.drop(['label'], axis='columns')

#  Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE)

#  Construct the model
model = RandomForestClassifier(n_estimators=N_ESTIMATORS, max_depth=MAX_DEPTH, random_state=RANDOM_STATE,oob_score=True)

#  Calculate the training accuracy
in_sample_accuracy = model.fit(X_train, y_train).score(X_train, y_train)
#  Calculate the testing accuracy
test_accuracy = model.score(X_test, y_test)

print()
print('In Sample Accuracy: {:.2f}%'.format(model.oob_score_ * 100))
print('Test Accuracy: {:.2f}%'.format(test_accuracy * 100))

我处理数据的方式是相同的,但是当我在 X_test 或 X_train 上进行预测时,我得到了正常的 98%,而当我对新数据进行预测时,它总是猜测同一个类别。

    #  The json file is not in the correct format, this function normalizes it
    normalized_json = json_normalizer(json_file, "", training=False)
    #  Turn the json into a list of dictionaries which contain the features
    features_dict = create_dict(normalized_json, label=None)

    #  Convert the dictionaries into pandas dataframes
    df = pd.DataFrame.from_records(features_dict)
    print('Total amount of email samples: ', len(df))
    print()

    df = df.fillna(-1)
    #  One hot encodes string values
    df = one_hot_encode(df, noOverride=True)
    if 'label' in df.columns:
        df = df.drop(['label'], axis='columns')
    print(list(model.predict(df))[:100])
    print(list(model.predict(X_train))[:100])

以上是我的测试场景,您可以在最后两行中看到我预测的 X_train 用于训练模型的数据和 df 它总是猜测为 0 类的样本外数据。

一些有用的信息:

  • 数据集不平衡;第 0 类有大约 150,000 个样本,而第 1 类有大约 600,000 个样本
  • 有 141 个特征
  • 更改 n_estimators 和 max_depth 并不能解决问题

任何想法都会有所帮助,如果您需要更多信息,请告诉我我的大脑现在已经炸了,这就是我能想到的。

【问题讨论】:

  • OP 中未回答的几个问题。 1. 在训练模型之前,你有没有采取任何措施来处理不平衡的数据? 2. 在训练模型之前是否对数据进行了随机抽样? 3. 在构建模型之前是否应用了交叉验证?
  • @mnm 所以这个模型几天前就开始工作了,即使没有平衡数据也能准确地预测事情,所以我没有尝试。数据是随机抽样的,我什至尝试对训练中使用的样本进行重新处理和预测,结果每次都猜测同一个类
  • 请您检查df是否填写正确?在df=df.fillna(-1) 之后可能都是-1?只是猜测。
  • 准确性对于不平衡数据来说不是很好,因为它指导模型正确预测多数类。您需要 (1) 重新采样数据,以便类或多或少均匀地再现 (2) 权重类 (3) 选择更稳健的指标,如 AUC 或 f1
  • @DL_Engineer 根据 OP,1 类比 0 类大 4 倍,因此最初该模型很可能仅适用于 1 类。尝试使用 ROC AUC 作为评估来构建新模型指标。

标签: python machine-learning scikit-learn random-forest imbalanced-data


【解决方案1】:

已修复,问题是数据集的不平衡,我也意识到改变深度会给我带来不同的结果。

例如,10 棵深度为 3 的树 -> 似乎工作正常 6 深度的 10 棵树 -> 回到只猜测同一个类

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2019-08-12
    • 2020-11-25
    • 2016-12-04
    • 2020-10-31
    • 2021-02-11
    • 2019-06-07
    • 2021-07-10
    • 2021-12-04
    相关资源
    最近更新 更多