import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # 设置日志级别为ERROR,以减少警告信息
# 禁用 Gemini 的底层库(gRPC 和 Abseil)在初始化日志警告
os.environ["GRPC_VERBOSITY"] = "ERROR"
os.environ["GLOG_minloglevel"] = "3" # 0: INFO, 1: WARNING, 2: ERROR, 3: FATAL
os.environ["GLOG_minloglevel"] = "true"
import logging
import tensorflow as tf
tf.get_logger().setLevel(logging.ERROR)
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
!export TF_FORCE_GPU_ALLOW_GROWTH=true
from pathlib import Path
temp_dir = Path(".temp")
temp_dir.mkdir(parents=True, exist_ok=True)
# Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
使用 TensorFlow Hub 对电影评论进行文本分类#
在 TensorFlow.org 上查看 | 在 Google Colab 中运行 | 在 GitHub 上查看源代码 | 下载笔记本 | 查看 TF Hub 模型 |
此笔记本(notebook)使用评论文本将影评分为*积极(positive)或消极(nagetive)两类。这是一个二元(binary)*或者二分类问题,一种重要且应用广泛的机器学习问题。
本教程演示了使用 TensorFlow Hub 和 Keras 进行迁移学习的基本应用。
我们将使用包含 Internet Movie Database 中的 50,000 条电影评论文本的 IMDB 数据集。先将这些评论分为两组,其中 25,000 条用于训练,另外 25,000 条用于测试。训练组和测试组是均衡的,也就是说其中包含相等数量的正面评价和负面评价。
此笔记本使用 tf.keras
(一个在 TensorFlow 中用于构建和训练模型的高级 API)和 tensorflow_hub
(一个用于在单行代码中从 TFHub 加载训练模型的库)。有关使用 tf.keras
的更高级的文本分类教程,请参阅 MLCC 文本分类指南。
!pip install --upgrade tensorflow_hub
!pip install --upgrade tensorflow-datasets
Requirement already satisfied: tensorflow_hub in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (0.16.1)
Requirement already satisfied: numpy>=1.12.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow_hub) (1.26.3)
Requirement already satisfied: protobuf>=3.19.6 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow_hub) (4.25.5)
Requirement already satisfied: tf-keras>=2.14.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow_hub) (2.17.0)
Requirement already satisfied: tensorflow<2.18,>=2.17 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tf-keras>=2.14.1->tensorflow_hub) (2.17.0)
Requirement already satisfied: absl-py>=1.0.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (1.4.0)
Requirement already satisfied: astunparse>=1.6.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (1.6.3)
Requirement already satisfied: flatbuffers>=24.3.25 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (24.3.25)
Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.6.0)
Requirement already satisfied: google-pasta>=0.1.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.2.0)
Requirement already satisfied: h5py>=3.10.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.11.0)
Requirement already satisfied: libclang>=13.0.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (18.1.1)
Requirement already satisfied: ml-dtypes<0.5.0,>=0.3.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.4.0)
Requirement already satisfied: opt-einsum>=2.3.2 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.3.0)
Requirement already satisfied: packaging in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (24.1)
Requirement already satisfied: requests<3,>=2.21.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2.32.3)
Requirement already satisfied: setuptools in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (72.1.0)
Requirement already satisfied: six>=1.12.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (1.16.0)
Requirement already satisfied: termcolor>=1.1.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2.4.0)
Requirement already satisfied: typing-extensions>=3.6.6 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (4.12.2)
Requirement already satisfied: wrapt>=1.11.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (1.16.0)
Requirement already satisfied: grpcio<2.0,>=1.24.3 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (1.65.5)
Requirement already satisfied: tensorboard<2.18,>=2.17 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2.17.1)
Requirement already satisfied: keras>=3.2.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.5.0)
Requirement already satisfied: wheel<1.0,>=0.23.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from astunparse>=1.6.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.43.0)
Requirement already satisfied: rich in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from keras>=3.2.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (13.8.0)
Requirement already satisfied: namex in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from keras>=3.2.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.0.8)
Requirement already satisfied: optree in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from keras>=3.2.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.12.1)
Requirement already satisfied: charset-normalizer<4,>=2 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.7)
Requirement already satisfied: urllib3<3,>=1.21.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2.2.2)
Requirement already satisfied: certifi>=2017.4.17 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests<3,>=2.21.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2024.8.30)
Requirement already satisfied: markdown>=2.6.8 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorboard<2.18,>=2.17->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.7)
Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorboard<2.18,>=2.17->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.7.2)
Requirement already satisfied: werkzeug>=1.0.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorboard<2.18,>=2.17->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.0.4)
Requirement already satisfied: MarkupSafe>=2.1.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from werkzeug>=1.0.1->tensorboard<2.18,>=2.17->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2.1.5)
Requirement already satisfied: markdown-it-py>=2.2.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from rich->keras>=3.2.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (3.0.0)
Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from rich->keras>=3.2.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (2.18.0)
Requirement already satisfied: mdurl~=0.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from markdown-it-py>=2.2.0->rich->keras>=3.2.0->tensorflow<2.18,>=2.17->tf-keras>=2.14.1->tensorflow_hub) (0.1.2)
Requirement already satisfied: tensorflow-datasets in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (4.9.6)
Requirement already satisfied: absl-py in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (1.4.0)
Requirement already satisfied: click in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (8.1.7)
Requirement already satisfied: dm-tree in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (0.1.8)
Requirement already satisfied: immutabledict in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (4.2.0)
Requirement already satisfied: numpy in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (1.26.3)
Requirement already satisfied: promise in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (2.3)
Requirement already satisfied: protobuf>=3.20 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (4.25.5)
Requirement already satisfied: psutil in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (6.0.0)
Requirement already satisfied: pyarrow in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (16.1.0)
Requirement already satisfied: requests>=2.19.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (2.32.3)
Requirement already satisfied: simple-parsing in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (0.1.6)
Requirement already satisfied: tensorflow-metadata in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (1.16.1)
Requirement already satisfied: termcolor in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (2.4.0)
Requirement already satisfied: toml in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (0.10.2)
Requirement already satisfied: tqdm in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (4.66.5)
Requirement already satisfied: wrapt in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (1.16.0)
Requirement already satisfied: array-record>=0.5.0 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-datasets) (0.5.1)
Requirement already satisfied: etils>=1.9.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from etils[enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (1.9.4)
Requirement already satisfied: fsspec in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from etils[enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (2024.9.0)
Requirement already satisfied: importlib_resources in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from etils[enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (6.4.5)
Requirement already satisfied: typing_extensions in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from etils[enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (4.12.2)
Requirement already satisfied: zipp in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from etils[enp,epath,epy,etree]>=1.9.1; python_version >= "3.11"->tensorflow-datasets) (3.19.2)
Requirement already satisfied: charset-normalizer<4,>=2 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.7)
Requirement already satisfied: urllib3<3,>=1.21.1 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.2.2)
Requirement already satisfied: certifi>=2017.4.17 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from requests>=2.19.0->tensorflow-datasets) (2024.8.30)
Requirement already satisfied: six in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from promise->tensorflow-datasets) (1.16.0)
Requirement already satisfied: docstring-parser<1.0,>=0.15 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from simple-parsing->tensorflow-datasets) (0.16)
Requirement already satisfied: googleapis-common-protos<2,>=1.56.4 in /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.65.0)
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices("GPU") else "NOT AVAILABLE")
Version: 2.17.0
Eager mode: True
Hub version: 0.16.1
GPU is available
下载 IMDB 数据集#
IMDB 评论或 TensorFlow Datasets 上提供了 IMDB 数据集。以下代码可将 IMDB 数据集下载到您的机器(或 Colab 运行时)上:
# Split the training set into 60% and 40% to end up with 15,000 examples
# for training, 10,000 examples for validation and 25,000 examples for testing.
train_data, validation_data, test_data = tfds.load(
"imdb_reviews",
split=('train[:60%]', 'train[60%:]', 'test'),
data_dir=temp_dir,
as_supervised=True)
Downloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to .temp/imdb_reviews/plain_text/1.0.0...
Dataset imdb_reviews downloaded and prepared to .temp/imdb_reviews/plain_text/1.0.0. Subsequent calls will reuse this data.
探索数据#
我们花一点时间来了解数据的格式。每个样本都是一个代表电影评论的句子和一个相应的标签。句子未经过任何预处理。标签是一个整数值(0 或 1),其中 0 表示负面评价,1 表示正面评价。
我们来打印下前十个样本。
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
train_examples_batch
<tf.Tensor: shape=(10,), dtype=string, numpy=
array([b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it.",
b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.',
b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.',
b'This is the kind of film for a snowy Sunday afternoon when the rest of the world can go ahead with its own business as you descend into a big arm-chair and mellow for a couple of hours. Wonderful performances from Cher and Nicolas Cage (as always) gently row the plot along. There are no rapids to cross, no dangerous waters, just a warm and witty paddle through New York life at its best. A family film in every sense and one that deserves the praise it received.',
b'As others have mentioned, all the women that go nude in this film are mostly absolutely gorgeous. The plot very ably shows the hypocrisy of the female libido. When men are around they want to be pursued, but when no "men" are around, they become the pursuers of a 14 year old boy. And the boy becomes a man really fast (we should all be so lucky at this age!). He then gets up the courage to pursue his true love.',
b"This is a film which should be seen by anybody interested in, effected by, or suffering from an eating disorder. It is an amazingly accurate and sensitive portrayal of bulimia in a teenage girl, its causes and its symptoms. The girl is played by one of the most brilliant young actresses working in cinema today, Alison Lohman, who was later so spectacular in 'Where the Truth Lies'. I would recommend that this film be shown in all schools, as you will never see a better on this subject. Alison Lohman is absolutely outstanding, and one marvels at her ability to convey the anguish of a girl suffering from this compulsive disorder. If barometers tell us the air pressure, Alison Lohman tells us the emotional pressure with the same degree of accuracy. Her emotional range is so precise, each scene could be measured microscopically for its gradations of trauma, on a scale of rising hysteria and desperation which reaches unbearable intensity. Mare Winningham is the perfect choice to play her mother, and does so with immense sympathy and a range of emotions just as finely tuned as Lohman's. Together, they make a pair of sensitive emotional oscillators vibrating in resonance with one another. This film is really an astonishing achievement, and director Katt Shea should be proud of it. The only reason for not seeing it is if you are not interested in people. But even if you like nature films best, this is after all animal behaviour at the sharp edge. Bulimia is an extreme version of how a tormented soul can destroy her own body in a frenzy of despair. And if we don't sympathise with people suffering from the depths of despair, then we are dead inside.",
b'Okay, you have:<br /><br />Penelope Keith as Miss Herringbone-Tweed, B.B.E. (Backbone of England.) She\'s killed off in the first scene - that\'s right, folks; this show has no backbone!<br /><br />Peter O\'Toole as Ol\' Colonel Cricket from The First War and now the emblazered Lord of the Manor.<br /><br />Joanna Lumley as the ensweatered Lady of the Manor, 20 years younger than the colonel and 20 years past her own prime but still glamourous (Brit spelling, not mine) enough to have a toy-boy on the side. It\'s alright, they have Col. Cricket\'s full knowledge and consent (they guy even comes \'round for Christmas!) Still, she\'s considerate of the colonel enough to have said toy-boy her own age (what a gal!)<br /><br />David McCallum as said toy-boy, equally as pointlessly glamourous as his squeeze. Pilcher couldn\'t come up with any cover for him within the story, so she gave him a hush-hush job at the Circus.<br /><br />and finally:<br /><br />Susan Hampshire as Miss Polonia Teacups, Venerable Headmistress of the Venerable Girls\' Boarding-School, serving tea in her office with a dash of deep, poignant advice for life in the outside world just before graduation. Her best bit of advice: "I\'ve only been to Nancherrow (the local Stately Home of England) once. I thought it was very beautiful but, somehow, not part of the real world." Well, we can\'t say they didn\'t warn us.<br /><br />Ah, Susan - time was, your character would have been running the whole show. They don\'t write \'em like that any more. Our loss, not yours.<br /><br />So - with a cast and setting like this, you have the re-makings of "Brideshead Revisited," right?<br /><br />Wrong! They took these 1-dimensional supporting roles because they paid so well. After all, acting is one of the oldest temp-jobs there is (YOU name another!)<br /><br />First warning sign: lots and lots of backlighting. They get around it by shooting outdoors - "hey, it\'s just the sunlight!"<br /><br />Second warning sign: Leading Lady cries a lot. When not crying, her eyes are moist. That\'s the law of romance novels: Leading Lady is "dewy-eyed."<br /><br />Henceforth, Leading Lady shall be known as L.L.<br /><br />Third warning sign: L.L. actually has stars in her eyes when she\'s in love. Still, I\'ll give Emily Mortimer an award just for having to act with that spotlight in her eyes (I wonder . did they use contacts?)<br /><br />And lastly, fourth warning sign: no on-screen female character is "Mrs." She\'s either "Miss" or "Lady."<br /><br />When all was said and done, I still couldn\'t tell you who was pursuing whom and why. I couldn\'t even tell you what was said and done.<br /><br />To sum up: they all live through World War II without anything happening to them at all.<br /><br />OK, at the end, L.L. finds she\'s lost her parents to the Japanese prison camps and baby sis comes home catatonic. Meanwhile (there\'s always a "meanwhile,") some young guy L.L. had a crush on (when, I don\'t know) comes home from some wartime tough spot and is found living on the street by Lady of the Manor (must be some street if SHE\'s going to find him there.) Both war casualties are whisked away to recover at Nancherrow (SOMEBODY has to be "whisked away" SOMEWHERE in these romance stories!)<br /><br />Great drama.',
b'The film is based on a genuine 1950s novel.<br /><br />Journalist Colin McInnes wrote a set of three "London novels": "Absolute Beginners", "City of Spades" and "Mr Love and Justice". I have read all three. The first two are excellent. The last, perhaps an experiment that did not come off. But McInnes\'s work is highly acclaimed; and rightly so. This musical is the novelist\'s ultimate nightmare - to see the fruits of one\'s mind being turned into a glitzy, badly-acted, soporific one-dimensional apology of a film that says it captures the spirit of 1950s London, and does nothing of the sort.<br /><br />Thank goodness Colin McInnes wasn\'t alive to witness it.',
b'I really love the sexy action and sci-fi films of the sixties and its because of the actress\'s that appeared in them. They found the sexiest women to be in these films and it didn\'t matter if they could act (Remember "Candy"?). The reason I was disappointed by this film was because it wasn\'t nostalgic enough. The story here has a European sci-fi film called "Dragonfly" being made and the director is fired. So the producers decide to let a young aspiring filmmaker (Jeremy Davies) to complete the picture. They\'re is one real beautiful woman in the film who plays Dragonfly but she\'s barely in it. Film is written and directed by Roman Coppola who uses some of his fathers exploits from his early days and puts it into the script. I wish the film could have been an homage to those early films. They could have lots of cameos by actors who appeared in them. There is one actor in this film who was popular from the sixties and its John Phillip Law (Barbarella). Gerard Depardieu, Giancarlo Giannini and Dean Stockwell appear as well. I guess I\'m going to have to continue waiting for a director to make a good homage to the films of the sixties. If any are reading this, "Make it as sexy as you can"! I\'ll be waiting!',
b'Sure, this one isn\'t really a blockbuster, nor does it target such a position. "Dieter" is the first name of a quite popular German musician, who is either loved or hated for his kind of acting and thats exactly what this movie is about. It is based on the autobiography "Dieter Bohlen" wrote a few years ago but isn\'t meant to be accurate on that. The movie is filled with some sexual offensive content (at least for American standard) which is either amusing (not for the other "actors" of course) or dumb - it depends on your individual kind of humor or on you being a "Bohlen"-Fan or not. Technically speaking there isn\'t much to criticize. Speaking of me I find this movie to be an OK-movie.'],
dtype=object)>
我们再打印下前十个标签。
train_labels_batch
<tf.Tensor: shape=(10,), dtype=int64, numpy=array([0, 0, 0, 1, 1, 1, 0, 0, 0, 0])>
构建模型#
神经网络由堆叠的层创建而成,这需要从三个主要方面来进行体系结构决策:
如何表示文本?
在模型中使用多少个层?
为每个层使用多少个隐藏单元?
本示例中,输入数据由句子组成。预测的标签为 0 或 1。
表示文本的一种方式是将句子转换为嵌入向量。使用一个预训练文本嵌入向量作为首层,这样做有三个优点:
不必担心文本预处理
可以从迁移学习中受益
嵌入向量具有固定大小,更易于处理
在本示例中,您使用来自 TensorFlow Hub 的 预训练文本嵌入向量模型,名称为 google/nnlm-en-dim50/2。
本教程中还可以使用来自 TFHub 的许多其他预训练文本嵌入向量:
google/nnlm-en-dim128/2 - 基于与 google/nnlm-en-dim50/2 相同的数据并使用相同的 NNLM 架构进行训练,但具有更大的嵌入向量维度。更大维度的嵌入向量可以改进您的任务,但可能需要更长的时间来训练您的模型。
google/nnlm-en-dim128-with-normalization/2 - 与 google/nnlm-en-dim128/2 相同,但具有额外的文本归一化,例如移除标点符号。如果您的任务中的文本包含附加字符或标点符号,这会有所帮助。
google/universal-sentence-encoder/4 - 一个可产生 512 维嵌入向量的大得多的模型,使用深度平均网络 (DAN) 编码器训练。
还有很多!在 TFHub 上查找更多文本嵌入向量模型。
让我们首先创建一个使用 Tensorflow Hub 模型嵌入(embed)语句的Keras层,并在几个输入样本中进行尝试。请注意无论输入文本的长度如何,嵌入(embeddings)输出的形状都是:(num_examples, embedding_dimension)
。
embedding = "https://tfhub.dev/google/nnlm-en-dim50/2"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])
<tf.Tensor: shape=(3, 50), dtype=float32, numpy=
array([[ 0.5423194 , -0.01190171, 0.06337537, 0.0686297 , -0.16776839,
-0.10581177, 0.168653 , -0.04998823, -0.31148052, 0.07910344,
0.15442258, 0.01488661, 0.03930155, 0.19772716, -0.12215477,
-0.04120982, -0.27041087, -0.21922147, 0.26517656, -0.80739075,
0.25833526, -0.31004202, 0.2868321 , 0.19433866, -0.29036498,
0.0386285 , -0.78444123, -0.04793238, 0.41102988, -0.36388886,
-0.58034706, 0.30269453, 0.36308962, -0.15227163, -0.4439151 ,
0.19462997, 0.19528405, 0.05666233, 0.2890704 , -0.28468323,
-0.00531206, 0.0571938 , -0.3201319 , -0.04418665, -0.08550781,
-0.55847436, -0.2333639 , -0.20782956, -0.03543065, -0.17533456],
[ 0.56338924, -0.12339553, -0.10862677, 0.7753425 , -0.07667087,
-0.15752274, 0.01872334, -0.08169781, -0.3521876 , 0.46373403,
-0.08492758, 0.07166861, -0.00670818, 0.12686071, -0.19326551,
-0.5262643 , -0.32958236, 0.14394784, 0.09043556, -0.54175544,
0.02468163, -0.15456744, 0.68333143, 0.09068333, -0.45327246,
0.23180094, -0.8615696 , 0.3448039 , 0.12838459, -0.58759046,
-0.40712303, 0.23061076, 0.48426905, -0.2712814 , -0.5380918 ,
0.47016335, 0.2257274 , -0.00830665, 0.28462422, -0.30498496,
0.04400366, 0.25025868, 0.14867125, 0.4071703 , -0.15422425,
-0.06878027, -0.40825695, -0.31492147, 0.09283663, -0.20183429],
[ 0.7456156 , 0.21256858, 0.1440033 , 0.52338624, 0.11032254,
0.00902788, -0.36678016, -0.08938274, -0.24165548, 0.33384597,
-0.111946 , -0.01460045, -0.00716449, 0.19562715, 0.00685217,
-0.24886714, -0.42796353, 0.1862 , -0.05241097, -0.664625 ,
0.13449019, -0.22205493, 0.08633009, 0.43685383, 0.2972681 ,
0.36140728, -0.71968895, 0.05291242, -0.1431612 , -0.15733941,
-0.15056324, -0.05988007, -0.08178931, -0.15569413, -0.09303784,
-0.18971168, 0.0762079 , -0.02541647, -0.27134502, -0.3392682 ,
-0.10296471, -0.27275252, -0.34078008, 0.20083308, -0.26644838,
0.00655449, -0.05141485, -0.04261916, -0.4541363 , 0.20023566]],
dtype=float32)>
现在让我们构建完整模型:
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))
model.summary()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[13], line 8
6 model = keras.Sequential()
7 model.add(hub_layer)
----> 8 model.add(tf.keras.layers.Dense(16, activation='relu'))
9 model.add(tf.keras.layers.Dense(1))
11 model.summary()
File /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages/tensorflow/python/trackable/base.py:204, in no_automatic_dependency_tracking.<locals>._method_wrapper(self, *args, **kwargs)
202 self._self_setattr_tracking = False # pylint: disable=protected-access
203 try:
--> 204 result = method(self, *args, **kwargs)
205 finally:
206 self._self_setattr_tracking = previous_value # pylint: disable=protected-access
File /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages/tf_keras/src/utils/traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
67 filtered_tb = _process_traceback_frames(e.__traceback__)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
File /media/pc/data/lxw/envs/anaconda3x/envs/xxx/lib/python3.12/site-packages/tf_keras/src/engine/sequential.py:177, in Sequential.add(self, layer)
175 layer = functional.ModuleWrapper(layer)
176 else:
--> 177 raise TypeError(
178 "The added layer must be an instance of class Layer. "
179 f"Received: layer={layer} of type {type(layer)}."
180 )
182 tf_utils.assert_no_legacy_layers([layer])
183 if not self._is_layer_name_unique(layer):
TypeError: The added layer must be an instance of class Layer. Received: layer=<Dense name=dense, built=False> of type <class 'keras.src.layers.core.dense.Dense'>.
层按顺序堆叠以构建分类器:
第一层是 TensorFlow Hub 层。该层使用预训练的 SavedModel 将句子映射到其嵌入向量。您使用的预训练文本嵌入向量模型 (google/nnlm-en-dim50/2) 可将句子拆分为词例,嵌入每个词例,然后组合嵌入向量。生成的维度是:
(num_examples, embedding_dimension)
。对于此 NNLM 模型,embedding_dimension
为 50。该定长输出向量通过一个有 16 个隐层单元的全连接层(
Dense
)进行管道传输。最后一层与单个输出结点紧密相连。
我们来编译模型。
损失函数与优化器#
一个模型需要一个损失函数和一个优化器来训练。由于这是一个二元分类问题,且模型输出 logits(具有线性激活的单一单元层),因此,我们将使用 binary_crossentropy
损失函数。
这并非损失函数的唯一选择,例如,您还可以选择 mean_squared_error
。但是,一般来说,binary_crossentropy
更适合处理概率问题,它可以测量概率分布之间的“距离”,或者在我们的用例中,是指真实分布与预测值之间的差距。
稍后,当您探索回归问题(例如,预测房屋价格)时,您将看到如何使用另一个称为均方误差的损失函数。
现在,配置模型来使用优化器和损失函数:
model.compile(optimizer='adam',
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
训练模型#
使用包含 512 个样本的 mini-batch 对模型进行 10 个周期的训练,也就是在 x_train
和 y_train
张量中对所有样本进行 10 次迭代。在训练时,监测模型在验证集的 10,000 个样本上的损失和准确率:
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=10,
validation_data=validation_data.batch(512),
verbose=1)
评估模型#
我们来看一下模型的性能如何。将返回两个值。损失值(一个表示误差的数字,值越低越好)与准确率。
results = model.evaluate(test_data.batch(512), verbose=2)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
这种相当简单的方法可以达到约 87% 的准确率。使用更高级的方法,模型的准确率应该会接近 95%。
延伸阅读#
有关处理字符串输入的更通用方式以及对训练过程中准确率和损失进度的更详细分析,请参阅使用预处理文本的文本分类教程。
尝试更多使用来自 TFHub 的训练模型的文本相关教程。