Tensorflow2 如何扩展现有数据集(缩放、随机旋转、水平翻转、平移等),从而提高模型的准确率 -- Tensorflow自学笔记14

实际生活中的数据集,往往不是标准的数据,而是有倾斜角度、有旋转、有偏移的数据,为了提高数据集的真实性,提高模型预测的准确率,可以用ImageDataGenerator函数来扩展数据集

复制代码
import tensorflow as tf

from tensorflow.keras.preprocessing.image import ImageDataGenerator

image_gen_train = ImageDataGenerator(

          rescale=1./255, #原像素值 0~255 归至 0~1 
          rotation_range=45, #随机 45 度旋转
          width_shift_range=.15, #随机宽度偏移 [-0.15,0.15)
          height_shift_range=.15,#随机高度偏移 [-0.15,0.15)
          horizontal_flip=True,#随机水平翻转
          zoom_range=0.5 #随机缩放到 [1-50%,1+50%]

MNIST数据集增强

复制代码
import tensorflow as tf

from tensorflow.keras.preprocessing.image import ImageDataGenerator



mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train, x_test = x_train / 255.0, x_test / 255.0

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) # 数据增强函数的输入要求是 4 维,通过 reshape 调整,给数据增加一个维度,从(60000, 28, 28)reshape为(60000, 28, 28, 1)



image_gen_train = ImageDataGenerator(

rescale=1. / 1., # 如为图像,分母为255时,可归至0~1

rotation_range=45, # 随机45度旋转

width_shift_range=.15, # 宽度偏移

height_shift_range=.15, # 高度偏移

horizontal_flip=False, # 水平翻转

zoom_range=0.5 # 将图像随机缩放阈量50%

)

image_gen_train.fit(x_train)



model = tf.keras.models.Sequential([

tf.keras.layers.Flatten(),

tf.keras.layers.Dense(128, activation='relu'),

tf.keras.layers.Dense(10, activation='softmax')

])



model.compile(optimizer='adam',

loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),

metrics=['sparse_categorical_accuracy'])



model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test),

validation_freq=1)

model.summary()

数据增强后,图片对比,发现,有的旋转了,有的放大了,有的旋转了。

相关推荐
xian_wwq5 分钟前
【学习笔记】「大模型安全:攻击面演化史」第 07 篇-安全左移
人工智能·笔记·学习
马拉AI21 分钟前
我把科研人用AI的水平,分成了5个阶段
人工智能
武子康24 分钟前
调查研究-164-NVIDIA DGX Station for Windows 解析:不是新显卡,而是企业本地 AI 超算
人工智能·openai
AndrewHZ30 分钟前
【LLM技术全景】预训练与微调:大模型如何“学习“
人工智能·深度学习·大模型·llm·微调·预训练·rlhf
audyxiao00131 分钟前
ICLR 2026论文分享 | WorldGym:用世界模型打造机器人策略评估新范式
大数据·人工智能·大模型·智能体·世界模型
泠不丁34 分钟前
用 Obsidian 双链笔记管理智能家居技术知识体系
人工智能
泠不丁34 分钟前
智能家居 Zigbee 协议在高并发传感数据时的丢包率实测
人工智能
螺丝钉code35 分钟前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
武子康1 小时前
调查研究-163-MiniMax M3 正式发布:1M 上下文、多模态、Coding Agent 与 Sparse Attention 到底意味着什么?
人工智能·openai
Cosolar1 小时前
LlamaIndex 文档解析与分块策略深度解析
人工智能·面试·架构