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

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

相关推荐
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之3 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
DFminer4 小时前
【LLM】fast-api 流式生成测试
人工智能·机器人
lyaihao4 小时前
使用python实现奔跑的线条效果
python·绘图
郄堃Deep Traffic4 小时前
机器学习+城市规划第十四期:利用半参数地理加权回归来实现区域带宽不同的规划任务
人工智能·机器学习·回归·城市规划
ai大师5 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
GIS小天5 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票
小小爬虾5 小时前
关于datetime获取时间的问题
python
阿部多瑞 ABU5 小时前
主流大语言模型安全性测试(三):阿拉伯语越狱提示词下的表现与分析
人工智能·安全·ai·语言模型·安全性测试