noumanjavaid commited on
Commit
90d43bc
β€’
1 Parent(s): 1e6410a

Changes.py

Browse files
Files changed (1) hide show
  1. app.py +334 -2
app.py CHANGED
@@ -1,5 +1,337 @@
1
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
5
 
 
1
  import streamlit as st
2
+ # %%
3
+ # Datasets installation
4
+ ! pip install datasets transformers
5
+ # To install from source instead of the last release, comment the command above and uncomment the following one.
6
+ # ! pip install git+https://github.com/huggingface/datasets.git
7
+
8
+ # %% [markdown]
9
+ # # Quickstart
10
+
11
+ # %% [markdown]
12
+ # This quickstart is intended for developers who are ready to dive into the code and see an example of how to integrate πŸ€— Datasets into their model training workflow. If you're a beginner, we recommend starting with our [tutorials](https://huggingface.co/docs/datasets/main/en/./tutorial), where you'll get a more thorough introduction.
13
+ #
14
+ # Each dataset is unique, and depending on the task, some datasets may require additional steps to prepare it for training. But you can always use πŸ€— Datasets tools to load and process a dataset. The fastest and easiest way to get started is by loading an existing dataset from the [Hugging Face Hub](https://huggingface.co/datasets). There are thousands of datasets to choose from, spanning many tasks. Choose the type of dataset you want to work with, and let's get started!
15
+ #
16
+ # <div class="mt-4">
17
+ # <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-3 md:gap-y-4 md:gap-x-5">
18
+ # <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#audio"
19
+ # ><div class="w-full text-center bg-gradient-to-r from-violet-300 via-sky-400 to-green-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Audio</div>
20
+ # <p class="text-gray-700">Resample an audio dataset and get it ready for a model to classify what type of banking issue a speaker is calling about.</p>
21
+ # </a>
22
+ # <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#vision"
23
+ # ><div class="w-full text-center bg-gradient-to-r from-pink-400 via-purple-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Vision</div>
24
+ # <p class="text-gray-700">Apply data augmentation to an image dataset and get it ready for a model to diagnose disease in bean plants.</p>
25
+ # </a>
26
+ # <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#nlp"
27
+ # ><div class="w-full text-center bg-gradient-to-r from-orange-300 via-red-400 to-violet-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">NLP</div>
28
+ # <p class="text-gray-700">Tokenize a dataset and get it ready for a model to determine whether a pair of sentences have the same meaning.</p>
29
+ # </a>
30
+ # </div>
31
+ # </div>
32
+ #
33
+ # <Tip>
34
+ #
35
+ # Check out [Chapter 5](https://huggingface.co/course/chapter5/1?fw=pt) of the Hugging Face course to learn more about other important topics such as loading remote or local datasets, tools for cleaning up a dataset, and creating your own dataset.
36
+ #
37
+ # </Tip>
38
+ #
39
+ # Start by installing πŸ€— Datasets:
40
+ #
41
+ # ```bash
42
+ # pip install datasets
43
+ # ```
44
+ #
45
+ # πŸ€— Datasets also support audio and image data formats:
46
+ #
47
+ # * To work with audio datasets, install the [Audio](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Audio) feature:
48
+ #
49
+ # ```bash
50
+ # pip install datasets[audio]
51
+ # ```
52
+ #
53
+ # * To work with image datasets, install the [Image](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Image) feature:
54
+ #
55
+ # ```bash
56
+ # pip install datasets[vision]
57
+ # ```
58
+ #
59
+ # Besides πŸ€— Datasets, make sure your preferred machine learning framework is installed:
60
+ #
61
+ # ```bash
62
+ # pip install torch
63
+ # ```
64
+ # ```bash
65
+ # pip install tensorflow
66
+ # ```
67
+
68
+ # %% [markdown]
69
+ # ## Audio
70
+
71
+ # %% [markdown]
72
+ # Audio datasets are loaded just like text datasets. However, an audio dataset is preprocessed a bit differently. Instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor). An audio input may also require resampling its sampling rate to match the sampling rate of the pretrained model you're using. In this quickstart, you'll prepare the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset for a model train on and classify the banking issue a customer is having.
73
+ #
74
+ # **1**. Load the MInDS-14 dataset by providing the [load_dataset()](https://huggingface.co/docs/datasets/main/en/package_reference/loading_methods#datasets.load_dataset) function with the dataset name, dataset configuration (not all datasets will have a configuration), and a dataset split:
75
+
76
+ # %%
77
+ from datasets import load_dataset, Audio
78
+
79
+ dataset = load_dataset("PolyAI/minds14", "en-US", split="train")
80
+
81
+ # %% [markdown]
82
+ # **2**. Next, load a pretrained [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) model and its corresponding feature extractor from the [πŸ€— Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task.
83
+
84
+ # %%
85
+ from transformers import AutoModelForAudioClassification, AutoFeatureExtractor
86
+
87
+ model = AutoModelForAudioClassification.from_pretrained("facebook/wav2vec2-base")
88
+ feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
89
+
90
+ # %% [markdown]
91
+ # **3**. The [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset card indicates the sampling rate is 8kHz, but the Wav2Vec2 model was pretrained on a sampling rate of 16kHZ. You'll need to upsample the `audio` column with the [cast_column()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.cast_column) function and [Audio](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Audio) feature to match the model's sampling rate.
92
+
93
+ # %%
94
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
95
+ dataset[0]["audio"]
96
+
97
+ # %% [markdown]
98
+ # **4**. Create a function to preprocess the audio `array` with the feature extractor, and truncate and pad the sequences into tidy rectangular tensors. The most important thing to remember is to call the audio `array` in the feature extractor since the `array` - the actual speech signal - is the model input.
99
+ #
100
+ # Once you have a preprocessing function, use the [map()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.map) function to speed up processing by applying the function to batches of examples in the dataset.
101
+
102
+ # %%
103
+ def preprocess_function(examples):
104
+ audio_arrays = [x["array"] for x in examples["audio"]]
105
+ inputs = feature_extractor(
106
+ audio_arrays,
107
+ sampling_rate=16000,
108
+ padding=True,
109
+ max_length=100000,
110
+ truncation=True,
111
+ )
112
+ return inputs
113
+
114
+ dataset = dataset.map(preprocess_function, batched=True)
115
+
116
+ # %% [markdown]
117
+ # **5**. Use the [rename_column()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.rename_column) function to rename the `intent_class` column to `labels`, which is the expected input name in [Wav2Vec2ForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2ForSequenceClassification):
118
+
119
+ # %%
120
+ dataset = dataset.rename_column("intent_class", "labels")
121
+
122
+ # %% [markdown]
123
+ # **6**. Set the dataset format according to the machine learning framework you're using.
124
+ #
125
+ # Use the [set_format()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.set_format) function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader):
126
+
127
+ # %%
128
+ from torch.utils.data import DataLoader
129
+
130
+ dataset.set_format(type="torch", columns=["input_values", "labels"])
131
+ dataloader = DataLoader(dataset, batch_size=4)
132
+
133
+ # %% [markdown]
134
+ # Use the [prepare_tf_dataset](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset) method from πŸ€— Transformers to prepare the dataset to be compatible with
135
+ # TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [Dataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset) as a `tf.data.Dataset`
136
+ # with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification.
137
+
138
+ # %%
139
+ import tensorflow as tf
140
+
141
+ tf_dataset = model.prepare_tf_dataset(
142
+ dataset,
143
+ batch_size=4,
144
+ shuffle=True,
145
+ )
146
+
147
+ # %% [markdown]
148
+ # **7**. Start training with your machine learning framework! Check out the πŸ€— Transformers [audio classification guide](https://huggingface.co/docs/transformers/tasks/audio_classification) for an end-to-end example of how to train a model on an audio dataset.
149
+
150
+ # %% [markdown]
151
+ # ## Vision
152
+
153
+ # %% [markdown]
154
+ # Image datasets are loaded just like text datasets. However, instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor) to preprocess the dataset. Applying data augmentation to an image is common in computer vision to make the model more robust against overfitting. You're free to use any data augmentation library you want, and then you can apply the augmentations with πŸ€— Datasets. In this quickstart, you'll load the [Beans](https://huggingface.co/datasets/beans) dataset and get it ready for the model to train on and identify disease from the leaf images.
155
+ #
156
+ # **1**. Load the Beans dataset by providing the [load_dataset()](https://huggingface.co/docs/datasets/main/en/package_reference/loading_methods#datasets.load_dataset) function with the dataset name and a dataset split:
157
+
158
+ # %%
159
+ from datasets import load_dataset, Image
160
+
161
+ dataset = load_dataset("beans", split="train")
162
+
163
+ # %% [markdown]
164
+ # **2**. Now you can add some data augmentations with any library ([Albumentations](https://albumentations.ai/), [imgaug](https://imgaug.readthedocs.io/en/latest/), [Kornia](https://kornia.readthedocs.io/en/latest/)) you like. Here, you'll use [torchvision](https://pytorch.org/vision/stable/transforms.html) to randomly change the color properties of an image:
165
+
166
+ # %%
167
+ from torchvision.transforms import Compose, ColorJitter, ToTensor
168
+
169
+ jitter = Compose(
170
+ [ColorJitter(brightness=0.5, hue=0.5), ToTensor()]
171
+ )
172
+
173
+ # %% [markdown]
174
+ # **3**. Create a function to apply your transform to the dataset and generate the model input: `pixel_values`.
175
+
176
+ # %%
177
+ def transforms(examples):
178
+ examples["pixel_values"] = [jitter(image.convert("RGB")) for image in examples["image"]]
179
+ return examples
180
+
181
+ # %% [markdown]
182
+ # **4**. Use the [with_transform()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.with_transform) function to apply the data augmentations on-the-fly:
183
+
184
+ # %%
185
+ dataset = dataset.with_transform(transforms)
186
+
187
+ # %% [markdown]
188
+ # **5**. Set the dataset format according to the machine learning framework you're using.
189
+ #
190
+ # Wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader). You'll also need to create a collate function to collate the samples into batches:
191
+
192
+ # %%
193
+ from torch.utils.data import DataLoader
194
+
195
+ def collate_fn(examples):
196
+ images = []
197
+ labels = []
198
+ for example in examples:
199
+ images.append((example["pixel_values"]))
200
+ labels.append(example["labels"])
201
+
202
+ pixel_values = torch.stack(images)
203
+ labels = torch.tensor(labels)
204
+ return {"pixel_values": pixel_values, "labels": labels}
205
+ dataloader = DataLoader(dataset, collate_fn=collate_fn, batch_size=4)
206
+
207
+ # %% [markdown]
208
+ # Use the [prepare_tf_dataset](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset) method from πŸ€— Transformers to prepare the dataset to be compatible with
209
+ # TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [Dataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset) as a `tf.data.Dataset`
210
+ # with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification.
211
+ #
212
+ # Before you start, make sure you have up-to-date versions of `albumentations` and `cv2` installed:
213
+ #
214
+ # ```bash
215
+ # pip install -U albumentations opencv-python
216
+ # ```
217
+
218
+ # %%
219
+ import albumentations
220
+ import numpy as np
221
+
222
+ transform = albumentations.Compose([
223
+ albumentations.RandomCrop(width=256, height=256),
224
+ albumentations.HorizontalFlip(p=0.5),
225
+ albumentations.RandomBrightnessContrast(p=0.2),
226
+ ])
227
+
228
+ def transforms(examples):
229
+ examples["pixel_values"] = [
230
+ transform(image=np.array(image))["image"] for image in examples["image"]
231
+ ]
232
+ return examples
233
+
234
+ dataset.set_transform(transforms)
235
+ tf_dataset = model.prepare_tf_dataset(
236
+ dataset,
237
+ batch_size=4,
238
+ shuffle=True,
239
+ )
240
+
241
+ # %% [markdown]
242
+ # **6**. Start training with your machine learning framework! Check out the πŸ€— Transformers [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification) for an end-to-end example of how to train a model on an image dataset.
243
+
244
+ # %% [markdown]
245
+ # ## NLP
246
+
247
+ # %% [markdown]
248
+ # Text needs to be tokenized into individual tokens by a [tokenizer](https://huggingface.co/docs/transformers/main_classes/tokenizer). For the quickstart, you'll load the [Microsoft Research Paraphrase Corpus (MRPC)](https://huggingface.co/datasets/glue/viewer/mrpc) training dataset to train a model to determine whether a pair of sentences mean the same thing.
249
+ #
250
+ # **1**. Load the MRPC dataset by providing the [load_dataset()](https://huggingface.co/docs/datasets/main/en/package_reference/loading_methods#datasets.load_dataset) function with the dataset name, dataset configuration (not all datasets will have a configuration), and dataset split:
251
+
252
+ # %%
253
+ from datasets import load_dataset
254
+
255
+ dataset = load_dataset("glue", "mrpc", split="train")
256
+
257
+ # %% [markdown]
258
+ # **2**. Next, load a pretrained [BERT](https://huggingface.co/bert-base-uncased) model and its corresponding tokenizer from the [πŸ€— Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task.
259
+
260
+ # %%
261
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
262
+
263
+ model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
264
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
265
+
266
+ # %%
267
+ from transformers import TFAutoModelForSequenceClassification, AutoTokenizer
268
+
269
+ model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
270
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
271
+
272
+ # %% [markdown]
273
+ # **3**. Create a function to tokenize the dataset, and you should also truncate and pad the text into tidy rectangular tensors. The tokenizer generates three new columns in the dataset: `input_ids`, `token_type_ids`, and an `attention_mask`. These are the model inputs.
274
+ #
275
+ # Use the [map()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.map) function to speed up processing by applying your tokenization function to batches of examples in the dataset:
276
+
277
+ # %%
278
+ def encode(examples):
279
+ return tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, padding="max_length")
280
+
281
+ dataset = dataset.map(encode, batched=True)
282
+ dataset[0]
283
+
284
+ # %% [markdown]
285
+ # **4**. Rename the `label` column to `labels`, which is the expected input name in [BertForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/bert#transformers.BertForSequenceClassification):
286
+
287
+ # %%
288
+ dataset = dataset.map(lambda examples: {"labels": examples["label"]}, batched=True)
289
+
290
+ # %% [markdown]
291
+ # **5**. Set the dataset format according to the machine learning framework you're using.
292
+ #
293
+ # Use the [set_format()](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.set_format) function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader):
294
+
295
+ # %%
296
+ # prompt: Set the dataset format according to the machine learning framework you're using.
297
+ # Use the set_format() function to set the dataset format to torch and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in torch.utils.data.DataLoader:
298
+
299
+ dataset.set_format(type="torch", columns=["input_ids", "labels"])
300
+ dataloader = DataLoader(dataset, batch_size=4)
301
+
302
+
303
+ # %%
304
+ import torch
305
+ from torch.utils.data import DataLoader
306
+
307
+ # %%
308
+ # prompt: Set the dataset format to torch and specify the columns to format:
309
+ # set_format(parquet_file, "torch", columns=["column1", "column2"])
310
+
311
+ dataset.set_format(type="torch", columns=["input_ids", "labels"])
312
+
313
+
314
+ # %% [markdown]
315
+ # Use the [prepare_tf_dataset](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset) method from πŸ€— Transformers to prepare the dataset to be compatible with
316
+ # TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [Dataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset) as a `tf.data.Dataset`
317
+ # with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification.
318
+
319
+ # %%
320
+
321
+ tf_dataset = model.prepare_tf_dataset(
322
+ dataset,
323
+ batch_size=4,
324
+ shuffle=True,)
325
+
326
+ # %% [markdown]
327
+ # **6**. Start training with your machine learning framework! Check out the πŸ€— Transformers [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification) for an end-to-end example of how to train a model on a text dataset.
328
+
329
+ # %% [markdown]
330
+ # ## What's next?
331
+
332
+ # %% [markdown]
333
+ # This completes the πŸ€— Datasets quickstart! You can load any text, audio, or image dataset with a single function and get it ready for your model to train on.
334
+ #
335
+ # For your next steps, take a look at our [How-to guides](https://huggingface.co/docs/datasets/main/en/./how_to) and learn how to do more specific things like loading different dataset formats, aligning labels, and streaming large datasets. If you're interested in learning more about πŸ€— Datasets core concepts, grab a cup of coffee and read our [Conceptual Guides](https://huggingface.co/docs/datasets/main/en/./about_arrow)!
336
 
 
 
337