使用分类数据进行预测

数据挖掘 机器学习 Python 特征工程 预言
2022-02-20 06:49:22

我有一个包含各种列的数据集:数字和分类。

数据集在这里

如方法 #2中所述我能够使用Pandas 数据框中的.astype('category')和特征来处理分类数据。cat.codes

def process_categorical(self, dataset):
        """

        :param dataset:
        :return:
        """
        # Label Encoding.
        for categorical_feature in LABEL_ENCODED_FEATURES:
            categorical_feature = _to_string(categorical_feature)
            dataset[categorical_feature] = dataset[categorical_feature].astype('category')
            dataset[categorical_feature + '_cat'] = dataset[categorical_feature].cat.codes
        # Drop previous values.
        dataset = dataset.drop(LABEL_ENCODED_FEATURES, axis=1)
        # Rename back categories. {'to_user_cat': 'to_user' ... }
        dataset.rename(columns={c + '_cat': c for c in LABEL_ENCODED_FEATURES}, inplace=True)
        return dataset

我能够训练我的模型和测试数据。当我生成对分类特征进行编码的训练数据集时。(使用.cat.codes),这个数值数据与我的预测不同。例子:

dataset['user_agent_numerical'].value_counts()

10    1002
11     850
1      288
8       18
7       17
2       16
6       14
3        5
0        4
9        2
5        2
4        2

对应于:dataset.groupby(['user_agent']).size()

user_agent
24gt2wreg24h                4
Avaya one-X Deskphone     288
Deskphone                  16
FreePBX 1.8                 5
HiDude UA v3.81             2
SimpleSIP V4.3              2
Twilio Gateway             14
caller                     17
eyeBeam release 3006o      18
friendly-scanner            2
pplsip                   1002
sipcli/v1.8               850

当我想进行预测并传递如下所示的原始记录时:(标题仅供参考)

ruri,ruri_user,ruri_domain,from_user,from_domain,from_tag,to_user,contact_user,callid,content_type,user_agent,source_ip,source_port,destination_port,contact_ip,contact_port
sip:789011972592277524@13.57.9.131,789011972592277524,13.57.9.131,78901113579131,13.57.9.131,1823821775,789011972592277524,78901113579131,1365624720-309058623-1808658022,application/sdp,pplsip,163.172.120.42,60993,5060,212.129.10.158,60993

我需要进行预处理,我的预测数据包含pplsipuser-agent因此它最终为 0,而不是 10。

如何将数据传递给需要转换为分类值的预测。如果我尝试将其转换为分类,我最终会得到不同的类值。

用户代理只是一个示例,但可以是 IP 地址或被叫号码,它们对应于非常大的有限集,因此字典无法扩展。我认为这是一个常见问题,但不知道如何解决。我尝试使用虚拟方法#3,但最终生成了与我的预测数据集不匹配的附加列。此处报告的问题

完整的代码在这里

1个回答

是的,这是一个常见的问题。我要做的是使用 SKLearns标签编码器使用与 SKLearn 模型类似的 API,它可以是fit您的类别 - 这意味着通过编码器对象传递的任何新数据都以相同的方式编码。例如

# Import the encoder
from sklearn.preprocessing import LabelEncoder

# Fit it to your training set + transform
encoder = LabelEncoder()
train[categorical_feature] = encoder.fit_transform(train[categorical_feature])

# Use it on the test set to ensure the same transformation
test[categorical_feature] = encoder.transform(test[categorical_feature])

巨大的警告#1

这假设每个可能的类别都存在于您的训练集中。如果您认为情况并非如此,请将编码器安装到包含所有这些的数据集。

巨大的警告#2

根据您使用的模型,分类标签在被标签编码后仍然没有被“处理”,您可能仍然需要一个热编码(SKLearn 也有一个包)。