machine-learning - DBSCAN 异常检测
问题描述
我在我的训练数据集上使用 DBSCAN,以便在训练模型之前找到异常值并从数据集中删除这些异常值。我在我的火车行 7697 上使用 DBSCAN,有 8 列。这是我的代码
from sklearn.cluster import DBSCAN
X = StandardScaler().fit_transform(X_train[all_features])
model = DBSCAN(eps=0.3 , min_samples=10).fit(X)
print (model)
X_train_1=X_train.drop(X_train[model.labels_==-1].index).copy()
X_train_1.reset_index(drop=True,inplace=True)
Q-1 在这 7 个中,有些是离散的,有些是连续的,是否可以同时缩放离散和连续或只是连续?Q-2 我需要将集群映射到从训练中学到的测试数据吗?
解决方案
DBSCAN 将为您处理这些异常值。这就是建造的目的。如果您有其他问题,请参阅下面的示例并回复。
import seaborn as sns
import pandas as pd
titanic = sns.load_dataset('titanic')
titanic = titanic.copy()
titanic = titanic.dropna()
titanic['age'].plot.hist(
bins = 50,
title = "Histogram of the age variable"
)
from scipy.stats import zscore
titanic["age_zscore"] = zscore(titanic["age"])
titanic["is_outlier"] = titanic["age_zscore"].apply(
lambda x: x <= -2.5 or x >= 2.5
)
titanic[titanic["is_outlier"]]
ageAndFare = titanic[["age", "fare"]]
ageAndFare.plot.scatter(x = "age", y = "fare")
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
ageAndFare = scaler.fit_transform(ageAndFare)
ageAndFare = pd.DataFrame(ageAndFare, columns = ["age", "fare"])
ageAndFare.plot.scatter(x = "age", y = "fare")
from sklearn.cluster import DBSCAN
outlier_detection = DBSCAN(
eps = 0.5,
metric="euclidean",
min_samples = 3,
n_jobs = -1)
clusters = outlier_detection.fit_predict(ageAndFare)
clusters
from matplotlib import cm
cmap = cm.get_cmap('Accent')
ageAndFare.plot.scatter(
x = "age",
y = "fare",
c = clusters,
cmap = cmap,
colorbar = False
)
推荐阅读
- android - Android WebView 仅在第一次失败
- c - 数学没有正确输出
- strapi - 将 Strapi 项目从 sqlite 迁移到 postgres
- python - Django TemplateView 从数据库的字段中获取模板
- java - 从具有访问限制的共享位置读取文件(java)
- ios - 故事板虚拟值
- c - 返回 char 字符串指针之间的差异时,强制转换和取消引用的顺序有多重要?
- java - 有没有一种简单的方法来比较二叉树的路径?
- mysql - 如何使用 ActiveRecord 忽略 MySQL 索引?
- sql - 如何在 SQL (Postgres) 中查找子字符串