Commit 221cc997 authored by Wolf's avatar Wolf
Browse files

Upload New File

parent 8becf39c
# load libraries
import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score,f1_score,roc_auc_score
# load data set
data = np.loadtxt('crimerate_binary.csv', delimiter=',')
[n,p] = data.shape
# split data into a training set and a testing set
size_train = int(0.75*n) # we use first 75% data for training, the rest for testing
sample_train = data[0:size_train,0:-1]
label_train = data[0:size_train,-1]
sample_test = data[size_train:,0:-1]
label_test = data[size_train:,-1]
# --------------------------------------------------------------
# Support Vector Data Descriptor (SVDD)-based anomaly detection
# tutorial slides, page 69 - 73
# --------------------------------------------------------------
# step 1. construct SVDD model
model = svm.OneClassSVM(kernel='rbf',gamma=0.1,nu=0.8)
# step 2. train the model using ONLY NORMAL examples
model.fit(sample_train[label_train==0,:], )
# the following code trains the model using both normal and abnormal examples
# model.fit(sample_train, )
# step 3. apply model to predict whether an example is normal or anomaly
label_pred = model.predict(sample_test)
label_pred[label_pred==-1] = 0
# evaluate detection error and f1-score
err = 1 - accuracy_score(label_test,label_pred)
f1score = f1_score(label_test,label_pred)
# evaluate AUC score, by first getting annomalous score
adscore = model.decision_function(sample_test)*-1
auc_score = roc_auc_score(label_test, adscore)
# step 4. print results
print('\nSVDD-based Approach')
print('Detection Error = %.4f' % err)
print('F1 Score = %.4f' % f1score)
print('AUC Score = %.4f' % auc_score)
# -----------
# Assignment
# -----------
# 1. train SVDD model using both normal and abnormal examples (replace line 27 with line 29), what do you observe?
# 2. play with different parameters of SVDD model (line 24), what do you observe?
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment