-
Notifications
You must be signed in to change notification settings - Fork 0
/
pca.py
executable file
·76 lines (56 loc) · 1.73 KB
/
pca.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import numpy as np
import pandas as pd
import csv
import sys
from sys import platform as sys_pf
if sys_pf == 'darwin':
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.decomposition import PCA
def analyze(plt):
filename = sys.argv[1]
df = pd.read_csv(filename, usecols = [2,4,5,7,8,9] , header = 0,
names = ['Amount','Source-OB','Source-NB','Dest-OB','Dest-NB','target'])
results = list(map(int, df['target']))
print('Number of fraudulent transactions ' , sum(results))
features = ['Amount', 'Source-OB', 'Source-NB', 'Dest-OB' , 'Dest-NB']
targets = ['target']
# Separating out the features and target variables
x = df.loc[:, features].values
y = df.loc[:, targets].values
print("Number of transactions " , len(y))
scaler = preprocessing.StandardScaler()
x = scaler.fit_transform(x)
pca = PCA(n_components=2)
pcs = pca.fit_transform(x)
pdf = pd.DataFrame(data = pcs,columns = ['PC 1', 'PC 2'])
x = pdf.values.tolist()
x = [tuple(l) for l in x]
y = y.tolist()
#print('List of labels')
#print(y)
be = []
fr = []
i = 0
while i < len(y):
if y[i][0] == 0:
be.append(x[i])
else:
fr.append(x[i])
i += 1
plt.clf()
plt.title('PCA for ' + filename[:-4] + ' transactions')
plt.xlabel('PC 1')
plt.ylabel('PC 2 ')
plt.grid(True)
x1,x2 = zip(*be)
plt.scatter(x1, x2,color = 'b' , marker='+' , label = 'Non-fraud txn')
if len(fr) > 0:
x1,x2 = zip(*fr)
plt.scatter(x1, x2,color = 'r' , marker = 'x' , label = 'Fraud txn')
fig = filename[:-4]
plt.legend()
plt.savefig('./' + fig +'.png')
analyze(plt)