-
Notifications
You must be signed in to change notification settings - Fork 1
Equalização do projeto: adição de novos algoritmos, métodos e refatorações a main. #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
LuizMiguel4444
commented
Jan 9, 2025
- Adiciona novos algorítmos (FlexCon, FlexConC, FlexConG, SelfTraining).
- Adiciona documentação à classes que ainda não tinham.
- Adiciona arquivos de testes básicos (testFlex e testSelf).
- Refatoração de códigos para ficar de acordo com regras configuradas no pylint.
…arning into flexconC
…arning into flexconC
|
@LuizMiguel4444, esse PR está realmente pronto? Se eu tentar rodar o projeto vai rodar? Em uma parte do código ele está usando uma lib chamada |
ArthurGorgonio
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sugiro que revisem o código como um todo. Além disso, seria interessante vocês consultarem o material de apoio que vocês têm acerca do flexcon, flexcon-c e flexcon-g. Algumas das classes propostas não está de acordo com a proposta original dos métodos supracitados.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Esses imports não parecem certos, poderia corrigir para import o que realmente faz sentido a pessoa que está consumindo a biblioteca ver.
Esse arquivo init.py vai servir como uma interface do que a gente quer exportar para as outras pessoas usarem. Não faz sentido a gente exportar tudo, então sugiro uma revisão desse arquivo.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Arthur, pelo que entendi, o init.py deve ser feito basicamente quando já se tem o projeto quase pronto ou estável, quando o nosso esta um pouco distante disso, no momento acho melhor focar nas mais imediatas.
| @abstractmethod | ||
| def adjust_threshold(self, local_measure): | ||
| """ | ||
| Método abstrato para ajuste do threshold. | ||
| Cada classe derivada deve implementar sua lógica específica. | ||
| """ | ||
| pass |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Faz um raise numa exceção que faça sentido, pois do jeito que está agora não é possível saber que esse método é obrigatório.
Aproveite defina os tipos dos atributos e retorno esperado dessa função.
| Args: | ||
| SelfTrainingClassifier: Método SelfTraining |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Argumento é só um, mas no init tem 4, descreva todos, por favor. Incluindo o valor default de cada um, quando houver.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Algo nesse estilo estaria adequado??
class BaseFlexCon(SelfTrainingClassifier):
"""
Classe que serve como base para os diferentes métodos FlexCon.
Essa classe implementa um modelo SelfTraining utilizando um classificador base
e outros parâmetros para controlar o treinamento e a execução do modelo.
Args:
base_classifier (classificador): O classificador base que será utilizado pelo método SelfTraining.
Isso pode ser qualquer classificador do scikit-learn (ex: LogisticRegression, SVC, etc.).
threshold (float, opcional): O limiar de confiança para considerar uma instância como rotulada.
O valor padrão é 0.95, ou seja, a instância será rotulada apenas se a
probabilidade prevista for maior ou igual a 95%.
verbose (bool, opcional): Controla o nível de saída detalhada durante o treinamento.
O valor padrão é False, ou seja, nenhuma saída detalhada será gerada.
max_iter (int, opcional): O número máximo de iterações durante o treinamento. O valor padrão é 10.
Atributos:
base_classifier (classificador): O classificador base utilizado para treinar o modelo.
threshold (float): O limiar de confiança para considerar instâncias rotuladas.
verbose (bool): Controle de saída detalhada.
max_iter (int): Número máximo de iterações para o treinamento.
pred_x_it (dict): Dicionário para armazenar previsões durante o treinamento.
cl_memory (list): Lista para armazenar as instâncias rotuladas durante o treinamento.
classifier_ (classificador): O classificador clonado do base_classifier para ser treinado.
accuracy_history (list): Lista para armazenar a acurácia ao longo das iterações.
"""
def __init__(
self,
base_classifier,
threshold=0.95,
verbose=False,
max_iter=10
):
"""
Inicializa a instância do modelo BaseFlexCon.
Args:
base_classifier (classificador): O classificador base que será utilizado no método SelfTraining.
threshold (float, opcional): O limiar de confiança para considerar uma instância como rotulada.
O valor padrão é 0.95.
verbose (bool, opcional): Controle de saída detalhada. O valor padrão é False.
max_iter (int, opcional): Número máximo de iterações durante o treinamento. O valor padrão é 10.
"""
self.base_classifier = base_classifier
self.threshold = threshold
self.verbose = verbose
self.max_iter = max_iter
self.pred_x_it = {}
self.cl_memory = []
self.classifier_ = clone(base_classifier)
self.accuracy_history = []
| threshold=0.95, | ||
| verbose=False, | ||
| max_iter=10 | ||
| ): | ||
| self.base_classifier = base_classifier | ||
| self.threshold = threshold | ||
| self.verbose = verbose | ||
| self.max_iter = max_iter | ||
| self.pred_x_it = {} | ||
| self.cl_memory = [] | ||
| self.classifier_ = clone(base_classifier) | ||
| self.accuracy_history = [] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seria muito bom a gente indicar qual seria o tipo que a gente está tratando. Por exemplo:
| threshold=0.95, | |
| verbose=False, | |
| max_iter=10 | |
| ): | |
| self.base_classifier = base_classifier | |
| self.threshold = threshold | |
| self.verbose = verbose | |
| self.max_iter = max_iter | |
| self.pred_x_it = {} | |
| self.cl_memory = [] | |
| self.classifier_ = clone(base_classifier) | |
| self.accuracy_history = [] | |
| threshold: float = 0.95, | |
| verbose: bool = False, | |
| max_iter: int = 10 | |
| ): | |
| self.base_classifier = base_classifier | |
| self.threshold = threshold | |
| self.verbose = verbose | |
| self.max_iter = max_iter | |
| self.pred_x_it: dict[int, int] = {} | |
| self.cl_memory = [] | |
| self.classifier_ = clone(base_classifier) | |
| self.accuracy_history: list[float] = [] |
continue a partir daí, coloque, de preferência o tipo correto para os argumentos que são listas, dicionários e etc. VALE PARA TODO O RESTO DO ARQUIVO!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Irei repassar por todo o arquivo.
| from typing import Dict, List, Optional | ||
|
|
||
| import numpy as np | ||
| from selfTrainingInitial import SelfTrainingClassifier |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Esse cara está na ordem errada.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Conforme o ISort, é isso mesmo.
| if (first_confidence >= self.threshold or \ | ||
| confidence >= self.threshold) and first_class == predicted_class: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Evitar o uso da ''.
escolha um dos modelos a seguir e refatore com ele em mente, veja a PEP-0008. Ou podem usar um estilo de vocês, mas essa backslash a PEP, e eu, desencorajamos fortemente.
| if first_class != predicted_class and \ | ||
| first_confidence >= self.threshold and \ | ||
| confidence >= self.threshold: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Evitar o uso da ''.
escolha um dos modelos a seguir e refatore com ele em mente, veja a PEP-0008. Ou podem usar um estilo de vocês, mas essa backslash a PEP, e eu, desencorajamos fortemente.
| if first_class != predicted_class and \ | ||
| (first_confidence >= self.threshold \ | ||
| or confidence >= self.threshold): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Evitar o uso da ''.
escolha um dos modelos a seguir e refatore com ele em mente, veja a PEP-0008. Ou podem usar um estilo de vocês, mas essa backslash a PEP, e eu, desencorajamos fortemente.
| Função responsável por gerenciar todas as regras de inclusão do método | ||
|
|
||
| Returns: | ||
| _type_: _description_ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cade a documentação do retorno?
|
|
||
|
|
||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
era para ser só uma linha aqui, pq tem 3?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Irei remover na correção.
|
Conforme alinhado com o @RenanCDev em reunião virtual, eu vou fechar essa revisão e serão criadas as tarefas específicas de cada um dos algoritmos para que seja melhor dividido e distribuído o código. Ele iniciou o trabalho da divisão desse PR pela tarefa #17 que está específica para o FlexCon-G. |