IsolationForest
可以用来清除您的数据中的异常值。正如这个答案所说,在通常的机器学习设置中,您可以将其运行来清除您的训练数据集。
from sklearn.ensemble import IsolationForest
clf = IsolationForest(max_samples=100, random_state=4, contamination=.1)
#identify outliers:
y_pred_train = clf.fit_predict(X_train)
#Remove outliers where 1 represent inliers and -1 represent outliers:
X_train_cleaned = X_train[np.where(y_pred_train == 1, True, False)]
在无监督设置中,我们可以使用不同的方法(例如IQR)来对contamination
进行参数化。
根据文档,此工具用于检测离群值而非移除它们。
df = pd.DataFrame({'temp': [1,2,3,345,6,7,5345, 8, 9, 10, 11]})
clf = IsolationForest().fit(df['temp'].values.reshape(-1, 1))
clf.predict([[4], [5], [3636]])
数组([ 1, 1, -1])
从输出中可以看出,4
和5
不是异常值,但3636
是。
如果你想从DataFrame中删除异常值,应该使用IQR。
quant = df['temp'].quantile([0.25, 0.75])
df['temp'][~df['temp'].clip(*quant).isin(quant)]
4 6
5 7
7 8
8 9
9 10
def IQR(df, colname, bounds = [.25, .75]):
s = df[colname]
q = s.quantile(bounds)
return df[~s.clip(*q).isin(q)]
我知道我晚回答这个问题,但正如@Kenan所说的,孤立森林用于识别异常值,但不会完全去除它们
。
你可以尝试使用O_Sieve
,它可以自动删除异常值并给出数据集。
pip install vcosmos
from spatial_domain.anaomaly import O_Sieve
sieve=O_Sieve(your_df target_column, tsf=2,tsf=2)
clean_df=sieve.filtered_data()
print(clean_df)