TiledViz
Loading...
Searching...
No Matches
anatreada.py
1import random
2import json
3import logging
4import numpy as np
5import pandas as pd
6from sklearn.linear_model import LinearRegression
7from sklearn.preprocessing import StandardScaler
8from sklearn.decomposition import PCA
9from sklearn.cluster import KMeans
10from kneed import KneeLocator
11
12Anatreada_graphical=False
13if (Anatreada_graphical):
14 import matplotlib.pyplot as plt
15
16# file : str
17try:
18 file = "../nodes.json"
19except FileNotFoundError as e:
20 print("File not found : the path to you 'nodes.json' may be uncorrect!")
21 logging.warning("An error occurred : " + e)
22
23
24# The json file should have this example of format :
25# {
26# "nodes": [
27# {
28# "title": "xxxxxxxxxx",
29# "url": "https://xxxxxxxxx/xxxxxxxxxxx.xxx",
30# "usersNotes": "xxxxxxx",
31# "comment": "xxxxxxxx",
32# "name": "xxxxxxxxxx",
33# "tags": [
34# "{tagName,minValue,value,maxValue}",
35# "{tagName1,minValue,value,maxValue}",
36# "{tagName2,minValue,value,maxValue}",
37# "tagName3"
38# ]
39# }
40# }
41
42def test(c):
43 return "test" + c
44
45def elbow_method_for_optimal_K(data_frame):
46 """DataFrame() -> void
47 Initialise k-means and use the inertia attribute
48 to identify the sum of squared distances of samples
49 to the nearest cluster centre.
50 Returns the optimal knee value"""
51
52 # sum_of_squared_distances : list()
53 sum_of_squared_distances = []
54 K = range(1,20)
55
56 for k in K:
57 km = KMeans(n_clusters=k)
58 km = km.fit(data_frame)
59 sum_of_squared_distances.append(km.inertia_)
60
61 x = range(1, len(sum_of_squared_distances)+1)
62
63 kn = KneeLocator(x, sum_of_squared_distances, curve='convex', direction='decreasing')
64 print(kn.knee)
65
66 """
67 plt.title('Elbow Method For Optimal k')
68 plt.xlabel('Number of clusters k')
69 plt.ylabel('Sum of squared distances')
70 plt.plot(x, sum_of_squared_distances, 'bx-')
71 plt.vlines(kn.knee, plt.ylim()[0], plt.ylim()[1], linestyles='dashed')
72 plt.show()
73 """
74
75 return kn.knee
76
77def pca_on_one_node(nodes_json_text):
78
79 # node_dict : dict()
80 # node_dict contains all the json text
81 json_dict = json.loads(nodes_json_text)
82
83 # nodes_list : list(dict())
84 # nodes_list contains all nodes/tiles information in a list of dictonaries format
85 nodes_list = json_dict["nodes"]
86 nodes_list_clean = nodes_list
87 # remove former "group" tag in tags list
88 # map(remove_group_from_list, nodes_list)
89
90 #for i in range(0, len(nodes_list)):
91 # for j in range(0, len(nodes_list[i]["tags"])) :
92 # if ("_group_" in nodes_list[i]["tags"][j]) and ("{" not in nodes_list[i]["tags"][j]) and ("}" not in nodes_list[i]["tags"][j]) :
93 # nodes_list_clean[i]["tags"].pop(j)
94
95
96 for i in range(0, len(nodes_list)):
97 for j, tag in enumerate(nodes_list_clean[i]["tags"]):
98 if ("_group_" in tag) and ("{" not in tag) and ("}" not in tag):
99 nodes_list_clean[i]["tags"].pop(j)
100 continue
101
102
103 # df_nodes_normalized : DataFrame()
104 # df_nodes_normalized contains the DataFrame of nodes_list_clean
105 df_nodes_normalized = pd.json_normalize(nodes_list_clean)
106
107 # df_column_tag_normalized : DataFrame()
108 # df_column_tag_normalized contains the DataFrame of tags column of df_nodes_normalized DataFrame
109 df_column_tag_normalized = df_nodes_normalized["tags"]
110 print(df_column_tag_normalized)
111 # tags_normalized : DataFrame()
112 # tags_normalized contains the DataFrame of node/tile tags
113 df_tags_normalized = pd.DataFrame()
114
115 # tag_lines : list(dict())
116 # tag_lines contains tags information in a dictionary format
117 tag_lines = []
118
119 #i : int
120 for i in range(0, len(df_column_tag_normalized)):
121 # dict_line : dict()
122 dict_line = dict()
123 # j : int
124 for j in range(0, len(df_column_tag_normalized[i])):
125
126 newline = df_column_tag_normalized[i][j]
127 newline = newline.replace("{", "")
128 newline = newline.replace("}", "")
129
130 # list_line : []
131 # list_line contains the list of elements of le string line
132 list_line = newline.split(',')
133
134 # tag_name : str
135 tag_name = list_line[0]
136
137 # if it's a variable tag
138 if len(list_line) > 1:
139 value_min = list_line[1]
140 value = list_line[2]
141 value_man = list_line[3]
142 dict_line[tag_name] = float(value)
143
144 # if the tag is the last of the node/tile
145 if j == len(df_column_tag_normalized[i]) -1 :
146 tag_lines.append(dict_line)
147 dict_line = {}
148
149
150 df_tags_normalized = pd.json_normalize(tag_lines)
151 #print("--------------------------------------- TAG DATAFRAME NORMALIZED -----------------------------------------------------------")
152 #print(df_tags_normalized)
153 #print("----------------------------------------------------------------------------------------------------------------------------")
154
155 # Drop rows with missing value -> uncomment the next line if you want it
156 # df_tags_normalized = df_tags_normalized.dropna()
157
158 # feature : list(str)
159 # features contains yhe list of column/feature names
160 features = []
161 features = df_tags_normalized.columns.values
162
163 # replacing NaN values by the median using -> .median()
164 # replacing NaN values by the mean average using -> .mean()
165 # replacing NaN values by the standard deviation using -> .std()
166
167 for feature in features:
168 df_tags_normalized[feature] = df_tags_normalized[feature].replace(np.NAN, df_tags_normalized[feature].mean())
169
170 nb_lines, nb_columns = df_tags_normalized.shape
171 print(df_tags_normalized)
172 # print("-------------------------------- TAG DATAFRAME NORMALIZED WITH MEAN INSTEAD OF NAN ------------------------------------------")
173 # print(df_tags_normalized)
174 # print("-----------------------------------------------------------------------------------------------------------------------------")
175
176 # --------------------------------------------- K-MEANS CLUSTERING ---------------------------------------------
177
178 # Declaring Model
179 knee = elbow_method_for_optimal_K(df_tags_normalized)
180 model = KMeans(n_clusters = knee)
181 model.fit(df_tags_normalized)
182
183 # Make a prediction
184 prediction = np.arange(len(features))
185 predicted_label = model.predict([prediction])
186
187 # Clustering ...
188 labels = model.labels_
189 clusters = model.cluster_centers_
190
191 # Add "group" column to features
192 features_labels = np.append(features, 'group')
193
194 # Reshape the array of labels to have a column shape
195 labels = np.reshape(labels, (nb_lines, 1))
196
197 # Concatenate arraya of data "df_tags_normalized" and labels "labels"
198 final_df_tags_normalized = np.concatenate([df_tags_normalized, labels], axis=1)
199
200 # Create tags dataset
201 tags_dataset = pd.DataFrame(final_df_tags_normalized)
202 tags_dataset.columns = features_labels
203
204 """
205 # Replace cluster number by a formated group name like "00_group"
206 targets = np.empty(0) # Will be used to attribut them a color in the graph
207
208 for i in range(0, len(clusters)):
209 name_group = ""
210 if i > 9:
211 name_group = str(i) + "_group"
212 else:
213 name_group = "0" + str(i) + "_group"
214 tags_dataset["group"].replace(i, name_group, inplace = True)
215 targets = np.append(targets, name_group)
216 """
217
218 # Replace cluster number by a formated group name like "00_group_1"
219 targets = np.empty(0) # Will be used to attribut them a color in the graph
220
221 for i in range(0, len(clusters)):
222 name_group = ""
223 name_group = "00" + "_group_" + str(i + 1)
224 tags_dataset["group"].replace(i, name_group, inplace = True)
225 targets = np.append(targets, name_group)
226
227 print(tags_dataset)
228 # --------------------------------------------- PCA ---------------------------------------------
229
230 # Assign values of tags dataset exept groups to x
231 x = tags_dataset.loc[:, features].values
232
233 # Normalizing the features : each feature of your data should be
234 # normally distributed such that it will scale the distribution
235 # to a mean of zero and a standard deviation of one
236 x = StandardScaler().fit_transform(x)
237 feat_cols = ["feature" + str(i) for i in range(0, x.shape[1])]
238 normalized_tags = pd.DataFrame(x, columns = feat_cols)
239
240 # print("Normalized tags : \n", normalized_tags.tail())
241
242 # Projecting the thirty-dimensional Tags Data to two-dimensional
243 pca_tags = PCA(n_components = 2)
244 principal_component_tags = pca_tags.fit_transform(x)
245 df_principal_tags = pd.DataFrame(data = principal_component_tags,
246 columns = ["Principal Component 1", "Principal Component 2"])
247
248 # print('Explained variation per principal component: {}'.format(pca_tags.explained_variance_ratio_))
249
250 if (Anatreada_graphical):
251 # Visualization of the n samples along the Principal Component - 1
252 # and Principal Component - 2 axis
253 plt.figure(figsize=(10,10))
254 plt.xticks(fontsize=12)
255 plt.yticks(fontsize=14)
256 plt.xlabel("Principal Component - 1",fontsize=20)
257 plt.ylabel("Principal Component - 2",fontsize=20)
258 plt.title("Principal Component Analysis of Tag Wikimedia Dataset (NaN -> mean average)",fontsize=20)
259
260 # Colors of clusters
261 colors = []
262 for target in targets:
263 r = random.random()
264 b = random.random()
265 g = random.random()
266 color = (r, g, b)
267 colors.append(color)
268
269 for target, color in zip(targets,colors):
270 indicesToKeep = tags_dataset["group"] == target
271 plt.scatter(df_principal_tags.loc[indicesToKeep, "Principal Component 1"]
272 , df_principal_tags.loc[indicesToKeep, "Principal Component 2"], c = color, s = 50)
273
274 plt.legend(targets,prop={"size": 15})
275
276 #plt.show()
277
278 # ------------------------------- Reformating Dataframe into json --------------------------------
279 # |_ get the column "group"
280 # |_ associate each row to each nodes with the following format : "{name_of_group}"
281 """
282 for i in range(0, len(nodes_list_clean)):
283 nodes_list_clean[i]["tags"].append("{" + tags_dataset["group"][i] + "}")
284 """
285 # |_ associate each row to each nodes with the following format : "name_of_group"
286 for i in range(0, len(nodes_list)):
287 nodes_list_clean[i]["tags"].append(tags_dataset["group"][i])
288
289 nodes_dict_node = dict()
290 nodes_dict_node["nodes"] = nodes_list_clean
291
292 json_tiles_text = json.dumps(nodes_dict_node)
293
294 return json_tiles_text
295
296
297def pca_on_multiple_nodes(nodes_json_text):
298
299 # node_dict : dict()
300 # node_dict contains all the json text
301 json_dict = json.loads(nodes_json_text)
302
303 # nodes_list : list(dict())
304 # nodes_list contains all nodes/tiles information in a list of dictonaries format
305 nodes_list = json_dict["nodes"]
306 nodes_list_clean = nodes_list
307 # remove former "group" tag in tags list
308 # map(remove_group_from_list, nodes_list)
309
310 #for i in range(0, len(nodes_list)):
311 # for j in range(0, len(nodes_list[i]["tags"])) :
312 # if ("_group_" in nodes_list[i]["tags"][j]) and ("{" not in nodes_list[i]["tags"][j]) and ("}" not in nodes_list[i]["tags"][j]) :
313 # nodes_list_clean[i]["tags"].pop(j)
314
315
316 for i in range(0, len(nodes_list)):
317 for j, tag in enumerate(nodes_list_clean[i]["tags"]):
318 if ("_group_" in tag) and ("{" not in tag) and ("}" not in tag):
319 nodes_list_clean[i]["tags"].pop(j)
320 continue
321
322
323 # df_nodes_normalized : DataFrame()
324 # df_nodes_normalized contains the DataFrame of nodes_list_clean
325 df_nodes_normalized = pd.json_normalize(nodes_list_clean)
326
327 # df_column_tag_normalized : DataFrame()
328 # df_column_tag_normalized contains the DataFrame of tags column of df_nodes_normalized DataFrame
329 df_column_tag_normalized = df_nodes_normalized["tags"]
330 print(df_column_tag_normalized)
331 # tags_normalized : DataFrame()
332 # tags_normalized contains the DataFrame of node/tile tags
333 df_tags_normalized = pd.DataFrame()
334
335 # tag_lines : list(dict())
336 # tag_lines contains tags information in a dictionary format
337 tag_lines = []
338
339 #i : int
340 for i in range(0, len(df_column_tag_normalized)):
341 # dict_line : dict()
342 dict_line = dict()
343 # j : int
344 for j in range(0, len(df_column_tag_normalized[i])):
345
346 newline = df_column_tag_normalized[i][j]
347 newline = newline.replace("{", "")
348 newline = newline.replace("}", "")
349
350 # list_line : []
351 # list_line contains the list of elements of le string line
352 list_line = newline.split(',')
353
354 # tag_name : str
355 tag_name = list_line[0]
356
357 # if it's a variable tag
358 if len(list_line) > 1:
359 value_min = list_line[1]
360 value = list_line[2]
361 value_man = list_line[3]
362 dict_line[tag_name] = float(value)
363
364 # if the tag is the last of the node/tile
365 if j == len(df_column_tag_normalized[i]) -1 :
366 tag_lines.append(dict_line)
367 dict_line = {}
368
369
370 df_tags_normalized = pd.json_normalize(tag_lines)
371 #print("--------------------------------------- TAG DATAFRAME NORMALIZED -----------------------------------------------------------")
372 #print(df_tags_normalized)
373 #print("----------------------------------------------------------------------------------------------------------------------------")
374
375 # Drop rows with missing value -> uncomment the next line if you want it
376 # df_tags_normalized = df_tags_normalized.dropna()
377
378 # feature : list(str)
379 # features contains yhe list of column/feature names
380 features = []
381 features = df_tags_normalized.columns.values
382
383 # replacing NaN values by the median using -> .median()
384 # replacing NaN values by the mean average using -> .mean()
385 # replacing NaN values by the standard deviation using -> .std()
386
387 for feature in features:
388 df_tags_normalized[feature] = df_tags_normalized[feature].replace(np.NAN, df_tags_normalized[feature].mean())
389
390 nb_lines, nb_columns = df_tags_normalized.shape
391 print(df_tags_normalized)
392 # print("-------------------------------- TAG DATAFRAME NORMALIZED WITH MEAN INSTEAD OF NAN ------------------------------------------")
393 # print(df_tags_normalized)
394 # print("-----------------------------------------------------------------------------------------------------------------------------")
395
396 # --------------------------------------------- K-MEANS CLUSTERING ---------------------------------------------
397
398 # Declaring Model
399 knee = elbow_method_for_optimal_K(df_tags_normalized)
400 model = KMeans(n_clusters = knee)
401 model.fit(df_tags_normalized)
402
403 # Make a prediction
404 prediction = np.arange(len(features))
405 predicted_label = model.predict([prediction])
406
407 # Clustering ...
408 labels = model.labels_
409 clusters = model.cluster_centers_
410
411 # Add "group" column to features
412 features_labels = np.append(features, 'group')
413
414 # Reshape the array of labels to have a column shape
415 labels = np.reshape(labels, (nb_lines, 1))
416
417 # Concatenate arraya of data "df_tags_normalized" and labels "labels"
418 final_df_tags_normalized = np.concatenate([df_tags_normalized, labels], axis=1)
419
420 # Create tags dataset
421 tags_dataset = pd.DataFrame(final_df_tags_normalized)
422 tags_dataset.columns = features_labels
423
424 """
425 # Replace cluster number by a formated group name like "00_group"
426 targets = np.empty(0) # Will be used to attribut them a color in the graph
427
428 for i in range(0, len(clusters)):
429 name_group = ""
430 if i > 9:
431 name_group = str(i) + "_group"
432 else:
433 name_group = "0" + str(i) + "_group"
434 tags_dataset["group"].replace(i, name_group, inplace = True)
435 targets = np.append(targets, name_group)
436 """
437
438 # Replace cluster number by a formated group name like "00_group_1"
439 targets = np.empty(0) # Will be used to attribut them a color in the graph
440
441 for i in range(0, len(clusters)):
442 name_group = ""
443 name_group = "00" + "_group_" + str(i + 1)
444 tags_dataset["group"].replace(i, name_group, inplace = True)
445 targets = np.append(targets, name_group)
446
447 print(tags_dataset)
448 # --------------------------------------------- PCA ---------------------------------------------
449
450 # Assign values of tags dataset exept groups to x
451 x = tags_dataset.loc[:, features].values
452
453 # Normalizing the features : each feature of your data should be
454 # normally distributed such that it will scale the distribution
455 # to a mean of zero and a standard deviation of one
456 x = StandardScaler().fit_transform(x)
457 feat_cols = ["feature" + str(i) for i in range(0, x.shape[1])]
458 normalized_tags = pd.DataFrame(x, columns = feat_cols)
459
460 # print("Normalized tags : \n", normalized_tags.tail())
461
462 # Projecting the thirty-dimensional Tags Data to two-dimensional
463 pca_tags = PCA(n_components = 2)
464 principal_component_tags = pca_tags.fit_transform(x)
465 df_principal_tags = pd.DataFrame(data = principal_component_tags,
466 columns = ["Principal Component 1", "Principal Component 2"])
467
468 # print('Explained variation per principal component: {}'.format(pca_tags.explained_variance_ratio_))
469
470 # Visualization of the n samples along the Principal Component - 1
471 # and Principal Component - 2 axis
472 if (Anatreada_graphical):
473 plt.figure(figsize=(10,10))
474 plt.xticks(fontsize=12)
475 plt.yticks(fontsize=14)
476 plt.xlabel("Principal Component - 1",fontsize=20)
477 plt.ylabel("Principal Component - 2",fontsize=20)
478 plt.title("Principal Component Analysis of Tag Wikimedia Dataset (NaN -> mean average)",fontsize=20)
479
480 # Colors of clusters
481 colors = []
482 for target in targets:
483 r = random.random()
484 b = random.random()
485 g = random.random()
486 color = (r, g, b)
487 colors.append(color)
488
489 for target, color in zip(targets,colors):
490 indicesToKeep = tags_dataset["group"] == target
491 plt.scatter(df_principal_tags.loc[indicesToKeep, "Principal Component 1"]
492 , df_principal_tags.loc[indicesToKeep, "Principal Component 2"], c = color, s = 50)
493
494 plt.legend(targets,prop={"size": 15})
495
496 #plt.show()
497
498 # ------------------------------- Reformating Dataframe into json --------------------------------
499 # |_ get the column "group"
500 # |_ associate each row to each nodes with the following format : "{name_of_group}"
501 """
502 for i in range(0, len(nodes_list_clean)):
503 nodes_list_clean[i]["tags"].append("{" + tags_dataset["group"][i] + "}")
504 """
505 # |_ associate each row to each nodes with the following format : "name_of_group"
506 groups_dict = dict()
507 for i in range(0, len(nodes_list)):
508 nodes_list_clean[i]["tags"].append(tags_dataset["group"][i])
509 groups_dict[nodes_list_clean[i]["id"]] = tags_dataset["group"][i]
510
511 nodes_dict_node = dict()
512 nodes_dict_node["nodes"] = nodes_list_clean
513
514 json_tiles_text = json.dumps(nodes_dict_node)
515
516 groups_dict = json.dumps(groups_dict)
517
518 return (json_tiles_text, groups_dict)
519
520
521def pca_test():
522
523 with open(file) as nodes_json_file:
524
525 # node_dict : dict()
526 # node_dict contains all the json file
527 json_dict = json.load(nodes_json_file)
528
529 # nodes_list : list(dict())
530 # nodes_list contains all nodes/tiles information in a list of dictonaries format
531 nodes_list = json_dict["nodes"]
532
533 # df_nodes_normalized : DataFrame()
534 # df_nodes_normalized contains the DataFrame of nodes_list
535 df_nodes_normalized = pd.json_normalize(nodes_list)
536
537 # df_column_tag_normalized : DataFrame()
538 # df_column_tag_normalized contains the DataFrame of tags column of df_nodes_normalized DataFrame
539 df_column_tag_normalized = df_nodes_normalized["tags"]
540 print(df_column_tag_normalized)
541 # tags_normalized : DataFrame()
542 # tags_normalized contains the DataFrame of node/tile tags
543 df_tags_normalized = pd.DataFrame()
544
545 # tag_lines : list(dict())
546 # tag_lines contains tags information in a dictionary format
547 tag_lines = []
548
549 #i : int
550 for i in range(0, len(df_column_tag_normalized)):
551 # dict_line : dict()
552 dict_line = dict()
553 # j : int
554 for j in range(0, len(df_column_tag_normalized[i])):
555
556 newline = df_column_tag_normalized[i][j]
557 newline = newline.replace("{", "")
558 newline = newline.replace("}", "")
559
560 # list_line : []
561 # list_line contains the list of elements of le string line
562 list_line = newline.split(',')
563
564 # tag_name : str
565 tag_name = list_line[0]
566
567 # if it's a variable tag
568 if len(list_line) > 1:
569 value_min = list_line[1]
570 value = list_line[2]
571 value_man = list_line[3]
572 dict_line[tag_name] = float(value)
573
574 # if the tag is the last of the node/tile
575 if j == len(df_column_tag_normalized[i]) -1 :
576 tag_lines.append(dict_line)
577 dict_line = {}
578
579
580 df_tags_normalized = pd.json_normalize(tag_lines)
581 #print("--------------------------------------- TAG DATAFRAME NORMALIZED -----------------------------------------------------------")
582 #print(df_tags_normalized)
583 #print("----------------------------------------------------------------------------------------------------------------------------")
584
585 # Drop rows with missing value -> uncomment the next line if you want it
586 # df_tags_normalized = df_tags_normalized.dropna()
587
588 # feature : list(str)
589 # features contains yhe list of column/feature names
590 features = []
591 features = df_tags_normalized.columns.values
592
593 # replacing NaN values by the median using -> .median()
594 # replacing NaN values by the mean average using -> .mean()
595 # replacing NaN values by the standard deviation using -> .std()
596
597 for feature in features:
598 df_tags_normalized[feature] = df_tags_normalized[feature].replace(np.NAN, df_tags_normalized[feature].mean())
599
600 nb_lines, nb_columns = df_tags_normalized.shape
601 print(df_tags_normalized)
602 # print("-------------------------------- TAG DATAFRAME NORMALIZED WITH MEAN INSTEAD OF NAN ------------------------------------------")
603 # print(df_tags_normalized)
604 # print("-----------------------------------------------------------------------------------------------------------------------------")
605
606 # --------------------------------------------- K-MEANS CLUSTERING ---------------------------------------------
607
608 # Declaring Model
609 knee = elbow_method_for_optimal_K(df_tags_normalized)
610 model = KMeans(n_clusters = knee)
611 model.fit(df_tags_normalized)
612
613 # Make a prediction
614 prediction = np.arange(len(features))
615 predicted_label = model.predict([prediction])
616
617 # Clustering ...
618 labels = model.labels_
619 clusters = model.cluster_centers_
620
621 # Add "group" column to features
622 features_labels = np.append(features, 'group')
623
624 # Reshape the array of labels to have a column shape
625 labels = np.reshape(labels, (nb_lines, 1))
626
627 # Concatenate arraya of data "df_tags_normalized" and labels "labels"
628 final_df_tags_normalized = np.concatenate([df_tags_normalized, labels], axis=1)
629
630 # Create tags dataset
631 tags_dataset = pd.DataFrame(final_df_tags_normalized)
632 tags_dataset.columns = features_labels
633
634 # Replace cluster number by a formated group name like "0_group"
635 targets = np.empty(0) # Will be used to attribut them a color in the graph
636 for i in range(0, len(clusters)):
637 name_group = ""
638 if i > 9:
639 name_group = str(i) + "_group"
640 else:
641 name_group = "0" + str(i) + "_group"
642 tags_dataset["group"].replace(i, name_group, inplace = True)
643 targets = np.append(targets, name_group)
644
645 print(tags_dataset)
646 # --------------------------------------------- PCA ---------------------------------------------
647
648 # Assign values of tags dataset exept groups to x
649 x = tags_dataset.loc[:, features].values
650
651 # Normalizing the features : each feature of your data should be
652 # normally distributed such that it will scale the distribution
653 # to a mean of zero and a standard deviation of one
654 x = StandardScaler().fit_transform(x)
655 feat_cols = ["feature" + str(i) for i in range(0, x.shape[1])]
656 normalized_tags = pd.DataFrame(x, columns = feat_cols)
657
658 # print("Normalized tags : \n", normalized_tags.tail())
659
660 # Projecting the thirty-dimensional Tags Data to two-dimensional
661 pca_tags = PCA(n_components = 2)
662 principal_component_tags = pca_tags.fit_transform(x)
663 df_principal_tags = pd.DataFrame(data = principal_component_tags,
664 columns = ["Principal Component 1", "Principal Component 2"])
665
666 # print('Explained variation per principal component: {}'.format(pca_tags.explained_variance_ratio_))
667
668 # Visualization of the n samples along the Principal Component - 1
669 # and Principal Component - 2 axis
670 if (Anatreada_graphical):
671 plt.figure(figsize=(10,10))
672 plt.xticks(fontsize=12)
673 plt.yticks(fontsize=14)
674 plt.xlabel("Principal Component - 1",fontsize=20)
675 plt.ylabel("Principal Component - 2",fontsize=20)
676 plt.title("Principal Component Analysis of Tag Wikimedia Dataset (NaN -> mean average)",fontsize=20)
677
678 # Colors of clusters
679 colors = []
680 for target in targets:
681 r = random.random()
682 b = random.random()
683 g = random.random()
684 color = (r, g, b)
685 colors.append(color)
686
687 for target, color in zip(targets,colors):
688 indicesToKeep = tags_dataset["group"] == target
689 plt.scatter(df_principal_tags.loc[indicesToKeep, "Principal Component 1"]
690 , df_principal_tags.loc[indicesToKeep, "Principal Component 2"], c = color, s = 50)
691
692 plt.legend(targets,prop={"size": 15})
693
694 # plt.show()
695
696 # => Observation :
697 # 1 - When missing data of samples are replacing by the mean or the median, the lack of
698 # relevant data set distorts the analysis. Clusters are not distinctive
699 # 2 - When samples containing missing data are removed from the data set, clusters are
700 # visible because of the accuracy of the data set.
701
702
703 # ------------------------------- Reformating Dataframe into json --------------------------------
704 # |_ get the column "group"
705 # |_ associate each row to each nodes with the following format : "{name_of_group}"
706
707 for i in range(0, len(nodes_list)):
708 nodes_list[i]["tags"].append("{" + tags_dataset["group"][i] + "}")
709
710 json_tiles_text = json.dumps(nodes_list)
711
712 return json_tiles_text
713