| | --- |
| | language: |
| | - en |
| | metrics: |
| | - accuracy |
| | library_name: adapter-transformers |
| | pipeline_tag: text-classification |
| | tags: |
| | - code |
| | --- |
| | # Model Card for Model ID |
| |
|
| | <!--el modelo BERT para clasificaci贸n de secuencias que hemos afinado y entrenado es capaz de comprender el contexto de las oraciones y clasificarlas en dos categor铆as distintas basadas en el aprendizaje de patrones en los datos de entrenamiento.. --> |
| |
|
| | ## Model Details |
| |
|
| | los detalles del modelo que utilizamos: |
| |
|
| | Modelo base: BERT (Bidirectional Encoder Representations from Transformers). |
| | Funci贸n del modelo: Clasificaci贸n de secuencias de texto. |
| | N煤mero de etiquetas: Dos clases o categor铆as. |
| | Tokenizer utilizado: BertTokenizer de la biblioteca Transformers. |
| | Modelo espec铆fico utilizado: BertForSequenceClassification de la biblioteca Transformers. |
| | Optimizador: AdamW (una variante de Adam, con correcciones de peso) para ajustar los pesos del modelo durante el entrenamiento. |
| | Dispositivo de entrenamiento: GPU si est谩 disponible, de lo contrario, se usa CPU. |
| | M茅tricas evaluadas: Durante el entrenamiento, se evaluaron m茅tricas como precisi贸n, exactitud, sensibilidad (recall) y especificidad en un conjunto de validaci贸n. |
| | Proceso de entrenamiento: Entrenamiento del modelo durante m煤ltiples 茅pocas (ajustable) con un ciclo que involucra actualizaci贸n de pesos basada en la p茅rdida (loss) calculada y evaluaci贸n del desempe帽o del modelo en un conjunto de validaci贸n. |
| |
|
| | ### Model Description |
| |
|
| | El modelo utilizado, BERT (Bidirectional Encoder Representations from Transformers), es una red neuronal preentrenada que ha mostrado un rendimiento excepcional en tareas de procesamiento de lenguaje natural (NLP). Utiliza una arquitectura Transformer que permite capturar y comprender contextos de palabras y frases en ambos sentidos, lo que lo hace efectivo para entender el significado y contexto de una secuencia de texto. |
| |
|
| | En este caso, empleamos BertForSequenceClassification, una adaptaci贸n de BERT para la clasificaci贸n de secuencias de texto. Esta variante agrega una capa de clasificaci贸n lineal sobre la salida de la capa de representaci贸n de BERT, permitiendo clasificar secuencias en un n煤mero espec铆fico de categor铆as. El modelo se entren贸 para diferenciar entre dos etiquetas o clases en este caso particular. |
| |
|
| | El proceso de entrenamiento consisti贸 en ajustar los pesos del modelo utilizando un optimizador AdamW, minimizando la funci贸n de p茅rdida a trav茅s de m煤ltiples 茅pocas de entrenamiento. Se evalu贸 el desempe帽o del modelo utilizando m茅tricas como precisi贸n, exactitud, sensibilidad y especificidad en un conjunto de validaci贸n para garantizar su capacidad predictiva. |
| |
|
| | Developed by: Freddy Morales |
| | Funded by [optional]: N/A |
| | Shared by [optional]: |
| | Model type: BERT (Bidirectional Encoder Representations from Transformers). |
| | Language(s) (NLP): Primarily designed for English, but can be fine-tuned and adapted to other languages. |
| | License: BERT and its variations are released under the Apache License 2.0. |
| | Finetuned from model [optional]: The model used might have been fine-tuned from the 'bert-base-uncased' model, a pre-trained version of BERT released by Google. |
| |
|
| | ### Model Sources [optional] |
| |
|
| | <!-- Provide the basic links for the model. --> |
| |
|
| | - **Repository:** [More Information Needed] |
| | - **Paper [optional]:** https://towardsdatascience.com/fine-tuning-bert-for-text-classification-54e7df642894 |
| | - **Demo [optional]:** [More Information Needed] |
| |
|
| | ## Uses |
| |
|
| | <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. --> |
| |
|
| | ### Direct Use |
| |
|
| | <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. --> |
| |
|
| | [More Information Needed] |
| |
|
| | ### Downstream Use [optional] |
| |
|
| | <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app --> |
| |
|
| | [More Information Needed] |
| |
|
| | ### Out-of-Scope Use |
| |
|
| | <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. --> |
| |
|
| | [More Information Needed] |
| |
|
| | ## Bias, Risks, and Limitations |
| |
|
| | <!-- This section is meant to convey both technical and sociotechnical limitations. --> |
| |
|
| | [More Information Needed] |
| |
|
| | ### Recommendations |
| |
|
| | <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. --> |
| |
|
| | Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations. |
| |
|
| | ## How to Get Started with the Model |
| | from transformers import BertTokenizer, BertForSequenceClassification |
| |
|
| | # N煤mero de etiquetas/clases en tu problema de clasificaci贸n |
| | num_etiquetas = 2 # Actualiza con el n煤mero correcto de clases |
| | #1 Descargar y cargar el modelo BERT para clasificaci贸n: |
| | # Descargar el tokenizador y el modelo preentrenado BERT para clasificaci贸n |
| | tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') |
| | model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=num_etiquetas) |
| | |
| | from transformers import BertTokenizer, BertForSequenceClassification |
| | #2. Configuraci贸n del optimizador y del dispositivo: |
| | |
| | from torch.optim import AdamW |
| | |
| | # Par谩metros de optimizaci贸n |
| | optimizador = AdamW(model.parameters(), lr=5e-5) |
| | |
| | # Dispositivo (GPU si est谩 disponible, de lo contrario, CPU) |
| | dispositivo = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| | model.to(dispositivo) |
| |
|
| | # 3 Divisi贸n del conjunto de datos y creaci贸n de DataLoader: |
| | from torch.utils.data import DataLoader, TensorDataset, RandomSampler, SequentialSampler |
| | from sklearn.model_selection import train_test_split |
| | |
| | # Divisi贸n del conjunto de datos |
| | train_idx, val_idx = train_test_split(np.arange(len(labels)), test_size=val_ratio, shuffle=True, stratify=labels) |
| | |
| | # Creaci贸n de DataLoader para entrenamiento |
| | train_dataloader = DataLoader( |
| | TensorDataset(token_id[train_idx], attention_masks[train_idx], labels[train_idx]), |
| | sampler=RandomSampler(train_idx), |
| | batch_size=batch_size |
| | ) |
| | |
| | # Creaci贸n de DataLoader para validaci贸n |
| | val_dataloader = DataLoader( |
| | TensorDataset(token_id[val_idx], attention_masks[val_idx], labels[val_idx]), |
| | sampler=SequentialSampler(val_idx), |
| | batch_size=batch_size |
| | ) |
| | |
| |
|
| | from sklearn.metrics import precision_score |
| | |
| | # ... |
| | |
| | #4Entrenamiento del modelo BERT para clasificaci贸n: |
| | |
| | num_epochs = 3 # ajusta el n煤mero de 茅pocas seg煤n sea necesario |
| |
|
| | # Ciclo de entrenamiento |
| | for epoch in trange(num_epochs, desc='Epoch'): |
| | model.train() |
| | |
| | for step, batch in enumerate(train_dataloader): |
| | batch = tuple(t.to(dispositivo) for t in batch) |
| | input_ids, attention_mask, labels = batch |
| | |
| | optimizador.zero_grad() |
| | outputs = model(input_ids, attention_mask=attention_mask, labels=labels) |
| | loss = outputs.loss |
| | loss.backward() |
| | optimizador.step() |
| | |
| | # Evaluaci贸n en el conjunto de validaci贸n despu茅s de cada 茅poca |
| | model.eval() |
| | |
| | # Tracking variables |
| | val_accuracy = [] |
| | val_precision = [] |
| | |
| | for batch in val_dataloader: # Cambiado a val_dataloader en lugar de validation_dataloader |
| | batch = tuple(t.to(dispositivo) for t in batch) |
| | b_input_ids, b_input_mask, b_labels = batch |
| | with torch.no_grad(): |
| | # Forward pass |
| | eval_output = model( |
| | b_input_ids, |
| | token_type_ids=None, |
| | attention_mask=b_input_mask |
| | ) |
| | logits = eval_output.logits.detach().cpu().numpy() |
| | label_ids = b_labels.to('cpu').numpy() |
| | |
| | # Calculate validation metrics |
| | b_accuracy, _, _, b_precision = b_metrics(logits, label_ids) |
| | val_accuracy.append(b_accuracy) |
| | val_precision.append(b_precision) |
| | |
| | # Calcular m茅tricas promedio para la 茅poca |
| | avg_val_accuracy = sum(val_accuracy) / len(val_accuracy) |
| | avg_val_precision = sum(val_precision) / len(val_precision) if len(val_precision) > 0 else float('nan') |
| | |
| | # Imprimir resultados de la 茅poca |
| | print(f'\nEpoch {epoch + 1}/{num_epochs}') |
| | print(f' - Training Loss: {loss.item()}') |
| | print(f' - Validation Accuracy: {avg_val_accuracy}') |
| | print(f' - Validation Precision: {avg_val_precision}') |
| | |
| | # Predicci贸n en un nuevo ejemplo |
| | nueva_oracion = "Nah I don't think he goes to usf, he lives around here though" |
| | |
| | # Aplicar el tokenizer para obtener los IDs de tokens y la m谩scara de atenci贸n |
| | encoding = tokenizer.encode_plus( |
| | nueva_oracion, |
| | add_special_tokens=True, |
| | max_length=32, # Ajusta la longitud m谩xima seg煤n sea necesario |
| | pad_to_max_length=True, |
| | return_attention_mask=True, |
| | return_tensors='pt' # Devuelve tensores de PyTorch |
| | ) |
| | |
| | # Obtener los IDs de tokens y la m谩scara de atenci贸n |
| | input_ids = encoding['input_ids'].to(dispositivo) |
| | attention_mask = encoding['attention_mask'].to(dispositivo) |
| |
|
| | # Asegurarse de que las dimensiones sean adecuadas para el modelo BERT |
| | input_ids = input_ids.view(1, -1) # Cambiar la forma a (1, longitud) |
| | attention_mask = attention_mask.view(1, -1) # Cambiar la forma a (1, longitud) |
| |
|
| | # Realizar la predicci贸n |
| | with torch.no_grad(): |
| | output = model(input_ids, attention_mask=attention_mask) |
| |
|
| | # Obtener la clase predicha |
| | prediccion = 'Clase A' if torch.argmax(output.logits[0]).item() == 0 else 'Clase B' |
| |
|
| | # Imprimir resultados |
| | print(f'Nueva Oraci贸n: {nueva_oracion}') |
| | print(f'Predicci贸n: {prediccion}') |
| | |
| | [More Information Needed] |
| | |
| | ## Training Details |
| | |
| | ### Training Data |
| | |
| | <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. --> |
| | |
| | [More Information Needed] |
| | |
| | ### Training Procedure |
| | |
| | <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. --> |
| | |
| | #### Preprocessing [optional] |
| | |
| | [More Information Needed] |
| | |
| | |
| | #### Training Hyperparameters |
| | |
| | - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision --> |
| | |
| | #### Speeds, Sizes, Times [optional] |
| | |
| | <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. --> |
| | |
| | [More Information Needed] |
| | |
| | ## Evaluation |
| | |
| | <!-- This section describes the evaluation protocols and provides the results. --> |
| | |
| | ### Testing Data, Factors & Metrics |
| | |
| | #### Testing Data |
| | |
| | <!-- This should link to a Dataset Card if possible. --> |
| | |
| | [More Information Needed] |
| | |
| | #### Factors |
| | |
| | <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. --> |
| | |
| | [More Information Needed] |
| | |
| | #### Metrics |
| | |
| | <!-- These are the evaluation metrics being used, ideally with a description of why. --> |
| | |
| | [More Information Needed] |
| | |
| | ### Results |
| | |
| | [More Information Needed] |
| | |
| | #### Summary |
| | |
| | |
| | |
| | ## Model Examination [optional] |
| | |
| | <!-- Relevant interpretability work for the model goes here --> |
| | |
| | [More Information Needed] |
| | |
| | ## Environmental Impact |
| | |
| | <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly --> |
| | |
| | Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). |
| | |
| | - **Hardware Type:** [More Information Needed] |
| | - **Hours used:** [More Information Needed] |
| | - **Cloud Provider:** [More Information Needed] |
| | - **Compute Region:** [More Information Needed] |
| | - **Carbon Emitted:** [More Information Needed] |
| | |
| | ## Technical Specifications [optional] |
| | |
| | ### Model Architecture and Objective |
| | |
| | [More Information Needed] |
| | |
| | ### Compute Infrastructure |
| | |
| | [More Information Needed] |
| | |
| | #### Hardware |
| | |
| | [More Information Needed] |
| | |
| | #### Software |
| | |
| | [More Information Needed] |
| | |
| | ## Citation [optional] |
| | |
| | <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. --> |
| | |
| | **BibTeX:** |
| | |
| | [More Information Needed] |
| | |
| | **APA:** |
| | |
| | [More Information Needed] |
| | |
| | ## Glossary [optional] |
| | |
| | <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. --> |
| | |
| | [More Information Needed] |
| | |
| | ## More Information [optional] |
| | |
| | [More Information Needed] |
| | |
| | ## Model Card Authors [optional] |
| | |
| | [More Information Needed] |
| | |
| | ## Model Card Contact |
| | |
| | [More Information Needed] |
| | |
| | |
| | |