使用极不平衡且相关性较差的数据集



我正在处理一个困难的数据集,因为这些类既高度不平衡,又极不相关。该集合有96000个值,其中不到200个是1。

我尝试了几种方法,每种方法的精度和准确性都很高,但只有少数(不到5(值被归类为1。我想知道是否有办法迫使机器对更多的1进行分类。如果我能在25%的时间内正确分类,这将是一个很好的结果。

我试过使用随机林的"类权重"参数,但这似乎对结果没有任何影响。

import numpy as np
import pandas as pd
import sklearn as sklearn
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_pickle('/Users/shellyganga/Downloads/ola.pickle')
print(df.describe())
#filtering the df to improve results
df = df[(df['trip_duration'] > 5) & (df['Smooth_Driving_Score'] < 99)]
print(df.describe())

maxVal = 1
df.unsafe = df['unsafe'].where(df['unsafe'] <= maxVal, maxVal)
df.drop(df.columns[0], axis=1, inplace=True)
df.drop(df.columns[-2], axis=1, inplace=True)
#setting features and labels
labels = np.array(df['unsafe'])
features= df.drop('unsafe', axis = 1)
# Saving feature names for later use
feature_list = list(features.columns)
# Convert to numpy array
features = np.array(features)
from sklearn.model_selection import train_test_split
# 30% examples in test data
train, test, train_labels, test_labels = train_test_split(features, labels,
stratify = labels,
test_size = 0.4,
random_state = 12)
from sklearn.ensemble import RandomForestClassifier
# Create the model with 100 trees
model = RandomForestClassifier(n_estimators=100,
random_state=12,
max_features = 'sqrt',
n_jobs=-1, verbose = 1, class_weight={0:1, 1:1})
# Fit on training data
model.fit(train, train_labels)
predictions = model.predict(test)

print(np.mean(predictions))
print(predictions.shape)

from sklearn.metrics import classification_report
print(classification_report(test_labels, predictions)

输出:

precision    recall  f1-score   support
0       1.00      1.00      1.00     38300
1       1.00      0.01      0.02        90
avg / total       1.00      1.00      1.00     38390

我尝试使用{class_weight = 'balanced'}并提供了不同的结果,但我很难理解它

micro avg       1.00      1.00      1.00     38390
macro avg       1.00      0.51      0.51     38390
weighted avg       1.00      1.00      1.00     38390

我怎么知道它预测了多少积极因素?

这种程度的不平衡通常很难解决,尤其是如果你有很多功能(由于维度诅咒(。除非这两个阶级之间有一个非常明显的界限,否则很难将少数阶级与绝大多数阶级区分开来。正如Luke和Tacratis所建议的,类权重和过采样/欠采样都是你应该尝试的好方法。此外,我还建议使用适当的成本指标。例如,如果假阳性比假阴性更可取,请尝试最大限度地提高召回率,而不是精度或准确性。我还建议将这些方法结合起来。所以,让我们说

  1. 将少数类过采样到1000行。过采样时请尝试SMOTE
  2. 少数族裔阶级不足5000至10000行
  3. 应用类权重来创建平衡集
  4. 在测试集上评估您的成本指标,并更改以上数字,直到指标最大化

尽管如此,对于一个训练有素的模型来说,你可能没有足够的少数类样本。如果您能够在训练集上实现高值的成本度量,但无法在测试集上推广度量,则会出现这种情况。

最新更新