TensorFlow 实例 - 文本分类项目
将真实 IMDb 词袋特征转成多热输入,验证二分类训练、评估、预测和模型保存。
学完这一章,你能够
- 将真实 IMDb 词袋特征转成多热输入,验证二分类训练、评估、预测和模型保存。
确定文本的分类任务与环境
邮件过滤、新闻分类、客服分流和评论情感分析使用不同标签空间。本站做正负两类,流程包括数据划分、向量化、训练、评估和模型保存。解压后按 requirements.txt 安装 TensorFlow、Keras 和数值依赖,运行代码打印实际版本。Pandas 可用于表格探索,Matplotlib 可绘制历史。本章直接读官方数值特征并生成阅读页曲线。
核对发行数据和词表边界
IMDb 有 25,000 条官方训练评论和 25,000 条官方测试评论,两组正负各半。Keras 内置加载器返回整数词序列,可用 num_words 限定常见词并保留专用标记。本站使用同一数据发行方的 labeledBow.feat 格式,逐行核对评分与词项计数;保留计数、舍弃词序,不能把词袋还原成原句。
从选出的训练样本统计词频并建立 10,000 列,验证与测试只能使用既定列。多热编码把出现过的词设为 1,重复次数不累加。非词表项跳过,空记录仍是全零。用 float32 存储示例,更大的数据可考虑稀疏表示。
构建两个隐藏层并检查输出
Dense 的输入宽度等于词表列数,两个 16 单元隐藏层使用 ReLU;末端 sigmoid 产生一列正类概率。RMSprop 根据梯度历史调整更新幅度,binary_crossentropy 测量预测与标签差异,BinaryAccuracy 记录阈值后的准确率。
从训练集中保留验证样本
在官方训练分区内抽取 2,048 条拟合、512 条验证,保证两者索引互斥且各类平衡。每批 512 条,初始实验固定 20 轮,实际更新 80 次。独立测试来自官方测试分区。词表只从拟合样本统计。
记录训练和验证准确率,查看预测命中的比例随轮次如何变化。
二元交叉熵衡量概率误差。若训练继续改善而验证恶化,可用验证数据确定轮次,测试集留到最后。
用持有的测试样本检验整个流程
evaluate 以具名结果返回测试损失和准确率。逐条应用概率大于 0.5 的阈值,并把结果与实际标签比较。accuracy 等于命中比例;概率可用于回顾阈值。保存 .keras 并载入核对同一行概率,输入转换表及列顺序需与模型配套保存。
查验改进分支与可运行代码
可逐项变动深度、宽度、激活、优化器和学习率。变体实际用较窄 tanh 层、Dropout、L1/L2 与 Adam 或 SGD 更新。Embedding 分支把保留词项映射到稠密向量,0 留作掩码并池化;本例词袋输入无原句顺序。Word2Vec、GloVe 等预训练向量需要独立核对词表、向量维度、许可与未知词。
下载代码从发行方归档读取数据,完成词表拟合、训练、验证、官方测试、预测和模型载入。附带的 README 记录来源和散列。用测试集同时做 validation_data 会参与模型选择,因此训练改用独立验证划分。
用 IMDb 的官方词袋特征训练和评估情感分类器
展开查看收起
"""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)
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 运行本站程序。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
该词在既定词表中时是 1。需要保留频次时改用计数特征。