"""Classify official IMDb feature rows using a bounded multi-hot training pipeline."""
from argparse import ArgumentParser
from collections import Counter
from hashlib import file_digest, sha256
from pathlib import Path
from tempfile import TemporaryDirectory
import json
import platform
import tarfile
import numpy as np
import tensorflow as tf
from tensorflow import keras
ARCHIVE_SHA256 = "c40f74a18d3b61f90feba1e17730e0d38e8b97c05fde7008942e91923d1658fe"
VOCAB_SIZE = 10000
MEMBERS = {"aclImdb/train/labeledBow.feat":("train",21021197),
"aclImdb/test/labeledBow.feat":("test",20205283)}
def read_data(filename):
with filename.open("rb") as source:
if file_digest(source,"sha256").hexdigest()!=ARCHIVE_SHA256:
raise ValueError("Expected the verified official aclImdb_v1.tar.gz archive.")
payload={}
with tarfile.open(filename,"r|gz") as package:
for member in package:
if member.name not in MEMBERS:
continue
split,size=MEMBERS[member.name]
if not member.isfile() or member.size!=size or split in payload:
raise ValueError("Unexpected IMDb feature file.")
labels=[]
entries=[]
with package.extractfile(member) as stream:
for row in stream:
rating,*terms=row.split()
value=int(rating)
if not 1<=value<=10 or 4<value<7:
raise ValueError("A rating has an unexpected value.")
labels.append(int(value>=7))
pairs=[tuple(map(int, field.split(b":",1))) for field in terms]
if any(key<0 or count<1 for key,count in pairs):
raise ValueError("The feature row has an invalid term.")
entries.append(pairs)
payload[split]=(entries,np.array(labels,dtype=np.int32))
if set(payload)!={"train","test"}:
raise ValueError("The archive does not contain both official feature files.")
return payload
def choose(labels, count_per_class, rng, exclude=()):
selected=[]
for label in (0,1):
candidates=np.setdiff1d(np.flatnonzero(labels==label),exclude)
selected.extend(rng.choice(candidates,size=count_per_class,replace=False).tolist())
return rng.permutation(selected)
def rank_vocabulary(rows,indices):
totals=Counter()
for index in indices:
totals.update(dict(rows[index]))
ranked=sorted(totals.items(),key=lambda item:(-item[1],item[0]))[:VOCAB_SIZE]
return {term:column for column,(term,_) in enumerate(ranked)}
def multi_hot(rows,vocabulary):
output=np.zeros((len(rows),VOCAB_SIZE),dtype=np.float32)
for index,row in enumerate(rows):
for term,count in row:
if term in vocabulary:
output[index,vocabulary[term]]=1.
return output
def as_dataset(data,labels,batch_size=512,training=False):
options=tf.data.Options()
options.threading.private_threadpool_size=1
dataset=tf.data.Dataset.from_tensor_slices((data,labels)).with_options(options)
if training:
dataset=dataset.shuffle(len(labels),seed=1731)
return dataset.batch(batch_size).prefetch(1)
def dense_classifier(vocabulary_size,variant=False):
stack=[keras.Input((vocabulary_size,)),keras.layers.Dense(16,activation="relu"),
keras.layers.Dense(16,activation="relu"),keras.layers.Dense(1,activation="sigmoid")]
if variant:
stack=[stack[0],keras.layers.Dense(8,activation="tanh",kernel_regularizer=keras.regularizers.L1L2(.001,.001)),
keras.layers.Dropout(.25,seed=8),stack[-1]]
return keras.Sequential(stack)
def observe(cases,name,operation,inputs,expected,actual,measurements=None):
assert expected==actual,(name,expected,actual)
result=dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True)
if measurements is not None:
result["measurements"]=measurements
cases.append(result)
def main(filename):
keras.utils.set_random_seed(1728)
cases=[]
observe(cases,"environment_versions","Record the installed library versions of the running classifier",
["TensorFlow","Keras","NumPy"],[True]*3,
[bool(tf.__version__),bool(keras.__version__),bool(np.__version__)],
{"tensorflow":tf.__version__,"keras":keras.__version__,"numpy":np.__version__})
split=read_data(filename)
train_rows,train_labels=split["train"]
test_rows,test_labels=split["test"]
full_counts=[np.bincount(labels,minlength=2).tolist() for labels in (train_labels,test_labels)]
observe(cases,"official_feature_input","Read counts and sample numeric token data from both verified feature files",
{"archive_sha256":ARCHIVE_SHA256},[25000,25000,[[12500,12500],[12500,12500]],True],
[len(train_rows),len(test_rows),full_counts,all(term>=0 and count>0 for term,count in train_rows[0])],
{"first_review_distinct_terms":len(train_rows[0]),"first_review_label":int(train_labels[0])})
rng=np.random.default_rng(1732)
train=choose(train_labels,1024,rng)
validation=choose(train_labels,256,rng,exclude=train)
testing=choose(test_labels,256,rng)
observe(cases,"split_and_vocabulary","Reserve training, validation and official test rows before fitting the vocabulary",
{"seed":1732},[2048,512,512,0,[[1024,1024],[256,256],[256,256]]],
[len(train),len(validation),len(testing),len(np.intersect1d(train,validation)),
[np.bincount(labels[indices],minlength=2).tolist()
for labels,indices in ((train_labels,train),(train_labels,validation),(test_labels,testing))]])
vocabulary=rank_vocabulary(train_rows,train)
assert len(vocabulary)==VOCAB_SIZE
train_source=[train_rows[index] for index in train]
x=multi_hot(train_source,vocabulary)
vx=multi_hot([train_rows[index] for index in validation],vocabulary)
tx=multi_hot([test_rows[index] for index in testing],vocabulary)
y,vy,ty=train_labels[train],train_labels[validation],test_labels[testing]
exact=multi_hot([[(15,4),(99,2)],[]],{15:0})
observe(cases,"ten_thousand_multi_hot","Encode each present vocabulary term once, filter absent terms, check dtype and empty rows",
{"columns":VOCAB_SIZE,"sample_count":2048},[[2048,10000],"float32",[0.,1.],[1.,0.]],
[list(x.shape),str(x.dtype),np.unique(x).tolist(),exact.sum(axis=1).tolist()])
model=dense_classifier(VOCAB_SIZE)
output=model(x[:4])
model.compile(optimizer=keras.optimizers.RMSprop(0.001),loss=keras.losses.BinaryCrossentropy(),
metrics=[keras.metrics.BinaryAccuracy(name="accuracy")])
observe(cases,"dense_rmsprop_config","Inspect two hidden layers, probability range and compiled optimizer",
{"input_width":VOCAB_SIZE},[[16,16,1],[4,1],"RMSprop",True],
[[layer.units for layer in model.layers],list(output.shape),type(model.optimizer).__name__,
bool(tf.reduce_all((output>=0)&(output<=1)))])
training=as_dataset(x,y,training=True)
validating=as_dataset(vx,vy)
history=model.fit(training,validation_data=validating,epochs=20,verbose=0,shuffle=False).history
observe(cases,"history_twenty_epochs","Train with fixed 512-row batches and collect separate loss and accuracy series",
{"epochs":20,"batch_size":512,"train":2048,"validation":512},[80,[20,20,20,20],True,True],
[int(model.optimizer.iterations),[len(history[key]) for key in ("loss","val_loss","accuracy","val_accuracy")],
all(np.isfinite(values).all() for values in history.values()),history["loss"][-1]<history["loss"][0]],
{"history":history})
evaluation=model.evaluate(as_dataset(tx,ty),return_dict=True,verbose=0)
scores=model.predict(as_dataset(tx,ty),verbose=0)
predicted=scores[:,0]>.5
observed_accuracy=float(np.mean(predicted==ty))
observe(cases,"test_loss_and_accuracy","Compare named evaluation metrics with test predictions on the official held-out split",
{"test_rows":512},[["accuracy","loss"],True,True],
[sorted(evaluation),bool(np.isfinite(list(evaluation.values())).all()),abs(observed_accuracy-evaluation["accuracy"])<1e-6],
evaluation)
observe(cases,"predict_probability","Return probabilities and a thresholded label for the first selected test row",
{"threshold":.5},[[512,1],True,True],
[list(scores.shape),bool(np.all((scores>=0)&(scores<=1))),int(predicted[0])==int(scores[0,0]>.5)],
{"first_test_index":int(testing[0]),"probability":float(scores[0,0]),"predicted_label":int(predicted[0]),
"true_label":int(ty[0])})
with TemporaryDirectory() as directory:
path=Path(directory)/"sentiment.keras"
model.save(path)
restored=keras.models.load_model(path)
same=np.allclose(restored(tx[:4]).numpy(),scores[:4],atol=1e-6)
observe(cases,"save_and_reload","Save a local Keras model and verify restored inference on matching vocabulary columns",
{"rows":4,"format":".keras"},[True,True],[path.is_file(),bool(same)],
{"sha256":sha256(path.read_bytes()).hexdigest(),"bytes":path.stat().st_size})
alternate=[]
for optimizer in (keras.optimizers.Adam(.001),keras.optimizers.SGD(.01)):
candidate=dense_classifier(VOCAB_SIZE,variant=True)
candidate.compile(optimizer=optimizer,loss="binary_crossentropy")
value=candidate.train_on_batch(x[:32],y[:32])
alternate.append([type(optimizer).__name__,len(candidate.losses)>0,int(optimizer.iterations),float(value)])
observe(cases,"regularized_optimizer_variants","Run one Adam and SGD update with a small tanh layer and regularization",
{"dropout":.25,"l1":.001,"l2":.001},[["Adam",True,1,True],["SGD",True,1,True]],
[[name,regularized,step,bool(np.isfinite(loss))] for name,regularized,step,loss in alternate],
{"updates":alternate})
token_rows=[]
for review in train_source[:32]:
ids=[vocabulary[term]+1 for term,count in review if term in vocabulary]
token_rows.append(ids[:128])
token_ids=keras.utils.pad_sequences(token_rows,maxlen=128,padding="post",truncating="post")
embedding=keras.Sequential([keras.Input((128,),dtype=tf.int32),
keras.layers.Embedding(VOCAB_SIZE+1,16,mask_zero=True),keras.layers.GlobalAveragePooling1D(),
keras.layers.Dense(1,activation="sigmoid")])
embedding.compile(optimizer="adam",loss="binary_crossentropy")
value=embedding.train_on_batch(token_ids,y[:32])
predictions=embedding(token_ids,training=False).numpy()
observe(cases,"pooled_embedding","Index retained terms plus a zero mask and run a pooled embedding update",
{"vocabulary_ids":[1,VOCAB_SIZE],"padding_id":0},[[32,128],[32,1],1,True],
[list(token_ids.shape),list(predictions.shape),int(embedding.optimizer.iterations),bool(np.isfinite(value))],
{"order_semantics":"Official bag of words; the retained ID list cannot recover the original wording or order."})
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=keras.__version__,
system=platform.system(),devices=[item.name for item in tf.config.list_physical_devices()],cases=cases)))
if __name__=="__main__":
parser=ArgumentParser()
parser.add_argument("archive",type=Path)
main(parser.parse_args().archive)
本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
入口文件:projects/tensorflow-text-classification-lab/train-imdb-sentiment.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
train-imdb-sentiment.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a381.zip