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()

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

相关推荐
kcuwu.5 分钟前
机器学习入门:线性回归完全指南(含波士顿房价预测案例)
人工智能·机器学习·线性回归
阿豪只会阿巴11 分钟前
【没事学点啥】TurboBlog轻量级个人博客项目——Turbo Blog 项目学习与上线指南
开发语言·python·学习·状态模式
幸运的大号暖贴13 分钟前
解决Vibe Coding时Idea经常不自动git add问题
java·人工智能·git·intellij-idea·claudecode·opencode
MonkeyKing_sunyuhua13 分钟前
什么是服务端 VAD 端点检测
人工智能·语音识别
ascarl201014 分钟前
Linux.do 帖子整理:AI 调用 Chrome DevTools 调试前端页面
linux·前端·人工智能
qxq_sunshine18 分钟前
从 CNN 到 Agent:给 DL 工程师的“智能体”入门黑话指南(概念篇)
人工智能·神经网络·cnn
郝学胜-神的一滴19 分钟前
反向传播:神经网络的「灵魂」修炼法则
人工智能·pytorch·深度学习·神经网络·机器学习·数据挖掘
Tutankaaa25 分钟前
知识竞赛软件SaaS版 vs 本地部署
人工智能·经验分享·笔记·学习
DanCheOo25 分钟前
开源 | 我是怎么用 ai-memory 让 Cursor 每次开新对话都自动知道项目背景的
前端·人工智能·ai·ai编程
丝雨_xrc30 分钟前
AIGC 时代,面向开发者的内容营销正在被重新定义
人工智能