【问题标题】:Isolation Forest : Categorical data隔离森林:分类数据
【发布时间】:2019-07-20 00:55:45
【问题描述】:

我正在尝试使用 sklearn 中的隔离森林检测乳腺癌数据集中的异常情况。我正在尝试将 Iolation Forest 应用于混合数据集,当我拟合模型时它会给我带来价值错误。

这是我的数据集: https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer/

这是我的代码:

from sklearn.model_selection import train_test_split
rng = np.random.RandomState(42)

X = data_cancer.drop(['Class'],axis=1)
y = data_cancer['Class'] 

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 20)
X_outliers = rng.uniform(low=-4, high=4, size=(X.shape[0], X.shape[1]))

clf = IsolationForest()
clf.fit(X_train)

这是我得到的错误:

ValueError: 无法将字符串转换为浮点数:'30-39'

是否可以对分类数据使用隔离森林?如果是,我该怎么做?

【问题讨论】:

    标签: python scikit-learn categorical-data outliers anomaly-detection


    【解决方案1】:

    您应该将分类数据编码为数字表示。

    分类数据的编码方式有很多种,但我建议你先从

    sklearn.preprocessing.LabelEncoder 如果基数高,sklearn.preprocessing.OneHotEncoder 如果基数低。

    这里是一个用法示例:

    import numpy as np
    from numpy import argmax
    from sklearn.preprocessing import LabelEncoder
    from sklearn.preprocessing import OneHotEncoder
    # define example
    data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot']
    values = np.array(data)
    print(values)
    # integer encode
    label_encoder = LabelEncoder()
    integer_encoded = label_encoder.fit_transform(values)
    print(integer_encoded)
    # binary encode
    onehot_encoder = OneHotEncoder(sparse=False)
    integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
    onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
    print(onehot_encoded)
    # invert first example
    inverted = label_encoder.inverse_transform([argmax(onehot_encoded[0, :])])
    print(inverted)
    

    输出:

    ['cold' 'cold' 'warm' 'cold' 'hot' 'hot' 'warm' 'cold' 'warm' 'hot']
     
    [0 0 2 0 1 1 2 0 2 1]
     
    [[ 1.  0.  0.]
     [ 1.  0.  0.]
     [ 0.  0.  1.]
     [ 1.  0.  0.]
     [ 0.  1.  0.]
     [ 0.  1.  0.]
     [ 0.  0.  1.]
     [ 1.  0.  0.]
     [ 0.  0.  1.]
     [ 0.  1.  0.]]
     
    ['cold']
    

    【讨论】:

    • 好的,但是如果我想用自己的输入进行预测,我该怎么做。我写了input_par = encoder.transform(['string value 1', 'string value 2'...]),但出现错误:Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
    • @Farseer 忘记添加:from array import array 另外,您的玩具示例对我不起作用。我收到一个错误:TypeError: array() argument 1 or typecode must be char (string or ascii-unicode with length 1), not list (使用 Python 2)。
    • @user2205916 只需替换 values = np.array(data) 而不是 values = array(data) 即可。
    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 2018-09-10
    • 2019-07-11
    • 2019-06-29
    • 2020-11-16
    • 2019-08-02
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多