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:
- Spam Detection
- Sentiment analysis
- News Classification
- Customer service conversation classification
- Product review classification
Implementing text classification with TensorFlow typically involves the following steps:
- Data Preparation and Preprocessing
- Text vectorization
- Model construction
- Model training
- Model evaluation
- 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
(
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
(
"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
(
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:
optimizer: Optimizer, controls the learning processloss: Loss function, measures the difference between model predictions and true labelsmetrics: Evaluation metric, monitors the training and testing steps
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
)
(
results
)
Output example: [0.3245, 0.8732] represents loss and accuracy
Make predictions
Example
predictions
=
model.
predict
(
x_test
)
(
predictions
[
0
]
)
The predicted probability of the first test sample
Model optimization suggestions
-
Adjust the network architecture:
-
Regularization Techniques:
-
Optimizer selection:
-
Text preprocessing improvements:
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
)
(
"Test loss and accuracy:"
,
results
)
Make predictions
predictions
=
model.
predict
(
x_test
)
(
"Predicted probability of the first review:"
,
predictions
[
0
]
)