From d8734c96b5dbc3d3777fbf797875712b9af3a9e8 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:51:17 +0000 Subject: [PATCH] Add python-keras-text-classification materials folder Sample code for the Keras 3 update of Practical Text Classification With Python and Keras: one script per section, pinned requirements.txt. Co-Authored-By: Claude Opus 5.5 --- python-keras-text-classification/README.md | 51 ++++++++++ .../baseline_model.py | 40 ++++++++ .../convolutional_model.py | 37 ++++++++ .../data_loading.py | 29 ++++++ .../first_keras_model.py | 37 ++++++++ .../one_hot_encoding.py | 12 +++ python-keras-text-classification/plotting.py | 33 +++++++ .../pretrained_embeddings.py | 70 ++++++++++++++ .../random_search.py | 92 +++++++++++++++++++ .../requirements.txt | 7 ++ .../text_vectorization.py | 36 ++++++++ .../word_embeddings.py | 60 ++++++++++++ 12 files changed, 504 insertions(+) create mode 100644 python-keras-text-classification/README.md create mode 100644 python-keras-text-classification/baseline_model.py create mode 100644 python-keras-text-classification/convolutional_model.py create mode 100644 python-keras-text-classification/data_loading.py create mode 100644 python-keras-text-classification/first_keras_model.py create mode 100644 python-keras-text-classification/one_hot_encoding.py create mode 100644 python-keras-text-classification/plotting.py create mode 100644 python-keras-text-classification/pretrained_embeddings.py create mode 100644 python-keras-text-classification/random_search.py create mode 100644 python-keras-text-classification/requirements.txt create mode 100644 python-keras-text-classification/text_vectorization.py create mode 100644 python-keras-text-classification/word_embeddings.py diff --git a/python-keras-text-classification/README.md b/python-keras-text-classification/README.md new file mode 100644 index 0000000000..9c1e88ab86 --- /dev/null +++ b/python-keras-text-classification/README.md @@ -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`. diff --git a/python-keras-text-classification/baseline_model.py b/python-keras-text-classification/baseline_model.py new file mode 100644 index 0000000000..b4582dd5da --- /dev/null +++ b/python-keras-text-classification/baseline_model.py @@ -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)) diff --git a/python-keras-text-classification/convolutional_model.py b/python-keras-text-classification/convolutional_model.py new file mode 100644 index 0000000000..23d034e907 --- /dev/null +++ b/python-keras-text-classification/convolutional_model.py @@ -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") diff --git a/python-keras-text-classification/data_loading.py b/python-keras-text-classification/data_loading.py new file mode 100644 index 0000000000..7162695eb8 --- /dev/null +++ b/python-keras-text-classification/data_loading.py @@ -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]) diff --git a/python-keras-text-classification/first_keras_model.py b/python-keras-text-classification/first_keras_model.py new file mode 100644 index 0000000000..faf6bc4586 --- /dev/null +++ b/python-keras-text-classification/first_keras_model.py @@ -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") diff --git a/python-keras-text-classification/one_hot_encoding.py b/python-keras-text-classification/one_hot_encoding.py new file mode 100644 index 0000000000..6df9f0a07b --- /dev/null +++ b/python-keras-text-classification/one_hot_encoding.py @@ -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)) diff --git a/python-keras-text-classification/plotting.py b/python-keras-text-classification/plotting.py new file mode 100644 index 0000000000..7f5471b8e2 --- /dev/null +++ b/python-keras-text-classification/plotting.py @@ -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)) diff --git a/python-keras-text-classification/pretrained_embeddings.py b/python-keras-text-classification/pretrained_embeddings.py new file mode 100644 index 0000000000..35a50feda2 --- /dev/null +++ b/python-keras-text-classification/pretrained_embeddings.py @@ -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") diff --git a/python-keras-text-classification/random_search.py b/python-keras-text-classification/random_search.py new file mode 100644 index 0000000000..ab632846ae --- /dev/null +++ b/python-keras-text-classification/random_search.py @@ -0,0 +1,92 @@ +import keras +from keras import layers +from keras.models import Sequential +from scikeras.wrappers import KerasClassifier +from sklearn.model_selection import RandomizedSearchCV, train_test_split + +from data_loading import load_data +from text_vectorization import vectorize + + +def create_model(num_filters, kernel_size, vocab_size, embedding_dim, maxlen): + model = Sequential() + model.add(keras.Input(shape=(maxlen,))) + model.add(layers.Embedding(vocab_size, embedding_dim)) + model.add(layers.Conv1D(num_filters, kernel_size, 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"] + ) + return model + + +# Main settings +epochs = 20 +embedding_dim = 50 +maxlen = 100 +output_file = "data/output.txt" + +df = load_data() + +# Run grid search for each source (yelp, amazon, imdb) +for source, frame in df.groupby("source"): + print("Running grid search for data set :", source) + sentences = frame["sentence"].values + y = frame["label"].values + + # Train-test split + sentences_train, sentences_test, y_train, y_test = train_test_split( + sentences, y, test_size=0.25, random_state=1000 + ) + + # Tokenize words and pad sequences with zeros + vocab, X_train, X_test = vectorize(sentences_train, sentences_test, maxlen) + vocab_size = len(vocab) + + # Parameter grid for grid search + param_grid = dict( + num_filters=[32, 64, 128], + kernel_size=[3, 5, 7], + vocab_size=[vocab_size], + embedding_dim=[embedding_dim], + maxlen=[maxlen], + ) + model = KerasClassifier( + model=create_model, + epochs=epochs, + batch_size=10, + verbose=False, + num_filters=32, + kernel_size=3, + vocab_size=vocab_size, + embedding_dim=embedding_dim, + maxlen=maxlen, + ) + grid = RandomizedSearchCV( + estimator=model, + param_distributions=param_grid, + cv=4, + verbose=1, + n_iter=5, + ) + grid_result = grid.fit(X_train, y_train) + + # Evaluate testing set + test_accuracy = grid.score(X_test, y_test) + + # Save and evaluate results + with open(output_file, "a") as f: + s = ( + "Running {} data set\nBest Accuracy : " + "{:.4f}\n{}\nTest Accuracy : {:.4f}\n\n" + ) + output_string = s.format( + source, + grid_result.best_score_, + grid_result.best_params_, + test_accuracy, + ) + print(output_string) + f.write(output_string) diff --git a/python-keras-text-classification/requirements.txt b/python-keras-text-classification/requirements.txt new file mode 100644 index 0000000000..1917e7632c --- /dev/null +++ b/python-keras-text-classification/requirements.txt @@ -0,0 +1,7 @@ +keras==3.15.1 +matplotlib==3.11.2 +numpy==2.5.5 +pandas==3.1.2 +scikeras==0.13.0 +scikit-learn==1.9.1 +tensorflow==2.22.0 diff --git a/python-keras-text-classification/text_vectorization.py b/python-keras-text-classification/text_vectorization.py new file mode 100644 index 0000000000..5838fd7da4 --- /dev/null +++ b/python-keras-text-classification/text_vectorization.py @@ -0,0 +1,36 @@ +import numpy as np +from keras.layers import TextVectorization + +maxlen = 100 + + +def vectorize(sentences_train, sentences_test, maxlen=maxlen): + vectorize_layer = TextVectorization( + max_tokens=5000, output_mode="int", output_sequence_length=maxlen + ) + vectorize_layer.adapt(sentences_train) + X_train = np.array(vectorize_layer(sentences_train)) + X_test = np.array(vectorize_layer(sentences_test)) + return vectorize_layer.get_vocabulary(), X_train, X_test + + +if __name__ == "__main__": + from data_loading import load_data, split_source + + df = load_data() + sentences_train, sentences_test, y_train, y_test = split_source(df) + + vectorize_layer = TextVectorization(max_tokens=5000, output_mode="int") + vectorize_layer.adapt(sentences_train) + vocab = vectorize_layer.get_vocabulary() + print(len(vocab)) + print(vocab[:2]) + print(sentences_train[2]) + print(repr(np.array(vectorize_layer([sentences_train[2]])))) + + for word in ["the", "all", "happy", "sad"]: + print("{}: {}".format(word, vocab.index(word))) + + vocab, X_train, X_test = vectorize(sentences_train, sentences_test) + print(X_train.shape) + print(X_train[0, :]) diff --git a/python-keras-text-classification/word_embeddings.py b/python-keras-text-classification/word_embeddings.py new file mode 100644 index 0000000000..f74f0fb36d --- /dev/null +++ b/python-keras-text-classification/word_embeddings.py @@ -0,0 +1,60 @@ +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 = 50 + +# Embedding layer followed by a Flatten layer +model = Sequential() +model.add(keras.Input(shape=(maxlen,))) +model.add(layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)) +model.add(layers.Flatten()) +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=20, + verbose=False, + validation_data=(X_test, y_test), + batch_size=10, +) +evaluate(model, X_train, y_train, X_test, y_test) +plot_history(history, "embedding_flatten.png") + +# Embedding layer followed by a GlobalMaxPooling1D layer +model = Sequential() +model.add(keras.Input(shape=(maxlen,))) +model.add(layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)) +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) +plot_history(history, "max_pooling.png")