-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassification knn mobile sensor loop.py
160 lines (112 loc) · 5.79 KB
/
classification knn mobile sensor loop.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns
from time import time
from sklearn.random_projection import johnson_lindenstrauss_min_dim, GaussianRandomProjection
class CustomGaussianRandomProjection(GaussianRandomProjection):
def __init__(self, n_components, eps, randomProjectionMatrix):
super().__init__(n_components=n_components, eps=eps)
self._randomProjectionMatrix = randomProjectionMatrix
def _make_random_matrix(self, n_components, n_features):
# TODO kasih if?
return self._randomProjectionMatrix
# ============================================================================
df_train = pd.read_csv('train.csv', delimiter = ',')
X_train_df = df_train.drop(['subject', 'Activity'],axis = 1).values
label_np = df_train['Activity'].values
# ----------------------------------------------------------------------------
label_np = label_np.ravel()
le = LabelEncoder()
y_train = le.fit_transform(label_np)
# ============================================================================
df_test = pd.read_csv('test.csv', delimiter = ',')
X_test_df = df_test.drop(['subject', 'Activity'], axis = 1).values
label_np_test = df_test['Activity'].values
# ----------------------------------------------------------------------------
label_np_test = label_np_test.ravel()
y_test = le.fit_transform(label_np_test)
# ============================================================================
df_train_test = df_train.append(df_test)
# ----------------------------------------------------------------------------
# =============================================================================
# print(df_train_test.describe())
# print()
# =============================================================================
# ----------------------------------------------------------------------------
# =============================================================================
# plt.title("Activities Count")
# ax = sns.countplot(x = "Activity", data = df_train_test)
# ax.set_xticklabels(ax.get_xticklabels(), rotation = 20, ha="right")
# plt.show()
# =============================================================================
# ============================================================================
y_pred = []
for j in range(2, 21):
creator = GaussianRandomProjection(n_components=j)
X = creator._make_random_matrix(j, X_train_df.shape[1])
transformer = CustomGaussianRandomProjection(j, 0.1, X)
X_train = transformer.fit_transform(X_train_df)
X_test = transformer.fit_transform(X_test_df)
k_min = 15
neighbors = np.arange(k_min,25)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
for i,k in enumerate(neighbors):
knn = KNeighborsClassifier(n_neighbors = k)
knn.fit(X_train, y_train)
#Compute accuracy on the training set
train_accuracy[i] = knn.score(X_train, y_train)
#Compute accuracy on the test set
test_accuracy[i] = knn.score(X_test, y_test)
# ----------------------------------------------------------------------------
plt.title(str(j) + ': k-NN Varying number of neighbors')
plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training accuracy')
plt.legend()
plt.xlabel('Number of neighbors')
plt.ylabel('Accuracy')
plt.show()
# ----------------------------------------------------------------------------
# =============================================================================
# print("Akurasi setiap K pada training set: ")
# for i, accuracy in enumerate(train_accuracy):
# print(str(i + k_min) + ": " + str(accuracy))
# print()
#
# # ----------------------------------------------------------------------------
#
# print("Akurasi setiap K pada test set: ")
# for i, accuracy in enumerate(test_accuracy):
# print(str(i + k_min) + ": " + str(accuracy))
# print()
# =============================================================================
# ----------------------------------------------------------------------------
highest_test_accuracy = test_accuracy.max()
k_highest_test_accuracy = np.argmax(test_accuracy) + k_min
print(str(j) + ": K terbaik adalah " + str(k_highest_test_accuracy) + " dengan akurasi test set sebesar " + str(highest_test_accuracy))
print()
# ============================================================================
start_time = time()
knn = KNeighborsClassifier(n_neighbors = k_highest_test_accuracy)
knn.fit(X_train, y_train)
# print("--- Waktu yang dibutuhkan untuk melatih model adalah %s detik ---" % (time() - start_time))
# print()
# print("Akurasi pada model KNN yang digunakan: " + str(knn.score(X_test, y_test)))
# print()
# ----------------------------------------------------------------------------
start_time = time()
y_pred.append(knn.predict(X_test))
# print("--- Waktu yang dibutuhkan untuk melakukan prediksi adalah %s detik ---" % (time() - start_time))
# print()
# =============================================================================
# plt.title('Confusion Matrix pada Test Set')
# sns.heatmap(confusion_matrix(y_pred, y_test), annot = True, annot_kws={"size": 16}, fmt='g')
# plt.show()
# =============================================================================
# ============================================================================