Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions python-keras-text-classification/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Practical Text Classification With Python and Keras

This folder contains the sample code for the Real Python tutorial [Practical Text Classification With Python and Keras](https://realpython.com/python-keras-text-classification/).

## Setup

The code was tested with Python 3.14. TensorFlow doesn't publish wheels for Python 3.15 yet, so use Python 3.14 or older.

Create and activate a virtual environment, then install the pinned dependencies:

```sh
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

Download the [Sentiment Labelled Sentences](https://archive.ics.uci.edu/dataset/331/sentiment+labelled+sentences) data set from the UCI Machine Learning Repository. Unzip it, rename the extracted `sentiment labelled sentences` folder to `sentiment_analysis`, and move it into a `data/` folder next to the scripts.

For `pretrained_embeddings.py`, you also need the [GloVe](https://nlp.stanford.edu/projects/glove/) word embeddings. Download `glove.6B.zip` (822 MB) and extract `glove.6B.50d.txt` into `data/glove_word_embeddings/`.

The resulting layout looks like this:

```
data/
├── glove_word_embeddings/
│ └── glove.6B.50d.txt
└── sentiment_analysis/
├── amazon_cells_labelled.txt
├── imdb_labelled.txt
└── yelp_labelled.txt
```

## Usage

Run the scripts in the order of the tutorial's sections:

```sh
(venv) $ python data_loading.py
(venv) $ python baseline_model.py
(venv) $ python first_keras_model.py
(venv) $ python one_hot_encoding.py
(venv) $ python text_vectorization.py
(venv) $ python word_embeddings.py
(venv) $ python pretrained_embeddings.py
(venv) $ python convolutional_model.py
(venv) $ python random_search.py
```

The training scripts print the training and testing accuracy and save the training history plots as PNG files in the current folder. Because the weights start out random, your numbers will differ a little from the ones in the tutorial. If the Flatten model in `word_embeddings.py` gets stuck at a training accuracy of about 0.5067, then it predicts the same label for every review. Run the script again.

`random_search.py` runs a cross-validated random search over all three data sets, which takes roughly ten minutes on a laptop without a GPU. It appends its results to `data/output.txt`.
40 changes: 40 additions & 0 deletions python-keras-text-classification/baseline_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression

from data_loading import load_data, split_source

# Bag-of-words model on two example sentences
sentences = ["John likes ice cream", "John hates chocolate."]
vectorizer = CountVectorizer(min_df=1, lowercase=False)
vectorizer.fit(sentences)
print(vectorizer.vocabulary_)
print(vectorizer.transform(sentences).toarray())

# Logistic regression baseline on the Yelp reviews
df = load_data()
sentences_train, sentences_test, y_train, y_test = split_source(df, "yelp")

vectorizer = CountVectorizer()
vectorizer.fit(sentences_train)
X_train = vectorizer.transform(sentences_train)
X_test = vectorizer.transform(sentences_test)
print(repr(X_train))

classifier = LogisticRegression()
classifier.fit(X_train, y_train)
score = classifier.score(X_test, y_test)
print("Accuracy:", score)

# Baseline for each data set
for source in df["source"].unique():
sentences_train, sentences_test, y_train, y_test = split_source(df, source)

vectorizer = CountVectorizer()
vectorizer.fit(sentences_train)
X_train = vectorizer.transform(sentences_train)
X_test = vectorizer.transform(sentences_test)

classifier = LogisticRegression()
classifier.fit(X_train, y_train)
score = classifier.score(X_test, y_test)
print("Accuracy for {} data: {:.4f}".format(source, score))
37 changes: 37 additions & 0 deletions python-keras-text-classification/convolutional_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import keras
from keras import layers
from keras.models import Sequential

from data_loading import load_data, split_source
from plotting import evaluate, plot_history
from text_vectorization import maxlen, vectorize

df = load_data()
sentences_train, sentences_test, y_train, y_test = split_source(df, "yelp")
vocab, X_train, X_test = vectorize(sentences_train, sentences_test)
vocab_size = len(vocab)

embedding_dim = 100

model = Sequential()
model.add(keras.Input(shape=(maxlen,)))
model.add(layers.Embedding(vocab_size, embedding_dim))
model.add(layers.Conv1D(128, 5, activation="relu"))
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(10, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))
model.compile(
optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]
)
model.summary()

history = model.fit(
X_train,
y_train,
epochs=10,
verbose=False,
validation_data=(X_test, y_test),
batch_size=10,
)
evaluate(model, X_train, y_train, X_test, y_test)
plot_history(history, "convolution_model.png")
29 changes: 29 additions & 0 deletions python-keras-text-classification/data_loading.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import pandas as pd
from sklearn.model_selection import train_test_split

filepath_dict = {
"yelp": "data/sentiment_analysis/yelp_labelled.txt",
"amazon": "data/sentiment_analysis/amazon_cells_labelled.txt",
"imdb": "data/sentiment_analysis/imdb_labelled.txt",
}


def load_data():
df_list = []
for source, filepath in filepath_dict.items():
df = pd.read_csv(filepath, names=["sentence", "label"], sep="\t")
df["source"] = source # Add another column filled with the source name
df_list.append(df)
return pd.concat(df_list)


def split_source(df, source="yelp"):
df_source = df[df["source"] == source]
sentences = df_source["sentence"].values
y = df_source["label"].values
return train_test_split(sentences, y, test_size=0.25, random_state=1000)


if __name__ == "__main__":
df = load_data()
print(df.iloc[0])
37 changes: 37 additions & 0 deletions python-keras-text-classification/first_keras_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import keras
from keras import layers
from keras.models import Sequential
from sklearn.feature_extraction.text import CountVectorizer

from data_loading import load_data, split_source
from plotting import evaluate, plot_history

df = load_data()
sentences_train, sentences_test, y_train, y_test = split_source(df, "yelp")

vectorizer = CountVectorizer()
vectorizer.fit(sentences_train)
X_train = vectorizer.transform(sentences_train)
X_test = vectorizer.transform(sentences_test)

input_dim = X_train.shape[1] # Number of features

model = Sequential()
model.add(keras.Input(shape=(input_dim,)))
model.add(layers.Dense(10, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))
model.compile(
loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
)
model.summary()

history = model.fit(
X_train,
y_train,
epochs=100,
verbose=False,
validation_data=(X_test, y_test),
batch_size=10,
)
evaluate(model, X_train, y_train, X_test, y_test)
plot_history(history, "first_model.png")
12 changes: 12 additions & 0 deletions python-keras-text-classification/one_hot_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from sklearn.preprocessing import LabelEncoder, OneHotEncoder

cities = ["London", "Berlin", "Berlin", "New York", "London"]
print(cities)

encoder = LabelEncoder()
city_labels = encoder.fit_transform(cities)
print(city_labels)

encoder = OneHotEncoder(sparse_output=False)
city_labels = city_labels.reshape((5, 1))
print(encoder.fit_transform(city_labels))
33 changes: 33 additions & 0 deletions python-keras-text-classification/plotting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import matplotlib.pyplot as plt

plt.style.use("ggplot")


def plot_history(history, filename=None):
acc = history.history["accuracy"]
val_acc = history.history["val_accuracy"]
loss = history.history["loss"]
val_loss = history.history["val_loss"]
x = range(1, len(acc) + 1)

plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(x, acc, "b", label="Training acc")
plt.plot(x, val_acc, "r", label="Validation acc")
plt.title("Training and validation accuracy")
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(x, loss, "b", label="Training loss")
plt.plot(x, val_loss, "r", label="Validation loss")
plt.title("Training and validation loss")
plt.legend()
if filename:
plt.savefig(filename)
print(f"Saved the training history plot to {filename}")


def evaluate(model, X_train, y_train, X_test, y_test):
loss, accuracy = model.evaluate(X_train, y_train, verbose=False)
print("Training Accuracy: {:.4f}".format(accuracy))
loss, accuracy = model.evaluate(X_test, y_test, verbose=False)
print("Testing Accuracy: {:.4f}".format(accuracy))
70 changes: 70 additions & 0 deletions python-keras-text-classification/pretrained_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import keras
from keras import layers
from keras.models import Sequential
import numpy as np

from data_loading import load_data, split_source
from plotting import evaluate, plot_history
from text_vectorization import maxlen, vectorize


def create_embedding_matrix(filepath, vocabulary, embedding_dim):
word_index = {word: index for index, word in enumerate(vocabulary)}
embedding_matrix = np.zeros((len(vocabulary), embedding_dim))

with open(filepath, encoding="utf-8") as f:
for line in f:
word, *vector = line.split()
if word in word_index:
idx = word_index[word]
embedding_matrix[idx] = np.array(vector, dtype=np.float32)[
:embedding_dim
]

return embedding_matrix


df = load_data()
sentences_train, sentences_test, y_train, y_test = split_source(df, "yelp")
vocab, X_train, X_test = vectorize(sentences_train, sentences_test)
vocab_size = len(vocab)

embedding_dim = 50
embedding_matrix = create_embedding_matrix(
"data/glove_word_embeddings/glove.6B.50d.txt", vocab, embedding_dim
)
nonzero_elements = np.count_nonzero(np.count_nonzero(embedding_matrix, axis=1))
print(nonzero_elements / vocab_size)

for trainable in (False, True):
model = Sequential()
model.add(keras.Input(shape=(maxlen,)))
model.add(
layers.Embedding(
vocab_size,
embedding_dim,
embeddings_initializer=keras.initializers.Constant(
embedding_matrix
),
trainable=trainable,
)
)
model.add(layers.GlobalMaxPooling1D())
model.add(layers.Dense(10, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))
model.compile(
optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]
)
model.summary()

history = model.fit(
X_train,
y_train,
epochs=50,
verbose=False,
validation_data=(X_test, y_test),
batch_size=10,
)
evaluate(model, X_train, y_train, X_test, y_test)
suffix = "trained" if trainable else "untrained"
plot_history(history, f"embedding_{suffix}.png")
Loading
Loading