如何将 Tensorflow 与预训练网络(即迁移学习)结合使用来加载数据?
tensorflowserver side programmingprogramming更新于 2025/5/20 1:37:17
Tensorflow 可以与预训练网络(用于迁移学习)结合使用,使用 Keras 包中的 ‘get_file’ 方法加载数据。Google API 保存数据集,可以将其作为参数传递给 ‘get_file’方法下载当前环境中的数据集。
阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?
我们将了解如何借助预训练网络的迁移学习对猫和狗的图像进行分类。
图像分类迁移学习背后的直觉是,如果在大型通用数据集上训练模型,则该模型可有效地用作视觉世界的通用模型。它会学习特征图,这意味着用户不必从头开始在大型数据集上训练大型模型。
阅读更多: 如何预先训练定制模型?
我们使用 Google Colaboratory 运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,并且不需要任何配置,并且可以免费访问 GPU(图形处理单元)。Colaboratory 是在 Jupyter Notebook 之上构建的。
示例
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory
_URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'
path_to_zip = tf.keras.utils.get_file('cats_and_dogs.zip', origin=_URL, extract=True)
PATH = os.path.join(os.path.dirname(path_to_zip), 'cats_and_dogs_filtered')
print("Downloading the data")
train_dir = os.path.join(PATH, 'train')
validation_dir = os.path.join(PATH, 'validation')
BATCH_SIZE = 32
IMG_SIZE = (160, 160)
代码来源 −https://www.tensorflow.org/tutorials/images/transfer_learning
输出
Downloading data from https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip 68608000/68606236 [==============================] - 1s 0us/step Downloading the data
解释
在此数据集中,我们有数千张猫和狗的图像。
它们被下载并从 zip 文件中提取出来。
创建了一个 tf.data.Dataset,用于训练和验证目的。
这是在 tf.keras.preprocessing.image_dataset_from_directory 实用程序的帮助下完成的。
相关文章
打印
下一节:如何使用 Tensorflow 与预训练模型构建训练和验证数据集? ❯❮ 上一节:如何使用 Tensorflow 和 Estimator 查找 titanic 数据集上的 ROC 曲线?

