-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreprocessing.py
More file actions
67 lines (56 loc) · 1.85 KB
/
Copy pathpreprocessing.py
File metadata and controls
67 lines (56 loc) · 1.85 KB
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
from sklearn.decomposition import PCA
import numpy as np
import pandas as pd
# preprocessing data
def applyPCA(data1, data2):
# training data
data1 = data1.sample(frac=1).reset_index(drop=True) # shuffling
labels1 = data1.label
digits1 = data1.drop(['label'], axis=1)
# test data
labels2 = data2.label
digits2 = data2.drop(['label'], axis=1)
# preprocessing data
digits1 = digits1/255.0
digits2 = digits2/255.0
# make an instance of PCA model
pca = PCA(0.9)
# fit on training set only
pca.fit(digits1)
# apply transform to both training and test set
digits1pca = pca.transform(digits1)
digits2pca = pca.transform(digits2)
size = 10000
# creating a file with PCA training set
df1 = pd.DataFrame(digits1pca[:size])
df1['label'] = labels1[:size]
df1.to_csv('trainPCA.csv')
# creating a file with PCA test set
df2 = pd.DataFrame(digits2pca)
df2['label'] = labels2
df1.to_csv('testPCA.csv')
return {"imgTrain": digits1pca[:size],
"imgTest": digits2pca,
"labelTrain": labels1[:size],
"labelTest": labels2
}
# computing polynomial kernel
def polyKernel(X, Y, polyDegree):
m1,_ = X.shape
m2,_ = Y.shape
K = np.zeros((m1, m2))
for i in range(m1):
for j in range(m2):
print(i,j)
K[i,j] = (np.dot(X[i].T, Y[j]) + 1) ** polyDegree
return K
if __name__ == '__main__':
digitTrain = pd.read_csv("dataset/mnist_train.csv")
digitTest = pd.read_csv("dataset/mnist_test.csv")
# loading training set and test set
data = applyPCA(digitTrain, digitTest)
# computing kernel for training, once for every degree
degree = 8
for i in range(degree):
kernelTrain = polyKernel(data["imgTrain"], data["imgTrain"], i+1)
np.savetxt('k{0}.csv'.format(i+1), kernelTrain, delimiter='\n')