Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TensorFlow Example – Text Classification Project

TensorFlow Example - Text Classification Project

Text classification is a fundamental task in Natural Language Processing (NLP), which refers to automatically categorizing text documents into one or more predefined categories. In practical applications, text classification is widely used in:

Implementing text classification with TensorFlow typically involves the following steps:

  1. Data Preparation and Preprocessing
  2. Text vectorization
  3. Model construction
  4. Model training
  5. Model evaluation
  6. Model Deployment

Environment Preparation

Before starting the project, please make sure the following Python libraries are installed:



!pip install tensorflow

!pip install numpy

!pip install pandas

!pip install matplotlib

Import the necessary libraries:

Example

import

tensorflow

as

tf

from

tensorflow.

keras

import

layers

import

numpy

as

np

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

Check the TensorFlow version:

Example

print

(

tf.version

)

Output example: 2.8.0


Dataset preparation

We will use the IMDB movie review dataset, a classic binary classification dataset containing 50,000 movie reviews, labeled as positive (1) or negative (0).

Load the dataset

Example

Load IMDB data from TensorFlow datasets

imdb

=

tf.

keras

.

datasets

.

imdb

Keep only the top 10,000 most frequent words

(

train_data

,

train_labels

)

,

(

test_data

,

test_labels

)

=

imdb.

load_data

(

num_words

=

10000

)

Data exploration

View the data format:

Example

print

(

"Number of training samples: {}, number of test samples: {}"

.

format

(

len

(

train_data

)

,

len

(

test_data

)

)

)

Output: Number of training samples: 25000, number of test samples: 25000

View the first review

print

(

train_data

[

0

]

)

Output: [1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, ...]

Data preprocessing

Convert the integer sequence to multi-hot encoding:

Example

def

vectorize_sequences

(

sequences

,

dimension

=

10000

)

:

    results

=

np.

zeros

(

(

len

(

sequences

)

,

dimension

)

)

   

for

i

,

sequence

in

enumerate

(

sequences

)

:

        results

[

i

,

sequence

]

=

1

.

   

return

results

x_train

=

vectorize_sequences

(

train_data

)

x_test

=

vectorize_sequences

(

test_data

)

Convert the labels to floating point numbers

y_train

=

np.

asarray

(

train_labels

)

.

astype

(

'float32'

)

y_test

=

np.

asarray

(

test_labels

)

.

astype

(

'float32'

)


Build the model

Model architecture

We will build a simple fully connected neural network:

Example

model

=

tf.

keras

.

Sequential

(

[

    layers.

Dense

(

16

,

activation

=

'relu'

,

input_shape

=

(

10000

,

)

)

,

    layers.

Dense

(

16

,

activation

=

'relu'

)

,

    layers.

Dense

(

1

,

activation

=

'sigmoid'

)

]

)

Model compilation

Example

model.

compile

(

optimizer

=

'rmsprop'

,

              loss

=

'binary_crossentropy'

,

              metrics

=

[

'accuracy'

]

)

Parameter Description:


Train the model

Create a validation set

Example

x_val

=

x_train

[

:

10000

]

partial_x_train

=

x_train

[

10000

:

]

y_val

=

y_train

[

:

10000

]

partial_y_train

=

y_train

[

10000

:

]

Training process

Example

history

=

model.

fit

(

partial_x_train

,

                    partial_y_train

,

                    epochs

=

20

,

                    batch_size

=

512

,

                    validation_data

=

(

x_val

,

y_val

)

)

Visualize training results

Example

history_dict

=

history.

history

Plot training loss and validation loss

plt.

plot

(

history_dict

[

'loss'

]

,

'bo'

,

label

=

'Training loss'

)

plt.

plot

(

history_dict

[

'val_loss'

]

,

'b'

,

label

=

'Validation loss'

)

plt.

title

(

'Training and validation loss'

)

plt.

xlabel

(

'Epochs'

)

plt.

ylabel

(

'Loss'

)

plt.

legend

(

)

plt.

show

(

)

Plot training accuracy and validation accuracy

plt.

plot

(

history_dict

[

'accuracy'

]

,

'bo'

,

label

=

'Training acc'

)

plt.

plot

(

history_dict

[

'val_accuracy'

]

,

'b'

,

label

=

'Validation acc'

)

plt.

title

(

'Training and validation accuracy'

)

plt.

xlabel

(

'Epochs'

)

plt.

ylabel

(

'Accuracy'

)

plt.

legend

(

)

plt.

show

(

)


Model evaluation and prediction

Evaluate test set performance

Example

results

=

model.

evaluate

(

x_test

,

y_test

)

print

(

results

)

Output example: [0.3245, 0.8732] represents loss and accuracy

Make predictions

Example

predictions

=

model.

predict

(

x_test

)

print

(

predictions

[

0

]

)

 

The predicted probability of the first test sample


Model optimization suggestions

  1. Adjust the network architecture:

  2. Increase or decrease the number of hidden layers
  3. Try different numbers of neurons
  4. Use different activation functions
  5. - Increase or decrease the number of hidden layers - Try different numbers of neurons - Use different activation functions
    1. Regularization Techniques:

    2. Add a Dropout layer to prevent overfitting
    3. Use L1/L2 regularization
    4. - Add a Dropout layer to prevent overfitting - Use L1/L2 regularization
      1. Optimizer selection:

      2. Try other optimizers such as Adam and SGD
      3. Adjust the learning rate
      4. - Try other optimizers such as Adam and SGD - Adjust the learning rate
        1. Text preprocessing improvements:

        2. Use word embeddings (Embedding) instead of multi-hot encoding
        3. Try pre-trained word vectors (such as Word2Vec, GloVe)
        4. - Use word embeddings (Embedding) instead of multi-hot encoding - Try pre-trained word vectors (such as Word2Vec, GloVe)

          Complete Code Example

          Example

          import

          tensorflow

          as

          tf

          from

          tensorflow.

          keras

          import

          layers

          import

          numpy

          as

          np

          import

          matplotlib.

          pyplot

          as

          plt

          Load data

          imdb

          =

          tf.

          keras

          .

          datasets

          .

          imdb

          (

          train_data

          ,

          train_labels

          )

          ,

          (

          test_data

          ,

          test_labels

          )

          =

          imdb.

          load_data

          (

          num_words

          =

          10000

          )

          Data preprocessing

          def

          vectorize_sequences

          (

          sequences

          ,

          dimension

          =

          10000

          )

          :

              results

          =

          np.

          zeros

          (

          (

          len

          (

          sequences

          )

          ,

          dimension

          )

          )

             

          for

          i

          ,

          sequence

          in

          enumerate

          (

          sequences

          )

          :

                  results

          [

          i

          ,

          sequence

          ]

          =

          1

          .

             

          return

          results

          x_train

          =

          vectorize_sequences

          (

          train_data

          )

          x_test

          =

          vectorize_sequences

          (

          test_data

          )

          y_train

          =

          np.

          asarray

          (

          train_labels

          )

          .

          astype

          (

          'float32'

          )

          y_test

          =

          np.

          asarray

          (

          test_labels

          )

          .

          astype

          (

          'float32'

          )

          Build the model

          model

          =

          tf.

          keras

          .

          Sequential

          (

          [

              layers.

          Dense

          (

          16

          ,

          activation

          =

          'relu'

          ,

          input_shape

          =

          (

          10000

          ,

          )

          )

          ,

              layers.

          Dense

          (

          16

          ,

          activation

          =

          'relu'

          )

          ,

              layers.

          Dense

          (

          1

          ,

          activation

          =

          'sigmoid'

          )

          ]

          )

          Compile the model

          model.

          compile

          (

          optimizer

          =

          'rmsprop'

          ,

                        loss

          =

          'binary_crossentropy'

          ,

                        metrics

          =

          [

          'accuracy'

          ]

          )

          Train the model

          history

          =

          model.

          fit

          (

          x_train

          ,

          y_train

          ,

                             epochs

          =

          4

          ,

                             batch_size

          =

          512

          ,

                             validation_data

          =

          (

          x_test

          ,

          y_test

          )

          )

          Evaluate the model

          results

          =

          model.

          evaluate

          (

          x_test

          ,

          y_test

          )

          print

          (

          "Test loss and accuracy:"

          ,

          results

          )

          Make predictions

          predictions

          =

          model.

          predict

          (

          x_test

          )

          print

          (

          "Predicted probability of the first review:"

          ,

          predictions

          [

          0

          ]

          )