孤立森林:分类数据

5
我将使用sklearn中的孤立森林算法来检测乳腺癌数据集中的异常值。我正试图将该算法应用于混合数据集,但在拟合模型时出现了值错误。
以下是我的数据集: 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'

在分类数据上是否可以使用孤立森林算法?如果可以,如何操作?

1个回答

10

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

有许多方法可以对分类数据进行编码,但如果基数高,则建议从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. - taga
@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
@user2205916 只需将 values = array(data) 替换为 values = np.array(data),就可以正常工作了。 - Mario
1
LabelEncoder 用于目标标签,不适用于特征。如果您的类别没有顺序,使用 LabelEncoder 没有意义。 - Paul Coccoli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接