avatarNaina Chaturvedi

Summary

The web content provides an overview of the 60th day of a Data Science and Machine Learning series, focusing on fine-tuning BERT for text classification, and offers resources for further learning in related fields.

Abstract

The article marks the 50th day of a comprehensive series on Data Science and Machine Learning, with a particular focus on Bidirectional Encoder Representations from Transformers (BERT). It introduces TensorFlow as a foundational tool for machine learning, emphasizing its ability to handle large numerical computations and deep learning processes. The author guides readers through the steps of fine-tuning BERT for text classification tasks, including importing necessary libraries, loading and preprocessing datasets, tokenizing text, creating input pipelines, and building the model for training and evaluation. Additionally, the article points to a variety of educational resources, including project videos, a tech newsletter, and links to research papers and other projects related to machine learning and data science. The content aims to provide practical knowledge and coding examples to help readers understand and implement machine learning projects effectively.

Opinions

  • The author believes in the importance of understanding the tools and technologies used in data science, such as TensorFlow and BERT, for effective learning and application.
  • There is an emphasis on the practical aspect of learning, with the inclusion of code snippets and the encouragement to subscribe to a YouTube channel for project demonstrations.
  • The author values the sharing of knowledge and resources, as evidenced by the numerous links to educational content and the invitation to join a tech newsletter.
  • The article conveys enthusiasm and encouragement for readers to engage with the material and continue coding, suggesting a passion for teaching and a commitment to supporting learners in the field.
  • The inclusion of a quote by Steve Jobs at the end of the article indicates the author's belief in the importance of passion and perseverance in the pursuit of one's goals in technology and innovation.

Day 50: 60 days of Data Science and Machine Learning Series

Bidirectional Encoder Representations from Transformers ( BERT)…

Pic credits : ResearchGate

Tensorflow is an open source platform for machine learning and deep learning developed by Google Brain Team and written in C++, Python, and CUDA created for large numerical computations and deep learning. It ingests the data in the form of tensors which are nothing but multi-dimensional arrays of higher dimensions to handle large amounts of data. It works on the data flow graphs that have nodes and edges and supports both CPUs and GPUs. It works by preprocessing the data, building the model, training and estimating the model.

Pic credits : Tensorflow org

A good reference to Tensorflow ( used in this project as well ) —

Some of the other best Series —

30 Days of Natural Language Processing ( NLP) Series

30 days of Data Engineering with projects Series

60 days of Data Science and ML Series with projects

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

30 days of Machine Learning Ops

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

Bidirectional Encoder Representations from Transformers ( BERT) , developed by Google is a deeply bidirectional transformer-based machine learning technique for NLP. It primarily trains the language models based on the complete set of words in a query or sentence during text processing.

Pic credits : ResearchGate

A good reference to understand the vastness of BERT —

In this post we will learn how to fine tune BERT for text classification.

Let’s dive in!

Import necessary Libraries

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import sys
sys.path.append('models')
from official.nlp.data import classifier_data_lib
from official.nlp.bert import tokenization
from official.nlp import optimization
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.python.data.ops.dataset_ops import AUTOTUNE
print("TF Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.experimental.list_physical_devices("GPU") else "NOT AVAILABLE")

Output —

TF Version:  2.7.0
Eager mode:  True
Hub version:  0.12.0
GPU is available

Load Dataset

df = pd.read_csv('Path to data', compression='zip',low_memory=False)

Create tf.data.Datasets for Training and Evaluation

train_df, r = train_test_split(df,random_state=42,train_size=0.0075,stratify = df.target.values)
valid_df, _ = train_test_split(r,random_state=42,train_size=0.0075,stratify=r.target.values)
with tf.device('/cpu:0'):
  train_data = tf.data.Dataset.from_tensor_slices((train_df['question_text'].values,train_df['target'].values))
  valid_data = tf.data.Dataset.from_tensor_slices((valid_df.question_text.values,valid_df.target.values))

Pre-trained BERT Model

label_list = [0,1]
msl = 128
tbs=32
 
bert_layer = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2', trainable= True)
vocab_file= bert_layer.resolved_object.vocab_file.asset_path.numpy()
do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()
tokenizer = tokenization.FullTokenizer(vocab_file,do_lower_case)
tokenizer.wordpiece_tokenizer.tokenize('hi! beautiful world')

Output —

['hi', '##!', 'beautiful', 'world']

Tokenize and Preprocess Text

def to_feature(text, label, label_list=label_list, max_seq_length=msl, tokenizer=tokenizer):
  ex = classifier_data_lib.InputExample(guid= None, text_a = text.numpy(),text_b = None, label = label.numpy())
  f = classifier_data_lib.convert_single_example(0,ex,label_list,msl,tokenizer)
  return (f.input_ids,f.input_mask,f.segment_ids,f.label_id)

Eager Execution

def to_feature_map(text, label):
  input_ids, input_mask, segment_ids, label_id = tf.py_function(to_feature,inp=[text,label], Tout = [tf.int32,tf.int32,tf.int32,tf.int32])
input_ids.set_shape([msl])
  input_mask.set_shape([msl])
  segment_ids.set_shape([msl])
  label_id.set_shape([])
x = {
      
      'input_word_ids':input_ids, 'input_mask':input_mask, 'input_type_ids' : segment_ids
}
  return ( x, label_id)

Input Pipeline with tf.data

with tf.device('/cpu:0'):
  # train
  train_data = (train_data.map(to_feature_map,num_parallel_calls=tf.data.experimental.AUTOTUNE)
  
   .shuffle(1000)
   .batch(32,drop_remainder=True)
   .prefetch(tf.data.experimental.AUTOTUNE))
# valid
  valid_data = ( valid_data.map(to_feature_map,num_parallel_calls=tf.data.experimental.AUTOTUNE)
  
   
  .batch(32,drop_remainder=True)
  .prefetch(tf.data.experimental.AUTOTUNE))

Build Model

def create_model():
  input_word_ids = tf.keras.layers.Input(shape=(msl),dtype=tf.int32,num='input_word_ids')
  input_mask = tf.keras.layers.Input(shape=(msl),dtype=tf.int32,num='input_mask')
  segment_ids = tf.keras.layers.Input(shape=(msl),dtype=tf.int32,num='segment_ids')
pooled_output, sequnece_output = bert_layer([input_word_ids,input_mask,sement_ids])
  drop = tf.keras.layers.Droupout(0.4)(pooled_out)
  output = tf.keras.layers.Dense(1,activation='segment_ids
model = tf.keras.Model(
      input = {
          'input_word_ids':input_ids,
          'input_mask':input_mask,
          'input_type_ids':input_type_ids
},
      output = output)
  return model

Fine-Tune BERT

model = create_model()
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=2e-5),
              
              loss= tf.keras.losses.binary_CrossEntropy(),
              metrics = [tf.keras.metrics.BinaryAccuracy()]
              
              )
epochs = 4
history = model.fit(train_data,
                    validation_data = valid_data, epochs=epochs, verbose=1)

Learnings —

How to tokenize and preprocess Text for BERT Build tensorFlow input pipelines for text data with the tf.data API.

Day 51: Coming soon!

Follow and Stay tuned. Keep coding :)

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

That’s it fellas. Peace out and keep coding :)

Stay Tuned and of-course let me end this post with a quote by Steve Jobs ;)

“You have to be burning with an idea, or a problem, or a wrong that you want to right. If you’re not passionate enough from the start, you’ll never stick it out.”

Machine Learning
Artificial Intelligence
Data Science
Tech
Programming
Recommended from ReadMedium