keras神经网络模型加载fashion_mnist数据、训练、保存与恢复

目录

加载fashion_mnist数据集

定义简单模型方法

实例化模型并喂入数据

测试模型准确性

 

在训练期间保存模型(以 checkpoints 形式保存)

重置模型并加载最新的 checkpoint

 

保存整个模型

加载恢复模型


加载fashion_mnist数据集

  • fashion_mnist数据集包括:训练集60000张图片,测试集10000张图片
  • fashion_mnist = keras.datasets.fashion_mnist
    
    # 读取train,test数据集
    (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

      如果本地无fashion_mnist数据集,会下载数据集,并保存到C:\Users\.keras\datasets\fashion-mnist文件夹中。读取文件,并直接将图片和标签读取到train_images, train_labels,test_images, test_labels中。

定义简单模型方法

  • # 定义一个简单的序列模型
    def create_model():
        model = tf.keras.models.Sequential([
            keras.layers.Dense(units=512, activation='relu', input_shape=(784,)),
            keras.layers.Dropout(0.2),
            keras.layers.Dense(units=10, activation='softmax')
        ])
    
        model.compile(optimizer='adam',
                      loss='sparse_categorical_crossentropy',
                      metrics=['accuracy'])
    
        return model

 Dense :全连接层  相当于添加一个层,

units:输出的维度大小,改变inputs的最后一维。

activation:激活函数,即神经网络的非线性变化。

input_shape: 输入数据的维度

 

参考:tf.layers.dense()的用法https://blog.csdn.net/yangfengling1023/article/details/81774580

实例化模型并喂入数据


# 创建一个基本的模型实例
model = create_model()
# 将训练集数据喂入模型
model.fit(train_images, train_labels, epochs=10)

fit()将数据喂入神经网络。

x:输入数据。如果模型只有一个输入,那么x的类型是numpyarray,如果模型有多个输入,那么x的类型应当为list,list的元素是对应于各个输入的numpy array.

y:标签,numpy array

batch_size:整数,指定进行梯度下降时每个batch包含的样本数。训练时一个batch的样本会被计算一次梯度下降,使目标函数优化一步。默认值为32

epochs:整数,训练终止时的epoch值,训练将在达到该epoch值时停止,当没有设置initial_epoch时,它就是训练的总轮数,否则训练的总轮数为epochs - inital_epoch

verbose:日志显示,0为不在标准输出流输出日志信息,1为输出进度条记录,2为每个epoch输出一行记录

callbacks:list,其中的元素是keras.callbacks.Callback的对象。这个list中的回调函数将会在训练过程中的适当时机被调用,参考回调函数

 

参考:fit函数https://blog.csdn.net/a1111h/article/details/82148497

 

测试模型准确性

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print('\nTest accuracy:', test_acc)

 

 

在训练期间保存模型(以 checkpoints 形式保存)

# 在文件名中包含 epoch (使用 `str.format`)
checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# 创建一个回调,每 5 个 epochs 保存模型的权重
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path, 
    verbose=1, 
    save_weights_only=True,
    period=5)

# 创建一个新的模型实例
model = create_model()

# 使用 `checkpoint_path` 格式保存权重
model.save_weights(checkpoint_path.format(epoch=0))

# 使用新的回调*训练*模型
model.fit(train_images, 
              train_labels,
              epochs=50, 
              callbacks=[cp_callback],
              validation_data=(test_images,test_labels),
              verbose=0)

在调用model.fit()方法时,加入callback回调训练的weight。每五个 epochs 保存一次唯一命名的 checkpoint。

储存路径:项目目录/training_2

重置模型并加载最新的 checkpoint

# 创建一个新的模型实例
model = BaseTool.create_model()
# 加载以前保存的权重
latest = tf.train.latest_checkpoint(checkpoint_dir)
model.load_weights(latest)
# 重新评估模型
loss, acc = model.evaluate(test_images,  test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))

注意:恢复模型的权重时,必须具有与原始模型具有相同网络结构的模型。

保存整个模型

官方文档:保存完整模型会非常有用——您可以在 TensorFlow.js (HDF5, Saved Model) 加载他们,然后在 web 浏览器中训练和运行它们,或者使用 TensorFlow Lite 将它们转换为在移动设备上运行(HDF5, Saved Model)

# 创建一个基本的模型实例
model = BaseTool.create_model()

model.fit(train_images,
          train_labels,
          epochs=10,
          verbose=2)  # 通过回调训练

# Evaluate accuracy 测试集测试模型准确性
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\ntest_acc:', test_acc)
path = "my_model.h5"
# 将整个模型保存为HDF5文件
model.save(path)

关键方法:model.save(path)

加载恢复模型

new_model = keras.models.load_model('my_model.h5')
# 重新评估模型
loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))

这项技术可以保存一切:

  • 权重
  • 模型配置(结构)
  • 优化器配置

Keras 通过检查网络结构来保存模型。目前,它无法保存 Tensorflow 优化器(调用自 tf.train)。使用这些的时候,您需要在加载后重新编译模型,否则您将失去优化器的状态。

 

 

通过 saved_model 保存

 

tf.keras.experimental.export_saved_model(model, saved_model_path)

 

new_model = tf.keras.experimental.load_from_saved_model(saved_model_path)

现已废弃。

 参考:https://tensorflow.google.cn/tutorials/keras/save_and_load

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用 TensorFlow Federated 实现Fashion-MNIST联邦学习的示例代码: ``` import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff from tensorflow.keras.datasets import fashion_mnist # Load the Fashion-MNIST dataset (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() # Define the preprocessing function def preprocess(dataset): def batch_format_fn(element): return (tf.reshape(element['pixels'], [-1, 784]), tf.reshape(element['label'], [-1, 1])) return dataset.repeat(NUM_EPOCHS).batch(BATCH_SIZE).map(batch_format_fn) # Define the CNN model def create_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Reshape(input_shape=(784,), target_shape=(28, 28, 1)), tf.keras.layers.Conv2D(32, 5, padding='same', activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Conv2D(64, 5, padding='same', activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) return model # Define the Federated Averaging process iterative_process = tff.learning.build_federated_averaging_process( create_model_fn=create_model, client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02), server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0), use_experimental_simulation_loop=True ) # Create a TFF dataset from the Fashion-MNIST dataset TrainElement = collections.namedtuple('TrainElement', 'pixels label') train_data = [] for i in range(len(x_train)): train_data.append(TrainElement(x_train[i], y_train[i])) train_dataset = tf.data.Dataset.from_generator(lambda: train_data, output_types=(tf.uint8, tf.uint8)) preprocessed_train_dataset = preprocess(train_dataset) # Define the hyperparameters BATCH_SIZE = 100 NUM_CLIENTS = 10 NUM_EPOCHS = 5 SHUFFLE_BUFFER = 500 # Simulate the Federated Averaging process def sample_clients(dataset, num_clients): client_ids = np.random.choice(range(len(dataset)), num_clients, replace=False) return [dataset[i] for i in client_ids] def evaluate(iterative_process, preprocessed_test_dataset): model = create_model() tff.learning.assign_weights_to_keras_model(model, iterative_process.get_model_weights()) keras_model = tff.learning.from_keras_model( model, input_spec=preprocessed_test_dataset.element_spec, loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()] ) return keras_model.evaluate(preprocessed_test_dataset) state = iterative_process.initialize() for epoch in range(NUM_EPOCHS): sampled_clients = sample_clients(preprocessed_train_dataset, NUM_CLIENTS) federated_data = [sampled_clients[i:i+5] for i in range(0, len(sampled_clients), 5)] state, metrics = iterative_process.next(state, federated_data) print(f'Epoch {epoch + 1}, loss={metrics.loss}, accuracy={metrics.sparse_categorical_accuracy}') test_element = collections.namedtuple('TestElement', 'pixels label') test_data = [] for i in range(len(x_test)): test_data.append(test_element(x_test[i], y_test[i])) test_dataset = tf.data.Dataset.from_generator(lambda: test_data, output_types=(tf.uint8, tf.uint8)) preprocessed_test_dataset = preprocess(test_dataset) test_metrics = evaluate(iterative_process, preprocessed_test_dataset) print('Test accuracy:', test_metrics.sparse_categorical_accuracy) ``` 这个代码实现了基于TensorFlow Federated的Fashion-MNIST联邦学习。它使用卷积神经网络Fashion-MNIST图像进行类,使用FedAvg算法在多个客户端之间进行全局模型训练。代码包括以下步骤: 1. 加载Fashion-MNIST数据集,预处理数据并定义CNN模型。 2. 定义FedAvg算法的迭代过程,并初始化联邦学习状态。 3. 使用sample_clients()函数随机抽取n个客户端进行本地模型训练。 4. 使用next()函数将本地模型更新发送给服务器并聚合模型权重。 5. 使用evaluate()函数评估模型在测试数据集上的准确率。 6. 在整个训练过程中,迭代NUM_EPOCHS次。 希望这个例子可以帮助你实现Fashion-MNIST联邦学习。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值