Keras: IMDB text¶
IMDB sentiment with a Keras embedding model. Same callback as the Fashion-MNIST tutorial.
| Framework | TensorFlow / Keras |
| Task | Text classification |
Install¶
Plus the K-Veritas CLI.
train.py¶
Only the KV lines and the callback are new.
import numpy as np
import tensorflow as tf
SEED = 42
tf.keras.utils.set_random_seed(SEED)
print(f"KV seed {SEED}")
VOCAB = 20000
MAXLEN = 200
print("KV phase data")
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=VOCAB)
x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=MAXLEN)
x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=MAXLEN)
model = tf.keras.Sequential([
tf.keras.layers.Input((MAXLEN,)),
tf.keras.layers.Embedding(VOCAB, 64),
tf.keras.layers.GlobalAveragePooling1D(),
tf.keras.layers.Dense(64, activation="relu"),
tf.keras.layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
print(f"KV model params={model.count_params()} arch=embedding_mlp precision=fp32")
print(f"KV workload dataset_size={len(x_train)} epochs=4 batch_size=256")
class KVeritas(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
for name, value in (logs or {}).items():
print(f"KV {name.replace('/', '_')}={float(value):.4f} step={epoch}")
print("KV phase train")
model.fit(x_train, y_train, validation_split=0.1, epochs=4, batch_size=256,
verbose=2, callbacks=[KVeritas()])
print("KV phase evaluate")
loss, acc = model.evaluate(x_test, y_test, verbose=0)
print(f"KV test_accuracy={acc:.4f}")
print(f"KV claim test_accuracy={acc:.4f}")
print(f"final test_accuracy={acc:.4f}", flush=True)
Run it¶
Result¶
4 epochs: about 87.6% test accuracy.