Path: blob/master/site/en-snapshot/hub/tutorials/bangla_article_classifier.ipynb
25118 views
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Bangla Article Classification With TF-Hub
Caution: In addition to installing Python packages with pip, this notebook uses sudo apt install
to install system packages: unzip
.
This Colab is a demonstration of using Tensorflow Hub for text classification in non-English/local languages. Here we choose Bangla as the local language and use pretrained word embeddings to solve a multiclass classification task where we classify Bangla news articles in 5 categories. The pretrained embeddings for Bangla comes from fastText which is a library by Facebook with released pretrained word vectors for 157 languages.
We'll use TF-Hub's pretrained embedding exporter for converting the word embeddings to a text embedding module first and then use the module to train a classifier with tf.keras, Tensorflow's high level user friendly API to build deep learning models. Even if we are using fastText embeddings here, it's possible to export any other embeddings pretrained from other tasks and quickly get results with Tensorflow hub.
Setup
Dataset
We will use BARD (Bangla Article Dataset) which has around 376,226 articles collected from different Bangla news portals and labelled with 5 categories: economy, state, international, sports, and entertainment. We download the file from Google Drive this (bit.ly/BARD_DATASET) link is referring to from this GitHub repository.
Export pretrained word vectors to TF-Hub module
TF-Hub provides some useful scripts for converting word embeddings to TF-hub text embedding modules here. To make the module for Bangla or any other languages, we simply have to download the word embedding .txt
or .vec
file to the same directory as export_v2.py
and run the script.
The exporter reads the embedding vectors and exports it to a Tensorflow SavedModel. A SavedModel contains a complete TensorFlow program including weights and graph. TF-Hub can load the SavedModel as a module, which we will use to build the model for text classification. Since we are using tf.keras
to build the model, we will use hub.KerasLayer, which provides a wrapper for a TF-Hub module to use as a Keras Layer.
First we will get our word embeddings from fastText and embedding exporter from TF-Hub repo.
Then, we will run the exporter script on our embedding file. Since fastText embeddings have a header line and are pretty large (around 3.3 GB for Bangla after converting to a module) we ignore the first line and export only the first 100, 000 tokens to the text embedding module.
The text embedding module takes a batch of sentences in a 1D tensor of strings as input and outputs the embedding vectors of shape (batch_size, embedding_dim) corresponding to the sentences. It preprocesses the input by splitting on spaces. Word embeddings are combined to sentence embeddings with the sqrtn
combiner(See here). For demonstration we pass a list of Bangla words as input and get the corresponding embedding vectors.
Convert to Tensorflow Dataset
Since the dataset is really large instead of loading the entire dataset in memory we will use a generator to yield samples in run-time in batches using Tensorflow Dataset functions. The dataset is also very imbalanced, so, before using the generator, we will shuffle the dataset.
We can check the distribution of labels in the training and validation examples after shuffling.
To create a Dataset using a generator, we first write a generator function which reads each of the articles from file_paths
and the labels from the label array, and yields one training example at each step. We pass this generator function to the tf.data.Dataset.from_generator
method and specify the output types. Each training example is a tuple containing an article of tf.string
data type and one-hot encoded label. We split the dataset with a train-validation split of 80-20 using tf.data.Dataset.skip
and tf.data.Dataset.take
methods.
Model Training and Evaluation
Since we have already added a wrapper around our module to use it as any other layer in Keras, we can create a small Sequential model which is a linear stack of layers. We can add our text embedding module with model.add
just like any other layer. We compile the model by specifying the loss and optimizer and train it for 10 epochs. The tf.keras
API can handle Tensorflow Datasets as input, so we can pass a Dataset instance to the fit method for model training. Since we are using the generator function, tf.data
will handle generating the samples, batching them and feeding them to the model.
Model
Training
Evaluation
We can visualize the accuracy and loss curves for training and validation data using the tf.keras.callbacks.History
object returned by the tf.keras.Model.fit
method, which contains the loss and accuracy value for each epoch.
Prediction
We can get the predictions for the validation data and check the confusion matrix to see the model's performance for each of the 5 classes. Because tf.keras.Model.predict
method returns an n-d array for probabilities for each class, they can be converted to class labels using np.argmax
.
Compare Performance
Now we can take the correct labels for the validation data from labels
and compare them with our predictions to get a classification_report.
We can also compare our model's performance with the published results obtained in the original paper, which had a 0.96 precision .The original authors described many preprocessing steps performed on the dataset, such as dropping punctuations and digits, removing top 25 most frequest stop words. As we can see in the classification_report
, we also manage to obtain a 0.96 precision and accuracy after training for only 5 epochs without any preprocessing!
In this example, when we created the Keras layer from our embedding module, we set the parametertrainable=False
, which means the embedding weights will not be updated during training. Try setting it to True
to reach around 97% accuracy using this dataset after only 2 epochs.