Views
No views yet
pages/03_IMDB_Sentiment_SimpleRNN.py)artifacts/simple_rnn_imdb.h5 — trained Keras modelartifacts/config.json — key inference settings:
max_features (vocab size cap)max_len (sequence length)threshold_default (classification threshold)[a-z']+tensorflow.keras.datasets.imdb.get_word_index())12+3max_features; anything outside becomes 2 (unknown)max_len using pad_sequences (padding="pre", truncating="post")[0, 1].Positive if P(positive) >= thresholdNegative otherwiseartifacts/config.json (typically 0.5).1import re
2import numpy as np
3import tensorflow as tf
4from huggingface_hub import hf_hub_download
5from tensorflow.keras.preprocessing.sequence import pad_sequences
6from tensorflow.keras.datasets import imdb
7import json
8
9REPO_ID = "ash001/imdb-sentiment-simple-rnn"
10
11# Load model + config
12model_path = hf_hub_download(REPO_ID, "artifacts/simple_rnn_imdb.h5")
13cfg_path = hf_hub_download(REPO_ID, "artifacts/config.json")
14cfg = json.load(open(cfg_path, "r"))
15
16model = tf.keras.models.load_model(model_path, compile=False)
17word_index = imdb.get_word_index()
18
19max_features = int(cfg["max_features"])
20max_len = int(cfg["max_len"])
21threshold = float(cfg.get("threshold_default", 0.5))
22
23def text_to_sequence(text: str):
24 text = text.lower()
25 tokens = re.findall(r"[a-z']+", text)
26
27 seq = [1] # start token
28 for w in tokens:
29 idx = word_index.get(w, 2) + 3
30 if idx >= max_features:
31 idx = 2
32 seq.append(idx)
33
34 return pad_sequences([seq], maxlen=max_len, truncating="post", padding="pre")
35
36text = "This movie was surprisingly good, with great acting and a strong ending."
37X = text_to_sequence(text)
38
39prob_pos = float(model.predict(X, verbose=0).reshape(-1)[0])
40label = "Positive" if prob_pos >= threshold else "Negative"
41print("P(positive) =", prob_pos, "|", label)