Roxsas commited on
Commit
36ebee9
verified
1 Parent(s): 4a151b3

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +184 -195
README.md CHANGED
@@ -1,199 +1,188 @@
1
- ---
2
- library_name: transformers
3
- tags: []
4
- ---
5
-
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
-
10
-
11
-
12
- ## Model Details
13
-
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 馃 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- 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. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
 
101
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- 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).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
 
197
- ## Model Card Contact
 
198
 
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ ## **Documentaci贸n del Proyecto: Clasificador de Noticias Falsas con XLM-RoBERTa**
3
+
4
+ ### **Objetivo**
5
+ Este proyecto tiene como objetivo entrenar un modelo de **Clasificaci贸n de Texto** utilizando **XLM-RoBERTa**, un modelo preentrenado de **transformers** multiling眉es, para clasificar noticias como falsas (`label = 0`) o verdaderas (`label = 1`). El modelo se entrena utilizando un conjunto de datos etiquetado de noticias y se eval煤a en un conjunto de validaci贸n para determinar su capacidad para predecir correctamente las clases de las noticias.
6
+
7
+ ### **Desglose del C贸digo**
8
+
9
+ #### **1. Cargar el Conjunto de Datos**
10
+ En primer lugar, se carga el conjunto de datos desde un archivo CSV. Este dataset contiene las noticias y sus respectivas etiquetas (falsas o verdaderas). El archivo CSV se lee usando **pandas**, una librer铆a de Python para manipular datos en formato de tabla (DataFrame).
11
+
12
+ ```python
13
+ df = pd.read_csv(dataset_path, on_bad_lines='skip')
14
+ ```
15
+
16
+ **Par谩metro `on_bad_lines='skip'`**: Este par谩metro se utiliza para evitar que el c贸digo se caiga si hay l铆neas mal formadas en el archivo CSV. Simplemente las omite.
17
+
18
+ #### **2. Divisi贸n del Conjunto de Datos**
19
+ El conjunto de datos se divide en dos subconjuntos: uno para entrenamiento y otro para validaci贸n. **`train_test_split`** de **scikit-learn** se utiliza para esta tarea.
20
+
21
+ - **`test_size=0.2`**: Indica que el 20% de los datos se usar谩n para validaci贸n, mientras que el 80% restante se destinar谩 al entrenamiento.
22
+ - **`stratify=df['label'].tolist()`**: Asegura que las proporciones de las clases (falsas y verdaderas) sean iguales en ambos subconjuntos (estratificaci贸n).
23
+
24
+ ```python
25
+ train_texts, val_texts, train_labels, val_labels = train_test_split(
26
+ df['text'].tolist(),a
27
+ df['label'].tolist(),
28
+ test_size=0.2,
29
+ random_state=42,
30
+ stratify=df['label'].tolist()
31
+ )
32
+ ```
33
+
34
+ #### **3. Tokenizaci贸n de los Textos**
35
+ El modelo **XLM-RoBERTa** requiere que los textos se conviertan en tokens, es decir, en una representaci贸n num茅rica que el modelo pueda procesar. Utilizamos el tokenizador de **Hugging Face's Transformers**.
36
+
37
+ ```python
38
+ train_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=256)
39
+ val_encodings = tokenizer(val_texts, truncation=True, padding=True, max_length=256)
40
+ ```
41
+
42
+ - **`truncation=True`**: Si un texto es m谩s largo que el m谩ximo de 256 tokens, se trunca.
43
+ - **`padding=True`**: Si un texto es m谩s corto, se rellena con un token especial para asegurarse de que todos los textos tengan la misma longitud.
44
+ - **`max_length=256`**: Limita la longitud de los textos a 256 tokens.
45
+
46
+ #### **4. Creaci贸n de un Dataset Personalizado**
47
+ Para que el modelo pueda trabajar con el conjunto de datos, se crea una clase personalizada `FakeNewsDataset` que hereda de `torch.utils.data.Dataset`. Esta clase estructura los datos para que el modelo pueda acceder a ellos durante el entrenamiento y la evaluaci贸n.
48
+
49
+ ```python
50
+ class FakeNewsDataset(torch.utils.data.Dataset):
51
+ def __init__(self, encodings, labels):
52
+ self.encodings = encodings
53
+ self.labels = labels
54
+
55
+ def __len__(self):
56
+ return len(self.labels)
57
+
58
+ def __getitem__(self, idx):
59
+ item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
60
+ item['label'] = torch.tensor(self.labels[idx])
61
+ return item
62
+ ```
63
+
64
+ - **`__len__()`**: Devuelve la longitud del conjunto de datos (n煤mero de muestras).
65
+ - **`__getitem__()`**: Devuelve un diccionario con los datos de una muestra. Las claves son los nombres de las columnas de los tensores (`input_ids`, `attention_mask`), y se agrega tambi茅n la etiqueta (`label`).
66
+
67
+ #### **5. Modelo Personalizado: `AdvancedXLMRClassifier`**
68
+ El modelo **XLM-RoBERTa** es un modelo preentrenado de **transformers**, por lo que no es necesario entrenarlo desde cero. Sin embargo, creamos una clase personalizada que extiende el modelo base de **XLM-RoBERTa** para a帽adir una capa de clasificaci贸n adicional.
69
+
70
+ ##### **Congelaci贸n de Capas**
71
+ Se congelan las primeras capas del modelo base para evitar que sus par谩metros se actualicen durante el entrenamiento. Esto es 煤til para aprovechar las representaciones preentrenadas del modelo sin tener que ajustarlas completamente.
72
+
73
+ ```python
74
+ for param in self.xlm_roberta.roberta.embeddings.parameters():
75
+ param.requires_grad = False
76
+ for param in self.xlm_roberta.roberta.encoder.layer[:5].parameters():
77
+ param.requires_grad = False
78
+ ```
79
+
80
+ - **`self.xlm_roberta.roberta.embeddings.parameters()`**: Congela los par谩metros de la capa de embeddings (representaciones de palabras).
81
+ - **`self.xlm_roberta.roberta.encoder.layer[:5].parameters()`**: Congela las primeras 5 capas del encoder.
82
+
83
+ ##### **Arquitectura de Clasificaci贸n**
84
+ Despu茅s de la capa de **XLM-RoBERTa**, a帽adimos una red neuronal adicional (MLP) con varias capas **`Linear`**, **`BatchNorm1d`**, **`ReLU`** y **`Dropout`** para mejorar el rendimiento del modelo.
85
+
86
+ ```python
87
+ self.classifier = nn.Sequential(
88
+ nn.Dropout(0.5),
89
+ nn.Linear(self.xlm_roberta.config.hidden_size, 512),
90
+ nn.BatchNorm1d(512),
91
+ nn.ReLU(),
92
+ nn.Dropout(0.4),
93
+ nn.Linear(512, 256),
94
+ nn.BatchNorm1d(256),
95
+ nn.ReLU(),
96
+ nn.Dropout(0.3),
97
+ nn.Linear(256, num_labels)
98
+ )
99
+ ```
100
+
101
+ - **`Dropout`**: Regularizaci贸n para prevenir el sobreajuste, que apaga aleatoriamente ciertas neuronas durante el entrenamiento.
102
+ - **`Linear`**: Capa totalmente conectada que reduce la dimensi贸n del espacio de caracter铆sticas.
103
+ - **`BatchNorm1d`**: Normalizaci贸n de las activaciones para estabilizar el entrenamiento.
104
+ - **`ReLU`**: Funci贸n de activaci贸n no lineal para introducir no linealidad.
105
+
106
+ ##### **M茅todo Forward**
107
+ El m茅todo **`forward`** es el que define c贸mo pasan los datos a trav茅s del modelo. Primero, obtiene las salidas de **XLM-RoBERTa**, luego toma el **[CLS] token** (el token que representa la secuencia completa) y lo pasa a trav茅s de las capas adicionales de la red neuronal.
108
+
109
+ ```python
110
+ outputs = self.xlm_roberta.roberta(input_ids=input_ids, attention_mask=attention_mask, return_dict=True)
111
+ pooled_output = outputs.last_hidden_state[:, 0, :]
112
+ logits = self.classifier(pooled_output)
113
+ ```
114
+
115
+ - **`last_hidden_state[:, 0, :]`**: Selecciona el **[CLS] token** de la secuencia (el primer token) como representaci贸n de toda la secuencia.
116
+ - **`self.classifier(pooled_output)`**: Pasa el token **[CLS]** por la red de clasificaci贸n.
117
+
118
+ #### **6. C谩lculo de M茅tricas Personalizadas**
119
+ Se define la funci贸n **`compute_metrics`** para evaluar el rendimiento del modelo usando m茅tricas como **precisi贸n**, **recall**, **F1 score** y **accuracy**. Adem谩s, se experimenta con diferentes umbrales de decisi贸n para las predicciones (0.4, 0.45, 0.5).
120
+
121
+ ```python
122
+ def compute_metrics(eval_pred):
123
+ logits, labels = eval_pred
124
+ predictions = torch.softmax(torch.tensor(logits), dim=-1)
125
+ thresholds = [0.4, 0.45, 0.5]
126
+ best_f1 = 0
127
+ best_threshold = 0.45
128
+ best_metrics = {}
129
+
130
+ for threshold in thresholds:
131
+ binary_predictions = (predictions[:, 1] > threshold).int()
132
+ precision, recall, f1, _ = precision_recall_fscore_support(labels, binary_predictions, average='binary')
133
+
134
+ if f1 > best_f1:
135
+ best_f1 = f1
136
+ best_threshold = threshold
137
+ best_metrics = {
138
+ "accuracy": accuracy_score(labels, binary_predictions),
139
+ "f1": f1,
140
+ "precision": precision,
141
+ "recall": recall
142
+ }
143
+
144
+ return best_metrics
145
+ ```
146
+
147
+ #### **7. Entrenamiento del Modelo**
148
+ El **`Trainer`** es el encargado de gestionar el ciclo completo de entrenamiento y evaluaci贸n. Se le pasa el modelo, los datos, y los par谩metros de entrenamiento. Tambi茅n se configura el **early stopping** para detener el entrenamiento si la m茅trica de evaluaci贸n no mejora despu茅s de un n煤mero definido de 茅pocas.
149
+
150
+ ```python
151
+ trainer = Trainer(
152
+ model=model,
153
+ args=training_args,
154
+ train_dataset=train_dataset,
155
+ eval_dataset=val_dataset,
156
+ data_collator=data_collator,
157
+ compute_metrics=compute
158
+
159
+ _metrics,
160
+ callbacks=[early_stopping]
161
+ )
162
+ trainer.train()
163
+ ```
164
+
165
+ **`early_stopping`** es una funci贸n de callback que detiene el entrenamiento si la m茅trica **F1** no mejora despu茅s de 3 茅pocas consecutivas.
166
+
167
+ #### **8. Guardado del Modelo**
168
+ Una vez entrenado el modelo, se guarda tanto el modelo como el tokenizador para su reutilizaci贸n posterior:
169
+
170
+ ```python
171
+ model.save_pretrained('./results')
172
+ tokenizer.save_pretrained('./results')
173
+ ```
174
+
175
+ #### **9. Evaluaci贸n Final**
176
+ Se eval煤a el modelo en el conjunto de validaci贸n usando la funci贸n **`evaluate`** del **Trainer**, que devuelve las m茅tricas de rendimiento.
177
+
178
+ ```python
179
+ results = trainer.evaluate()
180
+ print("Resultados de evaluaci贸n:", results)
181
+ ```
182
 
183
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
+ ### **Conclusi贸n**
186
+ Este c贸digo utiliza t茅cnicas avanzadas como **fine-tuning** de un modelo preentrenado de **XLM-RoBERTa**, congelaci贸n de capas, **early stopping**, y c谩lculo de m茅tricas personalizadas para clasificar noticias como verdaderas o falsas. El modelo es afinado para este conjunto de datos espec铆fico, y su rendimiento se eval煤a con precisi贸n, recall, **F1 score** y **accuracy**.
187
 
188
+ Este enfoque proporciona una soluci贸n eficiente y efectiva para el problema de clasificaci贸n de texto en problemas de desinformaci贸n, utilizando modelos de lenguaje de 煤ltima generaci贸n.