mongodb-developer /
genai-devday-notebooks
This repository is home to all the Jupyter Notebooks required for MongoDB's GenAI Developer Day.
66/100 healthLoading repository data…
RajKKapadia / repository
This is repository for my Fiverr client, I have written a blog on custom dataset, Text Classification on BERT model using Transformers.
A transparent discovery signal based on current public GitHub metadata.
This score does not audit code, security, maintainers, documentation quality, or suitability. Verify the repository and its current documentation before adoption.
In recent years Natural language understanding [NLU] has made extraordinary advancements in many fields like text correction, text prediction, text translation, text classification, and many more... Recently Meta has released a 200 language Language Translation GitHub repository FAIRSEQ, in the world of NLP or NLU there is one name that is not that famous but has many tools under its sleeve is HuggingFace, they have a huge library for NLP and Image Classification.
In this blog, we will train a state-of-the-art Text Classification model using BERT base uncased, the word uncased means it does not make any difference between english and English. You can read about the BERT model from the Google Research team here, and Hugging Face implementation here.
So, let's get started...
To follow this blog end-to-end, you need to set up a new environment on your computer. However, it is not compulsory to use your local machine, you can train a model on, let's say Google Colab and download the trained model to server the requests for classification [it is out of the scope for this blog, maybe in my next blog I will cover this].
NOTE - it is not compulsory but if you can use VS Code to write and run the code, it will be very easy.
[1] open terminal[linux or mac] or cmd tool[windows] navigate to the directory where you want to keep the project files and run
python3 -m venv tutorial-env
here, tutorial-env is the name of the virtual environment.
You can get more help here.
[2] once the virtual environment is created, activate the virtual environment by running
on windowns run
tutorial-env\Scripts\activate.bat
on mac/linux run
source tutorial-env/bin/activate
Once the virtual environment is activated run the following command to get the required packages...
pip install transformers[torch] pandas datasets pyarrow scikit-learn
NOTE - this will take some time to complete, and depends on your laptop or pc and connection speed.
Here, in this tutorial I am using a dataset downloaded from Kaggle, it is a movie review dataset, and it has around 50K samples with two labels positive and negative, but this can be implemented to more than two classes as well.
Now, let's start training the BERT base uncased model, at this point I want you to understand that we can train any model from Huggin Face using the same concept I will show you below.
Now, let's read the dataset...
import pandas as pd
df = pd.read_csv('./input/dataset.csv')
df.head()
You will see that there are two columns, review and sentiment, the problem we have is a binary classification of the column review.
We need our data in a certain format before we pass it to the Bert base uncased, this model requires input_ids, token_type_ids, attention_mask, label, and text, also there is a particular way we need to pass the data and that is why we have installed pyarrow and datasets.
NOTE - When you work on a different model that
Bert base uncased, you need to make sure the data is in the format required by that model.
To tokenize the text, we will use AutoTokenizer. The following piece of code will initialize the tokenizer.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
Now, let's process the data in the CSV file, for this I will write a function, in this function the tokenizer uses max_length=128, you can increase that, but since I am just showing the workings, I will use 128.
from typing import Dict
def process_data(row) -> Dict:
# Clean the text
text = row['review']
text = str(text)
text = ' '.join(text.split())
# Get tokens
encodings = tokenizer(text, padding="max_length", truncation=True, max_length=128)
# Convert string to integers
label = 0
if row['sentiment'] == 'positive':
label += 1
encodings['label'] = label
encodings['text'] = text
return encodings
Let's check the working of the function...
print(process_data({
'review': 'this is a sample review of a movie.',
'sentiment': 'positive'
}))
We will pass each row of the dataset and process the review and convert the sentiment into int since the dataset consists of 15K samples, but as I said, for demonstration purposes, I will only use 1K samples.
# Store the encodings into an array to generate dataset
processed_data = []
for i in range(len(df[:1000])):
processed_data.append(process_data(df.iloc[i]))
Now, let's generate the dataset in a format required by the Trainer module of the transformers library. You can read mode about the Trainer here.
NOTE - The
Trainermodule accepts Datagenerator from PyTorch, so you can use that to generate the data on the go, in case you have a bigger dataset.
The code piece below converts the list of encodings into a data frame and split that into a training and validation set of data.
from sklearn.model_selection import train_test_split
new_df = pd.DataFrame(processed_data)
train_df, valid_df = train_test_split(
new_df,
test_size=0.2,
random_state=2022
)
Now, let's convert the train_df and valid_df into Dataset accepted by the Trainer module.
import pyarrow as pa
from datasets import Dataset
train_hg = Dataset(pa.Table.from_pandas(train_df))
valid_hg = Dataset(pa.Table.from_pandas(valid_df))
Since our dataset is now ready, we can safely move forward to training the model on our custom dataset.
The following piece of code will initialize a Bert base uncased model for our training.
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
'bert-base-uncased',
num_labels=2
)
The model is ready, we are getting closer to the results, let's create a Trainer, it will require TrainingArguments as well. The following code will initialize both of them.
Under TrainingArguments you will see a outpit_dir argument, it is used by the module to write training logs.
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(output_dir="./result", evaluation_strategy="epoch")
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_hg,
eval_dataset=valid_hg,
tokenizer=tokenizer
)
Let's train our model...
trainer.train()
once the training is complete, we can evaluate the model as well...
trainer.evaluate()
You will search all the internet on training a well-known model on your custom dataset, and they will show you everything, but only a very small fraction of the bloggers will explain the following step, by the way, I am one of the small fraction of the blogger.
We will save the model at the desired location...
model.save_pretrained('./model/')
When you need to load the model and initialize the tokenizer as well...
model...
from transformers import AutoModelForSequenceClassification
new_model = AutoModelForSequenceClassification.from_pretrained('./model/')
tokenizer...
from transformers import AutoTokenizer
new_tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
Now, that we have loaded our model, we are ready for the prediction...
The following function will use the model and tokenizer to get the prediction from a piece of text.
import torch
import numpy as np
def get_prediction(text):
encoding = new_tokenizer(text, return_tensors="pt", padding="max_length", truncation=True, max_length=128)
encoding = {k: v.to(trainer.model.device) for k,v in encoding.items()}
outputs = new_model(**encoding)
logits = outputs.logits
sigmoid = torch.nn.Sigmoid()
probs = sigmoid(logits.squeeze().cpu())
probs = probs.detach().numpy()
label = np.argmax(probs, axis=-1)
if label == 1:
return {
'sentiment': 'Positive',
'probability': probs[1]
}
else:
return {
'sentiment': 'Negative',
'probability': probs[0]
}
let's see if it works or not, fingers are crossed....
get_prediction('I am happy to see you.')
The code explained here in this blog can be replicated for any text classification problem, you can experiment with different models as well.
The code used in this blog can be downloaded from my Github.
I am Raj Kapadia, I am passionate about AI/ML/DL and their use in different domains, I also love to build chatbots using Google Dialogflow. For any work, you can reach out to me at...
Selected from shared topics, language and repository description—not editorial ratings.
mongodb-developer /
This repository is home to all the Jupyter Notebooks required for MongoDB's GenAI Developer Day.
66/100 healthmudigosa /
Image Classifier Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smartphone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications. In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice, you'd train this classifier, then export it for use in your application. We'll be using this dataset of 102 flower categories. When you've completed this project, you'll have an application that can be trained on any set of labelled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. This is the final Project of the Udacity AI with Python Nanodegree Prerequisites The Code is written in Python 3.6.5 . If you don't have Python installed you can find it here. If you are using a lower version of Python you can upgrade using the pip package, ensuring you have the latest version of pip. To install pip run in the command Line python -m ensurepip -- default-pip to upgrade it python -m pip install -- upgrade pip setuptools wheel to upgrade Python pip install python -- upgrade Additional Packages that are required are: Numpy, Pandas, MatplotLib, Pytorch, PIL and json. You can donwload them using pip pip install numpy pandas matplotlib pil or conda conda install numpy pandas matplotlib pil In order to intall Pytorch head over to the Pytorch site select your specs and follow the instructions given. Viewing the Jyputer Notebook In order to better view and work on the jupyter Notebook I encourage you to use nbviewer . You can simply copy and paste the link to this website and you will be able to edit it without any problem. Alternatively you can clone the repository using git clone https://github.com/fotisk07/Image-Classifier/ then in the command Line type, after you have downloaded jupyter notebook type jupyter notebook locate the notebook and run it. Command Line Application Train a new network on a data set with train.py Basic Usage : python train.py data_directory Prints out current epoch, training loss, validation loss, and validation accuracy as the netowrk trains Options: Set direcotry to save checkpoints: python train.py data_dor --save_dir save_directory Choose arcitecture (alexnet, densenet121 or vgg16 available): pytnon train.py data_dir --arch "vgg16" Set hyperparameters: python train.py data_dir --learning_rate 0.001 --hidden_layer1 120 --epochs 20 Use GPU for training: python train.py data_dir --gpu gpu Predict flower name from an image with predict.py along with the probability of that name. That is you'll pass in a single image /path/to/image and return the flower name and class probability Basic usage: python predict.py /path/to/image checkpoint Options: Return top K most likely classes: python predict.py input checkpoint ---top_k 3 Use a mapping of categories to real names: python predict.py input checkpoint --category_names cat_To_name.json Use GPU for inference: python predict.py input checkpoint --gpu Json file In order for the network to print out the name of the flower a .json file is required. If you aren't familiar with json you can find information here. By using a .json file the data can be sorted into folders with numbers and those numbers will correspond to specific names specified in the .json file. Data and the json file The data used specifically for this assignemnt are a flower database are not provided in the repository as it's larger than what github allows. Nevertheless, feel free to create your own databases and train the model on them to use with your own projects. The structure of your data should be the following: The data need to comprised of 3 folders, test, train and validate. Generally the proportions should be 70% training 10% validate and 20% test. Inside the train, test and validate folders there should be folders bearing a specific number which corresponds to a specific category, clarified in the json file. For example if we have the image a.jpj and it is a rose it could be in a path like this /test/5/a.jpg and json file would be like this {...5:"rose",...}. Make sure to include a lot of photos of your catagories (more than 10) with different angles and different lighting conditions in order for the network to generalize better. GPU As the network makes use of a sophisticated deep convolutional neural network the training process is impossible to be done by a common laptop. In order to train your models to your local machine you have three options Cuda -- If you have an NVIDIA GPU then you can install CUDA from here. With Cuda you will be able to train your model however the process will still be time consuming Cloud Services -- There are many paid cloud services that let you train your models like AWS or Google Cloud Coogle Colab -- Google Colab gives you free access to a tesla K80 GPU for 12 hours at a time. Once 12 hours have ellapsed you can just reload and continue! The only limitation is that you have to upload the data to Google Drive and if the dataset is massive you may run out of space. However, once a model is trained then a normal CPU can be used for the predict.py file and you will have an answer within some seconds. Hyperparameters As you can see you have a wide selection of hyperparameters available and you can get even more by making small modifications to the code. Thus it may seem overly complicated to choose the right ones especially if the training needs at least 15 minutes to be completed. So here are some hints: By increasing the number of epochs the accuracy of the network on the training set gets better and better however be careful because if you pick a large number of epochs the network won't generalize well, that is to say it will have high accuracy on the training image and low accuracy on the test images. Eg: training for 12 epochs training accuracy: 85% Test accuracy: 82%. Training for 30 epochs training accuracy 95% test accuracy 50%. A big learning rate guarantees that the network will converge fast to a small error but it will constantly overshot A small learning rate guarantees that the network will reach greater accuracies but the learning process will take longer Densenet121 works best for images but the training process takes significantly longer than alexnet or vgg16 *My settings were lr=0.001, dropoup=0.5, epochs= 15 and my test accuracy was 86% with densenet121 as my feature extraction model. Pre-Trained Network The checkpoint.pth file contains the information of a network trained to recognise 102 different species of flowers. I has been trained with specific hyperparameters thus if you don't set them right the network will fail. In order to have a prediction for an image located in the path /path/to/image using my pretrained model you can simply type python predict.py /path/to/image checkpoint.pth Contributing Please read CONTRIBUTING.md for the process for submitting pull requests. Authors Shanmukha Mudigonda - Initial work Udacity - Final Project of the AI with Python Nanodegree
insidelearningmachines /
This repository is meant to store the code examples used in articles posted on www.insidelearningmachines.com. Each article on the website will have an associated jupyter notebook here with the same name.
72/100 healthalbertofernandezvillan /
This repository contains both a collection of Jupyter Notebooks as well as other resources (e.g. presentations, links, ...) that are going to be used during the "Second quarter university extension courses" that the University of Oviedo is going to teach (online).
57/100 healthSHIRSENDU-KONER /
Customer Service Requests Analysis is one of the practical life problems that an analyst may face. This Project is one such take. The project is a beginner to intermediate level project. This repository has a Source Code, README file, Dataset, Image and License file.
55/100 healthBanVacc /
This repository is a beginner-friendly introduction to Computational Fluid Dynamics (CFD) for those interested in developing their own CFD solver. It includes Jupyter notebooks with detailed instructions.
65/100 health