我有一个多类数据集,正在尝试使用OneClassSVM()
对每个类进行分类。
from sklearn.svm import OneClassSVM
clf = OneClassSVM(gamma='auto').fit(df)
x_train,x_test,y_train,y_test = train_test_split(df,target,test_size=0.30, random_state=25)
inliers=df[clf.predict(df)==1]
outliers=df[clf.predict(df)==-1]
所以我想知道如何在每节课上训练OneClassSVM()
?
实现这一点的一种方法是按类分离数据集,并且在OCSVM中分别训练每个类。这里有一个代码,它为内值(1(和外值(-1(返回不同的评估度量。
from sklearn.model_selection import train_test_split
from sklearn.svm import OneClassSVM
from sklearn.metrics import classification_report
def evaluation_one_class(preds_interest, preds_outliers):
y_true = [1]*len(preds_interest) + [-1]*len(preds_outliers)
y_pred = list(preds_interest)+list(preds_outliers)
return classification_report(y_true, y_pred, output_dict=False)
def evaluate_model(X_train, X_test, X_outlier, model):
one_class_classifier = model.fit(X_train)
Y_pred_interest = one_class_classifier.predict(X_test)
Y_pred_ruido = one_class_classifier.predict(X_outlier)
print(evaluation_one_class(Y_pred_interest, Y_pred_ruido))
class_of_interest = ''
df_interest = df[df['target'] == class_of_interest]
df_outlier = df[df['target'] != class_of_interest]
df_train_int, df_test_int = train_test_split(df_interest,test_size=0.30, random_state=25)
clf = OneClassSVM(gamma='auto')
evaluate_model(df_train_int, df_test_int, df_outlier, clf)