Python 深度学习实战 第3章 Keras和TensorFlowKeras 训练和评估模型实例
Python 深度学习实战 第3章 Keras和TensorFlow&Keras 训练和评估模型实例
内容概要
第3章介绍了Keras和TensorFlow的基本概念及其关系,并指导如何设置深度学习工作区。本章还概述了核心深度学习概念如何转化为Keras和TensorFlow API。通过本章,读者将为实际应用深度学习做好准备。
主要内容
-
TensorFlow简介
- TensorFlow是一个基于Python的开源机器学习平台,由Google开发。
- 它支持自动求导、GPU和TPU加速,并且可以轻松扩展到多台机器。
- TensorFlow不仅是一个库,而是一个平台,包含多个组件,如TF-Agents、TFX、TensorFlow Serving等。
-
Keras简介
- Keras是一个基于Python的深度学习API,构建在TensorFlow之上,提供了方便的接口来定义和训练深度学习模型。
- Keras注重开发者体验,提供一致且简单的流程,减少常见用例所需的操作步骤,并在用户出错时提供清晰的反馈。
-
Keras和TensorFlow的历史
- Keras最初是为研究而开发的,后来与TensorFlow整合,成为其官方高级API。
- Keras和TensorFlow的共生关系使得Keras成为TensorFlow生态系统的重要组成部分。
-
设置深度学习工作区
- 推荐使用现代NVIDIA GPU而不是CPU,以加速深度学习任务。
- 提供了使用Google Colaboratory的免费GPU运行时的选项,适合初学者快速入门。
- 推荐使用Jupyter笔记本作为运行深度学习实验的主要工具。
-
TensorFlow的基本操作
- 介绍了TensorFlow中的张量、变量和张量操作。
- 详细讲解了GradientTape API,用于计算可微分表达式的梯度。
-
Keras的核心API
- 介绍了Keras中的层(Layer)概念,这是神经网络的基本构建块。
- 详细讲解了如何使用Keras构建和训练模型,包括编译模型、训练模型和评估模型。
关键代码和算法
3.5.1 创建张量和变量
import tensorflow as tf
# 创建常量张量
x = tf.ones(shape=(2, 1))
x = tf.zeros(shape=(2, 1))
x = tf.random.normal(shape=(3, 1), mean=0., stddev=1.)
# 创建变量
v = tf.Variable(initial_value=tf.random.normal(shape=(3, 1)))
v.assign(tf.ones((3, 1)))
3.5.2 张量操作
a = tf.ones((2, 2))
b = tf.square(a)
c = tf.sqrt(a)
d = b + c
e = tf.matmul(a, b)
e *= d
3.5.3 使用GradientTape计算梯度
input_var = tf.Variable(initial_value=3.)
with tf.GradientTape() as tape:
result = tf.square(input_var)
gradient = tape.gradient(result, input_var)
input_const = tf.constant(3.)
with tf.GradientTape() as tape:
tape.watch(input_const)
result = tf.square(input_const)
gradient = tape.gradient(result, input_const)
3.5.4 编译模型
from tensorflow import keras
model = keras.Sequential([
keras.layers.Dense(32, activation="relu"),
keras.layers.Dense(10, activation="softmax")
])
model.compile(optimizer=keras.optimizers.RMSprop(learning_rate=1e-4),
loss=keras.losses.SparseCategoricalCrossentropy(),
metrics=[keras.metrics.CategoricalAccuracy()])
3.5.5 训练模型
history = model.fit(
train_images,
train_labels,
epochs=5,
batch_size=128,
validation_data=(val_images, val_labels)
)
3.5.6 评估模型
loss_and_metrics = model.evaluate(test_images, test_labels, batch_size=128)
3.5.7 使用模型进行预测
predictions = model.predict(new_inputs, batch_size=128)
精彩语录
-
中文:Keras是深度学习的Python API,注重开发者体验,提供一致且简单的流程。
英文原文:Keras is a deep learning API for Python, built on top of TensorFlow, that provides a convenient way to define and train any kind of deep learning model.
解释:这句话强调了Keras的设计哲学,即为开发者提供友好的接口。 -
中文:TensorFlow是一个行业级的数值计算框架,可以自动计算任何可微分表达式的梯度。
英文原文:TensorFlow is an industry-strength numerical computing framework that can automatically compute the gradient of any differentiable expression.
解释:这句话总结了TensorFlow的核心功能,即自动求导。 -
中文:深度学习的目标不仅是让模型在训练数据上表现良好,而是让它在新数据上也能表现良好。
英文原文:The goal of machine learning is not to obtain models that perform well on the training data, but to obtain models that perform well in general, and particularly on data points that the model has never encountered before.
解释:这句话强调了深度学习的最终目标,即泛化能力。 -
中文:选择正确的损失函数对于解决问题至关重要。
英文原文:Choosing the right loss function for the right problem is extremely important: your network will take any shortcut it can to minimize the loss.
解释:这句话提醒开发者在选择损失函数时要谨慎,以确保模型的行为符合预期。 -
中文:Keras和TensorFlow的结合使得深度学习变得简单而强大。
英文原文:Keras and TensorFlow have had a symbiotic relationship for many years.
解释:这句话描述了Keras和TensorFlow之间的紧密合作关系,使得深度学习变得更加易于使用。
总结
通过本章的学习,读者将对Keras和TensorFlow的基本概念有一个清晰的理解,并能够设置深度学习工作区。通过实践示例,读者可以掌握如何使用Keras和TensorFlow构建和训练神经网络,并为解决实际问题做好准备。