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
12Anatreada_graphical=
False
13if (Anatreada_graphical):
14 import matplotlib.pyplot
as plt
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)
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"""
53 sum_of_squared_distances = []
57 km = KMeans(n_clusters=k)
58 km = km.fit(data_frame)
59 sum_of_squared_distances.append(km.inertia_)
61 x = range(1, len(sum_of_squared_distances)+1)
63 kn = KneeLocator(x, sum_of_squared_distances, curve=
'convex', direction=
'decreasing')
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')
77def pca_on_one_node(nodes_json_text):
81 json_dict = json.loads(nodes_json_text)
85 nodes_list = json_dict[
"nodes"]
86 nodes_list_clean = nodes_list
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)
105 df_nodes_normalized = pd.json_normalize(nodes_list_clean)
109 df_column_tag_normalized = df_nodes_normalized[
"tags"]
110 print(df_column_tag_normalized)
113 df_tags_normalized = pd.DataFrame()
120 for i
in range(0, len(df_column_tag_normalized)):
124 for j
in range(0, len(df_column_tag_normalized[i])):
126 newline = df_column_tag_normalized[i][j]
127 newline = newline.replace(
"{",
"")
128 newline = newline.replace(
"}",
"")
132 list_line = newline.split(
',')
135 tag_name = list_line[0]
138 if len(list_line) > 1:
139 value_min = list_line[1]
141 value_man = list_line[3]
142 dict_line[tag_name] = float(value)
145 if j == len(df_column_tag_normalized[i]) -1 :
146 tag_lines.append(dict_line)
150 df_tags_normalized = pd.json_normalize(tag_lines)
161 features = df_tags_normalized.columns.values
167 for feature
in features:
168 df_tags_normalized[feature] = df_tags_normalized[feature].replace(np.NAN, df_tags_normalized[feature].mean())
170 nb_lines, nb_columns = df_tags_normalized.shape
171 print(df_tags_normalized)
179 knee = elbow_method_for_optimal_K(df_tags_normalized)
180 model = KMeans(n_clusters = knee)
181 model.fit(df_tags_normalized)
184 prediction = np.arange(len(features))
185 predicted_label = model.predict([prediction])
188 labels = model.labels_
189 clusters = model.cluster_centers_
192 features_labels = np.append(features,
'group')
195 labels = np.reshape(labels, (nb_lines, 1))
198 final_df_tags_normalized = np.concatenate([df_tags_normalized, labels], axis=1)
201 tags_dataset = pd.DataFrame(final_df_tags_normalized)
202 tags_dataset.columns = features_labels
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
208 for i in range(0, len(clusters)):
211 name_group = str(i) + "_group"
213 name_group = "0" + str(i) + "_group"
214 tags_dataset["group"].replace(i, name_group, inplace = True)
215 targets = np.append(targets, name_group)
219 targets = np.empty(0)
221 for i
in range(0, len(clusters)):
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)
231 x = tags_dataset.loc[:, features].values
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)
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"])
250 if (Anatreada_graphical):
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)
262 for target
in targets:
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)
274 plt.legend(targets,prop={
"size": 15})
282 for i in range(0, len(nodes_list_clean)):
283 nodes_list_clean[i]["tags"].append("{" + tags_dataset["group"][i] + "}")
286 for i
in range(0, len(nodes_list)):
287 nodes_list_clean[i][
"tags"].append(tags_dataset[
"group"][i])
289 nodes_dict_node = dict()
290 nodes_dict_node[
"nodes"] = nodes_list_clean
292 json_tiles_text = json.dumps(nodes_dict_node)
294 return json_tiles_text
297def pca_on_multiple_nodes(nodes_json_text):
301 json_dict = json.loads(nodes_json_text)
305 nodes_list = json_dict[
"nodes"]
306 nodes_list_clean = nodes_list
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)
325 df_nodes_normalized = pd.json_normalize(nodes_list_clean)
329 df_column_tag_normalized = df_nodes_normalized[
"tags"]
330 print(df_column_tag_normalized)
333 df_tags_normalized = pd.DataFrame()
340 for i
in range(0, len(df_column_tag_normalized)):
344 for j
in range(0, len(df_column_tag_normalized[i])):
346 newline = df_column_tag_normalized[i][j]
347 newline = newline.replace(
"{",
"")
348 newline = newline.replace(
"}",
"")
352 list_line = newline.split(
',')
355 tag_name = list_line[0]
358 if len(list_line) > 1:
359 value_min = list_line[1]
361 value_man = list_line[3]
362 dict_line[tag_name] = float(value)
365 if j == len(df_column_tag_normalized[i]) -1 :
366 tag_lines.append(dict_line)
370 df_tags_normalized = pd.json_normalize(tag_lines)
381 features = df_tags_normalized.columns.values
387 for feature
in features:
388 df_tags_normalized[feature] = df_tags_normalized[feature].replace(np.NAN, df_tags_normalized[feature].mean())
390 nb_lines, nb_columns = df_tags_normalized.shape
391 print(df_tags_normalized)
399 knee = elbow_method_for_optimal_K(df_tags_normalized)
400 model = KMeans(n_clusters = knee)
401 model.fit(df_tags_normalized)
404 prediction = np.arange(len(features))
405 predicted_label = model.predict([prediction])
408 labels = model.labels_
409 clusters = model.cluster_centers_
412 features_labels = np.append(features,
'group')
415 labels = np.reshape(labels, (nb_lines, 1))
418 final_df_tags_normalized = np.concatenate([df_tags_normalized, labels], axis=1)
421 tags_dataset = pd.DataFrame(final_df_tags_normalized)
422 tags_dataset.columns = features_labels
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
428 for i in range(0, len(clusters)):
431 name_group = str(i) + "_group"
433 name_group = "0" + str(i) + "_group"
434 tags_dataset["group"].replace(i, name_group, inplace = True)
435 targets = np.append(targets, name_group)
439 targets = np.empty(0)
441 for i
in range(0, len(clusters)):
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)
451 x = tags_dataset.loc[:, features].values
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)
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"])
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)
482 for target
in targets:
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)
494 plt.legend(targets,prop={
"size": 15})
502 for i in range(0, len(nodes_list_clean)):
503 nodes_list_clean[i]["tags"].append("{" + tags_dataset["group"][i] + "}")
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]
511 nodes_dict_node = dict()
512 nodes_dict_node[
"nodes"] = nodes_list_clean
514 json_tiles_text = json.dumps(nodes_dict_node)
516 groups_dict = json.dumps(groups_dict)
518 return (json_tiles_text, groups_dict)
523 with open(file)
as nodes_json_file:
527 json_dict = json.load(nodes_json_file)
531 nodes_list = json_dict[
"nodes"]
535 df_nodes_normalized = pd.json_normalize(nodes_list)
539 df_column_tag_normalized = df_nodes_normalized[
"tags"]
540 print(df_column_tag_normalized)
543 df_tags_normalized = pd.DataFrame()
550 for i
in range(0, len(df_column_tag_normalized)):
554 for j
in range(0, len(df_column_tag_normalized[i])):
556 newline = df_column_tag_normalized[i][j]
557 newline = newline.replace(
"{",
"")
558 newline = newline.replace(
"}",
"")
562 list_line = newline.split(
',')
565 tag_name = list_line[0]
568 if len(list_line) > 1:
569 value_min = list_line[1]
571 value_man = list_line[3]
572 dict_line[tag_name] = float(value)
575 if j == len(df_column_tag_normalized[i]) -1 :
576 tag_lines.append(dict_line)
580 df_tags_normalized = pd.json_normalize(tag_lines)
591 features = df_tags_normalized.columns.values
597 for feature
in features:
598 df_tags_normalized[feature] = df_tags_normalized[feature].replace(np.NAN, df_tags_normalized[feature].mean())
600 nb_lines, nb_columns = df_tags_normalized.shape
601 print(df_tags_normalized)
609 knee = elbow_method_for_optimal_K(df_tags_normalized)
610 model = KMeans(n_clusters = knee)
611 model.fit(df_tags_normalized)
614 prediction = np.arange(len(features))
615 predicted_label = model.predict([prediction])
618 labels = model.labels_
619 clusters = model.cluster_centers_
622 features_labels = np.append(features,
'group')
625 labels = np.reshape(labels, (nb_lines, 1))
628 final_df_tags_normalized = np.concatenate([df_tags_normalized, labels], axis=1)
631 tags_dataset = pd.DataFrame(final_df_tags_normalized)
632 tags_dataset.columns = features_labels
635 targets = np.empty(0)
636 for i
in range(0, len(clusters)):
639 name_group = str(i) +
"_group"
641 name_group =
"0" + str(i) +
"_group"
642 tags_dataset[
"group"].replace(i, name_group, inplace =
True)
643 targets = np.append(targets, name_group)
649 x = tags_dataset.loc[:, features].values
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)
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"])
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)
680 for target
in targets:
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)
692 plt.legend(targets,prop={
"size": 15})
707 for i
in range(0, len(nodes_list)):
708 nodes_list[i][
"tags"].append(
"{" + tags_dataset[
"group"][i] +
"}")
710 json_tiles_text = json.dumps(nodes_list)
712 return json_tiles_text