当前位置: 首页 > news >正文

tensorflow 图像分类 之一

tensorflow 图像分类 之一

  • 图像分类代码
  • API 说明
    • tf.keras.utils.get_file
    • tf.keras.utils.image_dataset_from_directory

图像分类代码

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import pathlibdef image_classify():# 1. Download and prepare the datasetdataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)data_dir = pathlib.Path(data_dir)print(f"data_dir: {data_dir}")# Create a dataset from the directorybatch_size = 32img_height = 180img_width = 180train_ds = tf.keras.utils.image_dataset_from_directory(data_dir,validation_split=0.2,subset="training",seed=123,image_size=(img_height, img_width),batch_size=batch_size)val_ds = tf.keras.utils.image_dataset_from_directory(data_dir,validation_split=0.2,subset="validation",seed=123,image_size=(img_height, img_width),batch_size=batch_size)class_names = train_ds.class_namesprint(f"Class names: {class_names}")# Configure the dataset for performanceAUTOTUNE = tf.data.AUTOTUNEtrain_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)# 2. Create the modelnum_classes = len(class_names)model = Sequential([layers.Rescaling(1./255, input_shape=(img_height, img_width, 3)),layers.Conv2D(16, 3, padding='same', activation='relu'),layers.MaxPooling2D(),layers.Conv2D(32, 3, padding='same', activation='relu'),layers.MaxPooling2D(),layers.Conv2D(64, 3, padding='same', activation='relu'),layers.MaxPooling2D(),layers.Flatten(),layers.Dense(128, activation='relu'),layers.Dense(num_classes)])# 3. Compile the modelmodel.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])model.summary()# 4. Train the modelepochs = 10history = model.fit(train_ds,validation_data=val_ds,epochs=epochs)# 5. Evaluate and make predictions# You can plot training history or make predictions on new images here.# For example, to predict on a single image:"""sun_flower_path = list(data_dir.glob('sunflowers/*'))[0]img = tf.keras.utils.load_img(sun_flower_path, target_size=(img_height, img_width))img_array = tf.keras.utils.img_to_array(img)img_array = tf.expand_dims(img_array, 0) # Create a batchpredictions = model.predict(img_array)score = tf.nn.softmax(predictions[0])print("This image most likely belongs to {} with a {:.2f} percent confidence.".format(class_names[np.argmax(score)], 100 * np.max(score)))"""if __name__=="__main__":image_classify()
// An highlighted block
var foo = 'bar';

API 说明

tf.keras.utils.get_file

tf.keras.utils.get_file(
fname=None,
origin=None,
untar=False,
md5_hash=None,
file_hash=None,
cache_subdir=‘datasets’,
hash_algorithm=‘auto’,
extract=False,
archive_format=‘auto’,
cache_dir=None,
force_download=False
)

参数意义
fname文件名。如果指定绝对路径,例如“/path/to/file.txt”,则文件将保存在该位置。如果未指定,则使用原始文件名。
origin文件的原始URL。
untar已弃用,请改用 extract 参数。布尔值,表示是否应解压缩文件。
md5_hash已弃用,建议使用 file_hash 参数。用于验证的文件 MD5 哈希值。
file_hash文件下载后预期生成的哈希字符串。支持 sha256 和 md5 两种哈希算法。
cache_subdir文件保存在 Keras 缓存目录下的子目录中。如果指定了绝对路径,例如“/path/to/folder”,则文件将保存在该位置。
hash_algorithm选择用于验证文件的哈希算法。选项包括“md5”、“sha256”和“auto”。默认值“auto”会自动检测当前使用的哈希算法。
extractTrue 尝试将文件提取为归档文件,例如 tar 或 zip。
archive_format要尝试提取文件的归档格式。选项包括“auto”、“tar”、“zip”和“None”。“tar”包含 tar、tar.gz 和 tar.bz 文件。默认值“auto”对应于 [“tar”, “zip”]。None 或空列表将返回未找到匹配项。
cache_dir用于存储缓存文件的位置,如果为 None,则默认为 $KERAS_HOME(如果设置了 KERAS_HOME 环境变量)或 ~/.keras/。
force_download如果为真,则无论缓存状态如何,文件都会始终重新下载。

tf.keras.utils.image_dataset_from_directory

tf.keras.utils.image_dataset_from_directory(
directory,
labels=“inferred”,
label_mode=“int”,
class_names=None,
color_mode=“rgb”,
batch_size=32,
image_size=(256, 256),
shuffle=True,
seed=None,
validation_split=None,
subset=None,
interpolation=“bilinear”,
follow_links=False,
crop_to_aspect_ratio=False,
pad_to_aspect_ratio=False,
data_format=None,
format=“tf”,
verbose=True,
)

参数意义
directory数据所在的目录。如果labels是"inferred",则该目录应包含子目录。每个子目录包含一个类别的图像。否则,目录结构将被忽略。
labels标签可以是"inferred",标签从目录结构生成;None无标签;或整数标签列表/元组,列表/元组的大小与目录中找到的图像文件数量相同。标签应按照图像文件路径的字母数字顺序排序(通过 Python 中的 os.walk(directory) 获取)。
label_mode描述标签编码方式的字符串。选项包括:“int”表示标签编码为整数(例如,用于稀疏分类交叉熵损失函数)。“categorical”表示标签编码为分类向量(例如,用于分类交叉熵损失函数)。“binary”表示标签(最多只能有两个)编码为取值为 0 或 1 的 float32 标量(例如,用于二进制交叉熵损失函数)。None(无标签)。
class_names仅当labels是"inferred"时有效。这是类名的显式列表(必须与子目录名称匹配)。用于控制类的顺序,否则,使用字母数字顺序。
color_mode可以是"grayscale", “rgb”, “rgba”。用于指定图像将转换为1通道、3通道还是4通道图像。默认为“rgb”。
batch_size数据批次的大小。默认为 32。如果为 None,则数据将不会进行批次处理,数据集将生成单个样本。
image_size从磁盘读取图像后,要调整图像大小的目标尺寸,格式为(高度,宽度)。由于流程会处理批量图像,所有图像必须大小相同,因此必须提供此值。默认值为(256,256)。
shuffle是否对数据进行随机排序。默认为 True。如果设置为 False,则按字母数字顺序对数据进行排序。
seed可选的随机种子,用于随机排序和变换。
validation_split可选的浮点数,介于 0 和 1 之间,用于保留验证的数据比例。
subset要返回的数据子集。可以是“training”、“validation”或“both”之一。仅当设置了 validation_split 时才使用。当 subset=“both” 时,该工具返回一个包含两个数据集的元组,分别为训练数据集和验证数据集。
interpolation字符串,用于调整图像大小的插值方法。支持 “bilinear”, “nearest”, “bicubic”, “area”, “lanczos3”, “lanczos5”, “gaussian”, “mitchellcubic”。约定是"bilinear"。
follow_links是否访问符号链接指向的子目录。默认为 False。
crop_to_aspect_ratio如果为 True,则调整图像大小时不会改变宽高比。当原始图像的宽高比与目标宽高比不同时,输出图像将被裁剪,以返回图像中与目标宽高比匹配的最大窗口(大小为 image_size)。默认情况下(crop_to_aspect_ratio=False),宽高比可能无法保持。
pad_to_aspect_ratio如果为 True,则调整图像大小时不会改变宽高比。当原始图像的宽高比与目标宽高比不同时,输出图像将进行填充,以返回图像中与目标宽高比匹配的最大窗口(大小为 image_size)。默认情况下(pad_to_aspect_ratio=False),可能无法保持宽高比。
data_format如果 None 使用 keras.config.image_data_format(),否则使用 ‘channel_last’ 或 ‘channel_first’。
format返回对象的格式。默认为“tf”。可用选项包括:“tf”:返回一个 tf.data.Dataset 对象。需要安装 TensorFlow。“grain”:返回一个 grain.IterDataset 对象。需要安装 Grain。
verbose是否显示类别编号信息和找到的文件数量。默认为 True。
http://www.dtcms.com/a/573874.html

相关文章:

  • 自己网站上做淘宝搜索引擎网站开发属于什么行业
  • 查询网站备案号网站如何做免费的推广
  • 编写一个DXE driver 提供遍历pcie设备配置空间的protocol
  • 随笔之工作方法的“术”
  • 淘宝上做进出口网站有哪些我男同同性做视频网站
  • LLM中的选择性注意:从人类聚焦到模型聚焦
  • 从成本到战略:金仓 KingbaseES 的多维度优势与企业数据库选型的核心考量
  • 做pc网站排wordpress载入慢
  • Java注解在Spring Boot中的详细原理与使用情况解析
  • Python + WebSocket 实现实时体育比分系统(含数据库设计与前端演示)
  • 揭阳智能模板建站网站转应用
  • 多个网站 备案吗工作室网站建设要多大内存
  • 借助 TX Text Control:在 .NET C# 中验证 PDF/UA 文档
  • 高光谱成像系统赋能烟叶分选(烟叶除杂、烟叶霉变、烟叶烟梗区分、烟叶等级分选)
  • Java NIO 深度解析:从 BIO 到 NIO 的演进与实战​
  • 聊聊AIoT开发效率与安全:从ARMINO IDK框架说起
  • 0.5、提示词中 System、User、Assistant 的基本概念
  • 响应式网站设计建设制作温岭app开发公司
  • 门户网站用什么程序做广州手机app开发
  • 用Python和FastAPI构建一个完整的企业级AI Agent微服务脚手架
  • 青岛网站域名备案查询个人网站做哪些内容
  • Leet热题100--208. 实现 Trie (前缀树)--中等
  • 应用分析网站网站社区建设
  • 【上海海事大学主办】第六届智能电网与能源工程国际学术会议(SGEE 2025)
  • 每月网站开发费用网站改版如何做301
  • Will Al Replace Humans? From Stage to Symbiosis.
  • Springcloud核心组件之Sentinel详解
  • 饰品企业网站建设程序开发的步骤
  • 聊城网站建设科技公司网站自己的
  • 计算机视觉·TagCLIP