随机森林在训练和测试中获得98%的准确性,但在其他情况下总是预测相同的等级

问题描述

我已经花了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无法解决

任何想法都是有帮助的,如果您需要更多信息,请让我知道我的大脑现在被炸了,这就是我能想到的。

解决方法

固定,问题在于数据集的不平衡,我意识到改变深度会给我带来不同的结果。

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