-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlowDisco.py
More file actions
6996 lines (5722 loc) · 284 KB
/
FlowDisco.py
File metadata and controls
6996 lines (5722 loc) · 284 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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# %% [markdown]
# # Requisitos
# %%
#!pip install -r requirements.txt
#pip freeze > r.txt
#python3.11 -m venv venv
#source venv/bin/activate
#rm -rf venv
import pandas as pd
import pickle
import nltk
import os
from flask import Flask, request, jsonify
from flask_cors import CORS
import os, pickle
import networkx.drawing.nx_pydot as nx_pydot
import threading
import spacy
import numpy as np
import statistics
import seaborn as sns
import itertools
from pathlib import Path
import random
import sys
from datetime import datetime
import joblib
import pydot
import random
import json
import re
import math
from collections import Counter
import time
import hdbscan
import flask
from keybert import KeyBERT
from sentence_transformers import SentenceTransformer
from sklearn import metrics
from sklearn.cluster import HDBSCAN, DBSCAN, KMeans, OPTICS, AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import pairwise_distances_argmin_min
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from kneed import KneeLocator
import networkx as nx
from networkx.readwrite import json_graph
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
from rank_bm25 import BM25Okapi
from rake_nltk import Rake
import optuna
from optuna.storages import RDBStorage
import graphviz
from graphviz import Source
from langchain.llms.ollama import Ollama
import pickle
import matplotlib
matplotlib.use('Agg')
#import flask-cors
import re
import warnings
warnings.filterwarnings("ignore")
# ### Modelos de Sentence Transformers
# %%
nltk.download("stopwords")
nltk.download('punkt')
stopwords = nltk.corpus.stopwords.words("portuguese")
#Português
MODEL_ML = "paraphrase-multilingual-MiniLM-L12-v2"
#MODEL_ML = "rufimelo/bert-large-portuguese-cased-sts"
#MODEL_ML = "PORTULAN/serafim-100m-portuguese-pt-sentence-encoder"
#MODEL_ML = "PORTULAN/serafim-900m-portuguese-pt-sentence-encoder"
#Inglês
#MODEL_ML = "all-MiniLM-L6-v2"
#MODEL_ML ="all-mpnet-base-v2"
#MODEL_ML ="multi-qa-mpnet-base-cos-v1"
#MODEL_ML ="gtr-t5-base"
#MODEL_ML ="all-MiniLM-L12-v2"
#MODEL_ML ="gtr-t5-large"
# %% [markdown]
# ### Parâmetros
# Algoritmo
algorithm = "kmeans"
#algorithm = "keywords"
#algorithm = "hieraquico"
#algorithm = "dbscan"
#algorithm = "none"
# Labelling
labelling = "kbert"
#labelling = "keywords"
#labelling = "verbs"
#labelling = "closest"
#labelling = "llm"
#labelling = "none"
labelling_for_excel = [
#"kbert",
#"llm",
#"verbs",
#"closest",
# "none"
]
# Métrica a otimizar
metric_to_optimize = "silhouette"
#metric_to_optimize = "vmeasure"
#metric_to_optimize = "NONE"
# Datasets de treino
#filename = "DAs_train_emo.csv"
#filename = "MRDA_train.csv"
#filename = "Estado_Da_Nacao_21_julho_2021_falas_separadas.xlsx"
#filename = "Estado_da_Nacao_2025_CERTO.xlsx"
#filename = "Estado_Da_Nacao_17_julho_2025.xlsx"
#filename = "Estado_Da_Nacao_17_julho_2024.xlsx"
#filename = "Estado_Da_Nacao_20_julho_2023.xlsx"
#filename = "Estado_Da_Nacao_20_julho_2022.xlsx"
#filename = "Estado_Da_Nacao_21_julho_2021.xlsx"
filename = "24_TREINO.xlsx"
# Datasets de teste
#filename_test = "DAs_test_emo.csv"
#filename_test = "MRDA_test.csv"
#filename_test = "Estado_Da_Nacao_21_julho_2021_falas_separadas.xlsx"
#filename_test = "Estado_Da_Nacao_20_julho_2023.xlsx"
#filename_test = "Estado_Da_Nacao_20_julho_2022.xlsx"
#filename_test = "Estado_Da_Nacao_21_julho_2021.xlsx"
filename_test = "24_TESTE.xlsx"
#GENERICO OU POLITICA
TIPO_DATASET = "GENERICO"
#Valores de Threshold
#threshold = [0, 0.05, 0.1, 0.15, 0.2]
threshold = [0]
# Beta V-measure
beta = 1
# Número de trials para o optuna
n_trials = 5
#Se queremos colocar na label a contagem do número de utterances por cluster
count_utterances_label = False
#Sentimento do system (True = Transições com sentimento (cor)); False: Transições sem sentimento (a preto))
sentiment_system = True
#Se queremos colocar na label a contagem do número de utterances, o turno e tempo por cluster
turns_label = False
time_start_label = False
time_previous_label = False
#cluster = qd a cor do sentimento tem a ver com o sentimento médio destino
#transição = qd o sentimento médio é por transição origem->destino
#sentimento no fluxo (Opções: False | cluster | transition)
sentiment_in_flow = True
# Número de utterances passadas a considerar para o contexto (1 = sem contexto)
id_max = 1
# URL para o Ollama funcionar
llm_url = "http://localhost:8080"
#Diretoria
diretoria = filename +'_'+ algorithm +'_'+ labelling +'_'+ metric_to_optimize +'_'+ str(threshold[0]) +'_'+ str(n_trials) +'_'+ str(datetime.now())
os.makedirs('./Resultados/' + diretoria)
#print (diretoria)
amount_speakers = 0
#amount_speakers = ["USER", "SYSTEM"]
#amount_speakers = ["Rachel", "Ross", "Joey" , "Monica" , "Phoebe", "Chandler"]
#amount_speakers = ["Chandler"]
#amount_speakers = ["Presidente", "Primeiro-Ministro", "PSD", "PS", "CH"]
others = True
same_speakers = False
ENTIDADES_A_PROCESSAR = {}
#Dividir por categorias
#ENTIDADES_A_PROCESSAR = {
# "Esquerda": ["BE", "PCP", "PEV", "L", "PS"],
# "Direita": ["IL", "PSD", "CDS-PP", "CH"],
# "Outros_Partidos": ["PAN", "JPP"]
#}
# Meter só dois partidos
# ENTIDADES_A_PROCESSAR = {
# "PS": ["PS"],
# "PSD": ["PSD"]
# }
# Todos os partidos separados
#ENTIDADES_A_PROCESSAR = {
# "PS": ["PS"],
# "PSD": ["PSD"],
# "CH": ["CH"],
# "IL": ["IL"],
# "BE": ["BE"],
# "PCP": ["PCP"],
# "L": ["L"],
# "PAN": ["PAN"],
# "CDS-PP": ["CDS-PP"],
# "PEV": ["PEV"],
# "JPP": ["JPP"]
#}
# Governo
#BLOCO_MODERADOR = ["Presidente"]
#BLOCO_MODERADOR = ["Presidente", "Secretário", "Secretária"]
#BLOCO_GOVERNO_SPEAKERS = ["Primeiro-Ministro", "Ministro", "Ministra"]
# Se 'True', qualquer speaker que não esteja em ENTIDADES_A_PROCESSAR
# será agrupado num único nó chamado "Outros".
# Se 'False', eles serão simplesmente removidos do grafo.
#INCLUIR_OUTROS = True
n_nodes = 0
# %%
# Validation
val = {"validation":False, "val_filename":"24_TREINO.xlsx", "val_filename_test":"24_TREINO.xlsx", "val_model":"all-MiniLM-L6-v2"}
def normalize_dataset(df_initial, regex=None, removeGreetings=None, speaker=None):
"""Normalize turn_id by (all turn_id's/max turn_id) and some column names."""
df = df_initial.copy()
if "Tipo" in df.columns:
df = df[df["Tipo"].astype(str).str.lower().eq("fala")].copy()
else:
print("Coluna 'Tipo' não encontrada.")
# Também normaliza as ações
if "Tipo" in df.columns and "Ação" in df.columns:
mask_acoes = df["Tipo"].astype(str).str.lower() == "ação"
df.loc[mask_acoes, "Ação"] = df.loc[mask_acoes, "Ação"].astype(str).str.lower().str.strip()
# Padrões para substituição
url_pattern = r"https?://\S+"
url_placeholder = "xURLx"
user_tags_pattern = "@\\S+"
user_tags_placeholder = "xUSERNAMEx"
#Renomear as colunas
if "text" in df.columns:
df.rename(columns={"text": "utterance"}, inplace=True)
if "Utterance" in df.columns:
df.rename(columns={"Utterance": "utterance"}, inplace=True)
if "transcript" in df.columns:
df.rename(columns={"transcript": "utterance"}, inplace=True)
if "Msg" in df.columns:
df.rename(columns={"Msg": "utterance"}, inplace=True)
if "intent_title" in df.columns:
df.rename(columns={"intent_title": "trueLabel"}, inplace=True)
if "dialog_act" in df.columns:
df.rename(columns={"dialog_act": "trueLabel"}, inplace=True)
if "dialogue_act" in df.columns:
df.rename(columns={"dialogue_act": "trueLabel"}, inplace=True)
if "speaker" in df.columns:
df.rename(columns={"speaker": "Speaker"}, inplace=True)
if "user" in df.columns:
df.rename(columns={"user": "Speaker"}, inplace=True)
if "interlocutor" in df.columns:
df.rename(columns={"interlocutor": "Speaker"}, inplace=True)
if "trueLabel" in df.columns:
df["trueLabel"] = df["trueLabel"].replace(" ", "_", regex=True)
if 'trueLabel' in df.columns:
df['utterance']= df['utterance'].apply(lambda x: x.lower())
if 'trueLabel' in df.columns:
df.trueLabel = df.trueLabel.fillna('none')
if "Emotion" in df.columns:
df.rename(columns={"Emotion": "Emotion"}, inplace=True)
# Substituição de padrões usando expressões regulares
if regex is True:
df["utterance"] = df["utterance"].replace(
to_replace=url_pattern, value=url_placeholder, regex=True
)
df["utterance"] = df["utterance"].replace(
to_replace=user_tags_pattern, value=user_tags_placeholder, regex=True
)
if speaker == "both":
df = df
if 'Speaker' in df.columns:
df['Speaker'] = df['Speaker'].replace('USR', 'USER')
df['Speaker'] = df['Speaker'].replace('Cliente', 'USER')
df['Speaker'] = df['Speaker'].replace('SERVICE', 'SYSTEM')
df['Speaker'] = df['Speaker'].replace('SYS', 'SYSTEM')
df['Speaker'] = df['Speaker'].replace('Automaise', 'SYSTEM')
df['Speaker'] = df['Speaker'].str.strip()
# Criação de 'dialogue_id' com base no 'turn_id'
if 'dialogue_id' not in df.columns and 'turn_id' in df.columns:
dialog = 0
result = []
i_anterior = -1
for i in df['turn_id']:
if i_anterior == -1 or i > i_anterior:
i_anterior = i
else:
dialog = dialog + 1
i_anterior = -1
result.append(dialog)
df['dialogue_id'] = result
# Criação de 'turn_id' com base no 'dialogue_id'
if 'turn_id' not in df.columns and 'dialogue_id' in df.columns:
df['turn_id'] = df.groupby('dialogue_id').cumcount()
#create variable which is a incremental sequence by number of utterances
df['sequence'] = [i for i in range(len(df))]
return df
def compute_weighted_mean(df, id_max=99999, sep=False, opt=1):
df = df.sort_values(by=['dialogue_id', 'turn_id']).reset_index(drop=True)
weighted_vectors = [None] * len(df) # Initialize the list with None to maintain alignment
if sep:
grouped = df.groupby(['dialogue_id', 'Speaker'])
else:
grouped = df.groupby('dialogue_id')
for name, group in grouped:
sum_weighted_vectors = []
for idx, row in group.iterrows():
vector = row['vectors']
if len(sum_weighted_vectors) >= id_max:
sum_weighted_vectors.pop(0)
sum_weighted_vectors.append(vector)
sum_weights = range(1, len(sum_weighted_vectors) + 1)
if opt == 2:
weighted_mean_vector = np.concatenate(np.mean(sum_weighted_vectors[:-1], axis=0), sum_weighted_vectors[-1])
else:
weighted_mean_vector = sum(sum_weighted_vectors[g] * sum_weights[g] / sum(sum_weights) for g in range(len(sum_weighted_vectors)))
weighted_vectors[idx] = weighted_mean_vector
df['vectors_weight'] = weighted_vectors
return df
#Para a política
def mapear_entidade_dinamica(row, ano, gov_partido, entidades_map, incluir_outros=True):
speaker_nome = str(row.get('Speaker', ''))
partido_nome = str(row.get('Partido', ''))
tipo = str(row.get('Tipo', ''))
# 1. Tratar de Ações
if tipo.lower() == 'ação':
return 'Acao'
# 2. Tratar do Governo (pelo nome do Speaker)
for gov_speaker in BLOCO_GOVERNO_SPEAKERS:
if gov_speaker in speaker_nome:
return "GOV"
# 3. Tratar do Presidente
if any(mod in speaker_nome for mod in BLOCO_MODERADOR):
return "Presidente"
# 4. Tratar de Partidos
partido_real = partido_nome if pd.notna(partido_nome) and partido_nome else speaker_nome
partido_real_upper = partido_real.upper()
for nome_no, lista_partidos in entidades_map.items():
for p in lista_partidos:
# Cria um padrão que procura a palavra exata. Assim "PS" não é encontrado dentro de "PSD" por ex
padrao = r'\b' + re.escape(p.upper()) + r'\b'
if re.search(padrao, partido_real_upper):
return nome_no # Retorna a CHAVE (ex: PS, PSD)
return "Outros" if incluir_outros else None
cores_personalizadas = {}
def atribuir_cor_friends(speaker):
cores_fixas = {
"Rachel": "#FF6B6B", "Joey": "#FF9966", "Monica": "#66CDAA",
"Ross": "#6A5ACD", "Chandler": "#B266FF", "Phoebe": "#FF69B4",
"Others": "#40E0D0", "User": "#33CCFF", "System": "#3300FF",
"SOD": "#FFD700", "EOD": "#FFD700"
}
if speaker in cores_fixas:
return cores_fixas[speaker]
if speaker in cores_personalizadas:
return cores_personalizadas[speaker]
# gera cor nova
cores_usadas = set(cores_fixas.values()).union(cores_personalizadas.values())
while True:
cor_aleatoria = "#" + "".join(random.choices("0123456789ABCDEF", k=6))
if cor_aleatoria not in cores_usadas:
cores_personalizadas[speaker] = cor_aleatoria
return cor_aleatoria
def use_sentence_transformer(sentences, model):
# Frases são codificadas chamando model.encode()
embeddings = model.encode(sentences)
vectors = np.array(embeddings)
return vectors
#Silhouette Score
def silhouette_method(data, min_k, max_k, incr):
number_clusters = 0
atual_silhouette = 0.000
# Prepare the scaler
scale = StandardScaler().fit(data)
# Fit the scaler
scaled_data = pd.DataFrame(scale.fit_transform(data))
# Para o método de silhouette, k precisa começar a partir de 2
n_clusters_axis = range(min_k, max_k, incr)
silhouettes = []
# Ajustar o modelo
for k in n_clusters_axis:
kmeans = KMeans(n_clusters=k, init="k-means++", random_state=2)
kmeans.fit(scaled_data)
score = metrics.silhouette_score(scaled_data, kmeans.labels_)
silhouettes.append(score)
if score > atual_silhouette:
number_clusters = k
atual_silhouette = score
#Gerar o grafo de dispersão
scatter_plot = sns.scatterplot(
x=n_clusters_axis, y=silhouettes)
#Usa a função get_figure e armazena o gráfico em uma variável (scatter_fig)
scatter_fig = scatter_plot.get_figure()
# Guarda o gráfico
scatter_fig.savefig('scatterplot.png')
return number_clusters
# %% [markdown]
# #### K-means
# Função para treinar o modelo KMeans e guardar os resultados num ficheiro pickle
def clustering_kmeans(vectors, n_clusters, nomeFichPickle, max_iters=2500):
# Verifica se o modelo KMeans já foi treinado e guardado
if not os.path.exists(nomeFichPickle):
# Se o modelo ainda não foi treinado, executar o KMeans
kmeans = KMeans(n_clusters=n_clusters, init="k-means++", max_iter=max_iters, random_state=2)
kmeans.fit(vectors)
# Obtém rótulos de cluster e centros de cluster
labels_kmeans = kmeans.labels_
centers_kmeans = kmeans.cluster_centers_
print("\nInternal Evaluation:\nSilhouette Score: ", metrics.silhouette_score(vectors, labels_kmeans))
print("Davies-Bouldin Index (DBI): ", metrics.davies_bouldin_score(vectors, labels_kmeans))
# Guarda o modelo KMeans treinado num ficheiro pickle
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'wb') as file:
pickle.dump((labels_kmeans, centers_kmeans), file)
else:
# Se o modelo já foi treinado e guardado, carrega-o do ficheiro pickle
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'rb') as file:
labels_kmeans, centers_kmeans = pickle.load(file)
return labels_kmeans, centers_kmeans
# ### Topic Modeling
# %%
def bertopic_modeling(utterances, model_ml, n_topics, min_topic_size):
model = BERTopic(embedding_model=model_ml, nr_topics=n_topics)
topics, probabilities = model.fit_transform(utterances)
return model, topics, probabilities
# %%
def objective_bertopic(trial, vectors, utterances):
utterances = [str(doc) for doc in utterances if isinstance(doc, str) and doc.strip()]
n_topics = trial.suggest_int("n_topics", 2, 10)
min_topic_size = trial.suggest_int("min_topic_size", 2, 10)
# Criação do modelo BERTopic
topic_model = BERTopic(nr_topics=n_topics, min_topic_size=min_topic_size)
# Ajuste do modelo aos dados
topics, probs = topic_model.fit_transform(utterances)
# Cálculo do Silhouette Score usando os tópicos atribuídos
silhouette = silhouette_score(vectors, topics)
return silhouette
def clustering_bertopic_optuna(vectors, utterances, role, metric, nomeFichPickle, n_trials=5):
labels_topic_model = None
silhouette_topic_model = None
n_topics = None
best_params = None
# Configurar a base de dados para armazenar trials
storage_path = "sqlite:///optuna_studies.db"
storage = RDBStorage(url=storage_path)
# Limpeza dos utterances para garantir que sejam apenas strings
cleaned_utterances = [str(doc) for doc in utterances if isinstance(doc, str) and doc.strip()]
# Se o modelo já foi treinado e guardado, carrega-o do ficheiro pickle
if os.path.exists(nomeFichPickle):
with open(nomeFichPickle, 'rb') as file:
topic_model = pickle.load(file)
# Precisamos passar os documentos (cleaned_utterances) para get_document_info()
topics = topic_model.get_document_info(cleaned_utterances)["Topic"]
silhouette_topic_model = silhouette_score(vectors, topics)
params = topic_model.get_params()
print(f"Modelo já existente para {role}. Carregando os resultados guardados.")
print(f"Hiperparâmetros carregados do pickle para {role}: {params}")
print(f"Melhor {metric} Score carregado do pickle para {role}: {silhouette_topic_model}")
else:
# Se não existe um modelo, realiza a otimização com o Optuna
study = optuna.create_study(direction="maximize", storage=storage)
study.optimize(lambda trial: objective_bertopic(trial, vectors, cleaned_utterances), n_trials=n_trials)
best_trial = study.best_trial # Obtém a melhor tentativa
best_params = best_trial.params
n_topics = best_params['n_topics']
min_topic_size = best_params['min_topic_size']
# Criação do modelo com os melhores parâmetros
topic_model = BERTopic(nr_topics=n_topics, min_topic_size=min_topic_size)
# Ajuste do modelo usando as utterances
topics, probs = topic_model.fit_transform(cleaned_utterances)
silhouette_topic_model = silhouette_score(vectors, topics)
# Guarda o modelo no ficheiro pickle
with open(nomeFichPickle, 'wb') as file:
pickle.dump(topic_model, file)
print(f"Melhores parâmetros encontrados para {role} na Função Silhouette:")
print(best_params)
print(f"Melhor Silhouette para {role}: {silhouette_topic_model}")
labels_topic_model = topics
return labels_topic_model, silhouette_topic_model, n_topics, best_params
#CLUSTERING -> K-MEANS
def objective_kmeans_silhouette(trial, vectors):
# Codifica as frases usando o modelo selecionado
n_clusters = trial.suggest_int('n_clusters', 3, 10)
init_method = trial.suggest_categorical('init_method', ['k-means++', 'random'])
n_init = trial.suggest_int('n_init', 1, 30)
tol = trial.suggest_float('tol', 1e-4, 1e-1, log=True)
algorithm = trial.suggest_categorical('algorithm', ['lloyd', 'elkan'])
kmeans = KMeans(
n_clusters=n_clusters,
init=init_method,
n_init=n_init,
tol=tol,
algorithm=algorithm,
random_state=2
)
kmeans.fit(vectors)
silhouette = metrics.silhouette_score(vectors, kmeans.labels_)
return silhouette
def clustering_kmeans_silhouette_optuna(vectors, role, metric, nomeFichPickle):
labels_kmeans = None
centers_kmeans = None
silhouette_kmeans = None
n_clusters = None
best_params = None
parameters_trial = None
study = None
# Configurar a base de dados para armazenar trials
storage_path = f"sqlite:///{os.path.join('./Resultados/' + diretoria, 'optuna_studies.db')}"
storage = RDBStorage(storage_path)
# Se o modelo já foi treinado e guardado, carrega-o do ficheiro pickle
if os.path.exists(nomeFichPickle):
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'rb') as file:
kmeans = pickle.load(file)
print("kmeans", kmeans)
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
params = kmeans.get_params()
silhouette_kmeans = metrics.silhouette_score(vectors, labels_kmeans)
print(f"Modelo já existente para {role}. Carregando os resultados guardados.")
print(f"Hiperparâmetros carregados do pickle para {role}: {params}")
print(f"Melhor {metric} Score carregado do pickle para {role}: {silhouette_kmeans}")
if params is not None:
n_clusters = params["n_clusters"]
else:
# Se o ficheiro pickle não existe, aplica o optuna
study_name = f"study_{role}"
study = optuna.create_study(
study_name=study_name,
storage=storage,
load_if_exists=True,
direction="maximize",
)
study.optimize(lambda trial: objective_kmeans_silhouette(trial, vectors), n_trials=n_trials)
best_trial = study.best_trial # Obtém a melhor tentativa
best_params = best_trial.params
n_clusters = best_params['n_clusters']
init = best_params['init_method']
n_init = best_params['n_init']
tol = best_params['tol']
algorithm = best_params['algorithm']
parameters_trial = {
'n_clusters': n_clusters,
'init_method': init,
'n_init': n_init,
'tol': tol,
'algorithm': algorithm
}
kmeans = KMeans(n_clusters=n_clusters, init=init, n_init=n_init, tol=tol, algorithm=algorithm, random_state=2)
kmeans.fit(vectors)
silhouette_kmeans = metrics.silhouette_score(vectors, kmeans.labels_)
# Guarda todos os resultados no ficheiro pickle
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'wb') as file:
pickle.dump(kmeans, file)
print(f"Melhores parâmetros encontrados para {role} na Função Silhouette:")
print(best_params)
print(f"Melhor Silhouette para {role}: {silhouette_kmeans}")
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
return labels_kmeans, centers_kmeans, silhouette_kmeans, n_clusters, study
#V-measure
#PARA DIALOGUE ACTS
def objective_kmeans_vmeasure(trial, vectors, normalized_df):
# Defino os parâmetros do KMeans a serem otimizados
n_clusters = trial.suggest_int('n_clusters', 3, 10)
init_method = trial.suggest_categorical('init_method', ['k-means++', 'random'])
n_init = trial.suggest_int('n_init', 1, 30)
tol = trial.suggest_float('tol', 1e-4, 1e-1, log=True)
algorithm = trial.suggest_categorical('algorithm', ['lloyd', 'elkan'])
# Configurar kmeans
kmeans = KMeans(
n_clusters=n_clusters,
init=init_method,
n_init=n_init,
max_iter=1000,
tol=tol,
algorithm=algorithm,
random_state=2
)
kmeans.fit(vectors)
if 'trueLabel' in normalized_df.columns:
true_labels = []
pred_labels = []
for idx in range(len(kmeans.labels_)):
# Obter o valor da coluna trueLabel para o índice idx
true_label_entry = normalized_df.iloc[idx]['trueLabel']
# Verificar se true_label_entry é uma string válida
if isinstance(true_label_entry, str):
utterance_true_labels = true_label_entry.split(',')
else:
raise ValueError(f"O 'trueLabel' na linha {idx} não está no formato esperado.")
cluster_label = kmeans.labels_[idx]
true_labels.extend(utterance_true_labels)
pred_labels.extend([cluster_label] * len(utterance_true_labels))
# Calcular as métricas
v_measure = metrics.v_measure_score(true_labels, pred_labels, beta=1.0)
silhouette_score = metrics.silhouette_score(vectors, kmeans.labels_)
adjusted_rand_score = metrics.adjusted_rand_score(true_labels, pred_labels)
completeness_score = metrics.completeness_score(true_labels, pred_labels)
homogeneity_score = metrics.homogeneity_score(true_labels, pred_labels)
calinski_harabasz_score = metrics.calinski_harabasz_score(vectors, kmeans.labels_)
davies_bouldin_score = metrics.davies_bouldin_score(vectors, kmeans.labels_)
# Adicionar os valores calculados aos atributos do trial
trial.set_user_attr(key='v_measure', value=float(v_measure))
trial.set_user_attr(key='silhouette_score', value=float(silhouette_score))
trial.set_user_attr(key='adjusted_rand_score', value=float(adjusted_rand_score))
trial.set_user_attr(key='completeness_score', value=float(completeness_score))
trial.set_user_attr(key='homogeneity_score', value=float(homogeneity_score))
trial.set_user_attr(key='calinski_harabasz_score', value=float(calinski_harabasz_score))
trial.set_user_attr(key='davies_bouldin_score', value=float(davies_bouldin_score))
print(f" Trial {trial.number}:")
print(f" Silhouette Score: {silhouette_score}")
print(f" V-Measure: {v_measure}")
print(f" Adjusted Rand Score: {adjusted_rand_score}")
print(f" Completeness Score: {completeness_score}")
print(f" Homogeneity Score: {homogeneity_score}")
print(f" Calinski-Harabasz Score: {calinski_harabasz_score}")
print(f" Davies-Bouldin Score: {davies_bouldin_score}")
return v_measure
else:
silhouette_score = metrics.silhouette_score(vectors, kmeans.labels_)
print("Como o dataset não está anotado, não é possível calcular a V-measure e foi retornada a Silhouette score.")
return silhouette_score
def clustering_kmeans_vmeasure_optuna(vectors, normalized_df, role, nomeFichPickle, val={}):
labels_kmeans = None
centers_kmeans = None
n_clusters = None
study = None
# Configurar a base de dados para armazenar trials
storage_path = f"sqlite:///{os.path.join('./Resultados/' + diretoria, 'optuna_studies.db')}"
storage = RDBStorage(storage_path)
# Se o ficheiro pickle não existe, aplicar o optuna
# Se for para validar configurações de um dataset diferente
if val["validation"]:
# Colocar path do melhor modelo
best_model_path = f'models/{val["val_model"]}/{val["val_filename"]}/vmeasure/kmeans_{role}.pkl'
with open(os.path.join('./Resultados/' + diretoria, best_model_path), 'rb') as file:
kmeans = pickle.load(file)
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
best_params = kmeans.get_params()
n_clusters = best_params['n_clusters']
init = best_params['init']
n_init = best_params['n_init']
tol = best_params['tol']
algorithm= best_params['algorithm']
kmeans = KMeans(n_clusters=n_clusters, init=init, n_init=n_init, tol=tol, algorithm=algorithm, random_state=2)
kmeans.fit(vectors)
silhouette_kmeans = metrics.silhouette_score(vectors, kmeans.labels_)
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'wb') as file:
pickle.dump(kmeans, file)
print(f"Melhores parâmetros encontrados para {role}:")
print(best_params)
print(f"Melhor Silhouette para {role}: {silhouette_kmeans}")
print(f"Modelo já existente para {role}. Carregando os resultados guardados.")
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
elif os.path.exists(nomeFichPickle):
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'rb') as file:
kmeans = pickle.load(file)
print("kmeans", kmeans)
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
print(f"Modelo já existente para {role}. Carregando os resultados guardados.")
else:
study_name = f"study_{role}"
study = optuna.create_study(
study_name=study_name,
storage=storage,
load_if_exists=True,
direction="maximize",
)
study.optimize(lambda trial: objective_kmeans_vmeasure(trial, vectors, normalized_df), n_trials=n_trials)
best_trial = study.best_trial
best_params = best_trial.params
n_clusters = best_params['n_clusters']
init = best_params['init_method']
n_init = best_params['n_init']
tol = best_params['tol']
algorithm = best_params['algorithm']
parameters_trial = {
'n_clusters': n_clusters,
'init_method': init,
'n_init': n_init,
'tol': tol,
'algorithm': algorithm
}
kmeans = KMeans(n_clusters=n_clusters, init=init, n_init=n_init, tol=tol, algorithm=algorithm, random_state=2)
kmeans.fit(vectors)
print (vectors)
print(f"Melhores parâmetros encontrados para {role} na Otimização da V-measure:")
print(best_params)
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'wb') as file:
pickle.dump(kmeans, file)
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
return labels_kmeans, centers_kmeans, n_clusters, study
#Outra métrica
# %%
#CLUSTERING -> K-MEANS
def objective_kmeans_nova_func(trial, vectors, n_clusters_ant, best_silhouette):
n_clusters_ideal = 5
n_clusters = trial.suggest_int('n_clusters', 3, 10)
init_method = trial.suggest_categorical('init_method', ['k-means++', 'random'])
n_init = trial.suggest_int('n_init', 1, 30)
tol = trial.suggest_float('tol', 1e-4, 1e-1, log=True)
algorithm = trial.suggest_categorical('algorithm', ['lloyd', 'elkan'])
print("n_clusters 1", n_clusters)
kmeans = KMeans(
n_clusters=n_clusters,
init=init_method,
n_init=n_init,
tol=tol,
algorithm=algorithm,
random_state=2
)
kmeans.fit(vectors)
# Se o num de clusters que vem da função objetivo da silhouette for igual ao num de clusters ideal (5), passamos o num de clusters ideal para 6
objective_value = best_silhouette - (math.log(1 + (abs(n_clusters_ant - n_clusters_ideal))) / n_clusters_ideal)
return objective_value
def clustering_kmeans_nova_func_optuna(vectors, role, metric, nomeFichPickle, n_clusters_ant, best_silhouette):
labels_kmeans = None
centers_kmeans = None
silhouette_kmeans = None
n_clusters = None
best_params = None
parameters_trial = None
# Se o modelo já foi treinado e guardado, carrega-o do ficheiro pickle
if os.path.exists(nomeFichPickle):
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'rb') as file:
data = pickle.load(file)
labels_kmeans, centers_kmeans, params, silhouette_kmeans = data.get('labels'), data.get('centers'), data.get('params'), data.get('silhouette')
print(f"Modelo já existente para {role}. Carregando os resultados guardados.")
print(f"Hiperparâmetros carregados do pickle para {role}: {params}")
print(f"Melhor Silhouette Score carregado do pickle para {role}: {silhouette_kmeans}")
else:
# Se o ficheiro pickle não existe, aplica o optuna
study = optuna.create_study(direction="maximize") # Queremos o melhor valor
objective_func = lambda trial: objective_kmeans_nova_func(trial, vectors, n_clusters_ant, best_silhouette)
study.optimize(objective_func, n_trials=1)
best_trial = study.best_trial # Obtém a melhor tentativa
best_params = best_trial.params
n_clusters = best_params['n_clusters']
init = best_params['init_method']
n_init = best_params['n_init']
tol = best_params['tol']
algorithm = best_params['algorithm']
kmeans = KMeans(n_clusters=n_clusters, init=init, n_init=n_init, tol=tol, algorithm=algorithm, random_state=2)
kmeans.fit(vectors)
silhouette_kmeans = metrics.silhouette_score(vectors, kmeans.labels_)
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'wb') as file:
pickle.dump({'labels': kmeans.labels_, 'centers': centers_kmeans, 'params': best_params,'silhouette': silhouette_kmeans}, file)
print(f"Melhores parâmetros encontrados para {role} na Nova Função de Maximização:")
print(best_params)
print(f"Nova Silhouette para {role}: {silhouette_kmeans}")
labels_kmeans, centers_kmeans = kmeans.labels_, kmeans.cluster_centers_
return labels_kmeans, centers_kmeans, silhouette_kmeans, n_clusters, best_params
#CLUSTERING -> HIERÁRQUICO
def objective_hierarquico_silhouette(trial, vectors):
n_clusters = trial.suggest_int('n_clusters', 2, 20)
linkage_method = trial.suggest_categorical('linkage', ['ward', 'complete', 'average', 'single'])
if linkage_method == 'ward':
metric = 'euclidean' # Se a linkage for 'ward', a métrica é sempre 'euclidean'
else:
metric = trial.suggest_categorical('metric', ['euclidean', 'l1', 'l2', 'manhattan', 'cosine'])
hierarchical = AgglomerativeClustering(
n_clusters=n_clusters,
linkage=linkage_method,
metric=metric
)
hierarchical.fit(vectors)
silhouette = metrics.silhouette_score(vectors, hierarchical.labels_)
return silhouette
# Função de clustering Hierárquico com Optuna
def clustering_hierarquico_silhouette_optuna(vectors, role, nomeFichPickle):
labels_hierarchical = None
study = None
silhouette_hierarquico = None
n_clusters = None
# Se o modelo já foi treinado e guardado, carrega-o do ficheiro pickle
if os.path.exists(nomeFichPickle):
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'rb') as file:
data = pickle.load(file)
labels_hierarchical, params, silhouette_hierarquico = data.get('labels'), data.get('params'), data.get('silhouette')
print(f"Modelo já existente para {role}. Carregando os resultados guardados.")
print(f"Hiperparâmetros carregados do pickle para {role}: {params}")
print(f"Melhor Silhouette Score carregado do pickle para {role}: {silhouette_hierarquico}")
else:
# Se o ficheiro pickle não existe, aplica o optuna
# Garante que é executado até que os resultados estejam disponíveis
while labels_hierarchical is None:
study = optuna.create_study(direction="maximize")
objective_func = lambda trial: objective_hierarquico_silhouette(trial, vectors)
study.optimize(objective_func, n_trials=5)
best_params = study.best_params
n_clusters = best_params['n_clusters']
linkage_method = best_params['linkage']
hierarchical = AgglomerativeClustering(n_clusters=n_clusters, linkage=linkage_method)
hierarchical.fit(vectors)
silhouette_hierarquico = metrics.silhouette_score(vectors, hierarchical.labels_)
with open(os.path.join('./Resultados/' + diretoria, nomeFichPickle), 'wb') as file:
pickle.dump({'labels': hierarchical.labels_, 'params': best_params,'silhouette': silhouette_hierarquico}, file)
print(f"Melhores parâmetros encontrados para {role} na Função Silhouette:")
print(best_params)
print(f"Melhor Silhouette para {role}: {silhouette_hierarquico}")
labels_hierarchical = hierarchical.labels_
return labels_hierarchical, silhouette_hierarquico, n_clusters
#CLUSTERING -> HIERÁRQUICO
def objective_hierarquico_nova_func(trial, vectors, n_clusters_ant, best_silhouette):
n_clusters_ideal = 5
n_clusters = trial.suggest_int('n_clusters', 2, 20)
linkage_method = trial.suggest_categorical('linkage', ['ward', 'complete', 'average', 'single'])
if linkage_method == 'ward':
metric = 'euclidean' # Se a linkage for 'ward', a métrica é sempre 'euclidean'
else:
metric = trial.suggest_categorical('metric', ['euclidean', 'l1', 'l2', 'manhattan', 'cosine'])
hierarchical = AgglomerativeClustering(
n_clusters=n_clusters,