TensorFlow训练网络两种方式

简介: TensorFlow训练网络两种方式

TensorFlow训练网络有两种方式,一种是基于tensor(array),另外一种是迭代器

两种方式区别是:

第一种是要加载全部数据形成一个tensor,然后调用model.fit()然后指定参数batch_size进行将所有数据进行分批训练

第二种是自己先将数据分批形成一个迭代器,然后遍历这个迭代器,分别训练每个批次的数据

方式一:通过迭代器

IMAGE_SIZE = 1000
# step1:加载数据集
(train_images, train_labels), (val_images, val_labels) = tf.keras.datasets.mnist.load_data()
# step2:将图像归一化
train_images, val_images = train_images / 255.0, val_images / 255.0
# step3:设置训练集大小
train_images = train_images[:IMAGE_SIZE]
val_images = val_images[:IMAGE_SIZE]
train_labels = train_labels[:IMAGE_SIZE]
val_labels = val_labels[:IMAGE_SIZE]
# step4:将图像的维度变为(IMAGE_SIZE,28,28,1)
train_images = tf.expand_dims(train_images, axis=3)
val_images = tf.expand_dims(val_images, axis=3)
# step5:将图像的尺寸变为(32,32)
train_images = tf.image.resize(train_images, [32, 32])
val_images = tf.image.resize(val_images, [32, 32])
# step6:将数据变为迭代器
train_loader = tf.data.Dataset.from_tensor_slices((train_images, train_labels)).batch(32)
val_loader = tf.data.Dataset.from_tensor_slices((val_images, val_labels)).batch(IMAGE_SIZE)
# step5:导入模型
model = LeNet5()
# 让模型知道输入数据的形式
model.build(input_shape=(1, 32, 32, 1))
# 结局Output Shape为 multiple
model.call(Input(shape=(32, 32, 1)))
# step6:编译模型
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
# 权重保存路径
checkpoint_path = "./weight/cp.ckpt"
# 回调函数,用户保存权重
save_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                   save_best_only=True,
                                                   save_weights_only=True,
                                                   monitor='val_loss',
                                                   verbose=0)
EPOCHS = 11
for epoch in range(1, EPOCHS):
    # 每个批次训练集误差
    train_epoch_loss_avg = tf.keras.metrics.Mean()
    # 每个批次训练集精度
    train_epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
    # 每个批次验证集误差
    val_epoch_loss_avg = tf.keras.metrics.Mean()
    # 每个批次验证集精度
    val_epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
    for x, y in train_loader:
        history = model.fit(x,
                            y,
                            validation_data=val_loader,
                            callbacks=[save_callback],
                            verbose=0)
        # 更新误差,保留上次
        train_epoch_loss_avg.update_state(history.history['loss'][0])
        # 更新精度,保留上次
        train_epoch_accuracy.update_state(y, model(x, training=True))
        val_epoch_loss_avg.update_state(history.history['val_loss'][0])
        val_epoch_accuracy.update_state(next(iter(val_loader))[1], model(next(iter(val_loader))[0], training=True))
    # 使用.result()计算每个批次的误差和精度结果
    print("Epoch {:d}: trainLoss: {:.3f}, trainAccuracy: {:.3%} valLoss: {:.3f}, valAccuracy: {:.3%}".format(epoch,

方式二:适用model.fit()进行分批训练

import model_sequential
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# step2:将图像归一化
train_images, test_images = train_images / 255.0, test_images / 255.0
# step3:将图像的维度变为(60000,28,28,1)
train_images = tf.expand_dims(train_images, axis=3)
test_images = tf.expand_dims(test_images, axis=3)
# step4:将图像尺寸改为(60000,32,32,1)
train_images = tf.image.resize(train_images, [32, 32])
test_images = tf.image.resize(test_images, [32, 32])
# step5:导入模型
# history = LeNet5()
history = model_sequential.LeNet()
# 让模型知道输入数据的形式
history.build(input_shape=(1, 32, 32, 1))
# history(tf.zeros([1, 32, 32, 1]))
# 结局Output Shape为 multiple
history.call(Input(shape=(32, 32, 1)))
history.summary()
# step6:编译模型
history.compile(optimizer='adam',
                loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=['accuracy'])
# 权重保存路径
checkpoint_path = "./weight/cp.ckpt"
# 回调函数,用户保存权重
save_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                   save_best_only=True,
                                                   save_weights_only=True,
                                                   monitor='val_loss',
                                                   verbose=1)
# step7:训练模型
history = history.fit(train_images,
                      train_labels,
                      epochs=10,
                      batch_size=32,
                      validation_data=(test_images, test_labels),
                      callbacks=[save_callback])


目录
相关文章
|
21天前
|
机器学习/深度学习 TensorFlow 算法框架/工具
PYTHON TENSORFLOW 2二维卷积神经网络CNN对图像物体识别混淆矩阵评估|数据分享
PYTHON TENSORFLOW 2二维卷积神经网络CNN对图像物体识别混淆矩阵评估|数据分享
|
4天前
|
机器学习/深度学习 算法 TensorFlow
Python深度学习基于Tensorflow(6)神经网络基础
Python深度学习基于Tensorflow(6)神经网络基础
16 2
Python深度学习基于Tensorflow(6)神经网络基础
|
13天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
|
14天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python中TensorFlow的长短期记忆神经网络(LSTM)、指数移动平均法预测股票市场和可视化
Python中TensorFlow的长短期记忆神经网络(LSTM)、指数移动平均法预测股票市场和可视化
|
15天前
|
机器学习/深度学习 算法 TensorFlow
TensorFlow 2keras开发深度学习模型实例:多层感知器(MLP),卷积神经网络(CNN)和递归神经网络(RNN)
TensorFlow 2keras开发深度学习模型实例:多层感知器(MLP),卷积神经网络(CNN)和递归神经网络(RNN)
|
17天前
|
机器学习/深度学习 PyTorch TensorFlow
TensorFlow、Keras 和 Python 构建神经网络分析鸢尾花iris数据集|代码数据分享
TensorFlow、Keras 和 Python 构建神经网络分析鸢尾花iris数据集|代码数据分享
|
20天前
|
机器学习/深度学习 自然语言处理 TensorFlow
Python TensorFlow循环神经网络RNN-LSTM神经网络预测股票市场价格时间序列和MSE评估准确性
Python TensorFlow循环神经网络RNN-LSTM神经网络预测股票市场价格时间序列和MSE评估准确性
|
24天前
|
机器学习/深度学习 大数据 TensorFlow
使用TensorFlow实现Python简版神经网络模型
使用TensorFlow实现Python简版神经网络模型
|
26天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python中TensorFlow的长短期记忆神经网络(LSTM)、指数移动平均法预测股票市场和可视化2
Python中TensorFlow的长短期记忆神经网络(LSTM)、指数移动平均法预测股票市场和可视化
|
26天前
|
机器学习/深度学习 数据可视化 TensorFlow
Python中TensorFlow的长短期记忆神经网络(LSTM)、指数移动平均法预测股票市场和可视化1
Python中TensorFlow的长短期记忆神经网络(LSTM)、指数移动平均法预测股票市场和可视化