基于keras的fashion_mnist的卷积神经网络(CNN)

本文介绍了如何使用keras处理fashion_mnist数据集,该数据集由10个类别的7万张商品图片组成,与MNIST格式相同。文章详细讲解了代码实现过程,包括数据加载和CNN模型的构建,并提醒读者fashion_mnist数据集已经是二进制类矩阵,不需要额外转换。最后给出了实验结果。
摘要由CSDN通过智能技术生成

首先我们先介绍一个什么是fashion_mnist数据集。
FashionMNIST 是一个替代 MNIST 手写数字集的图像数据集。 它是由 Zalando(一家德国的时尚科技公司)旗下的研究部门提供。其涵盖了来自 10 种类别的共 7 万个不同商品的正面图片。
FashionMNIST 的大小、格式和训练集/测试集划分与原始的 MNIST 完全一致。60000/10000 的训练测试数据划分,28x28 的灰度图片。你可以直接用它来测试你的机器学习和深度学习算法性能,且不需要改动任何的代码。
类别如下:

标注编号 描述
0 T-shirt/top(T恤)
1 Trouser(裤子)
2 Pullover(套衫)
3 Dress(裙子)
4 Coat(外套)
5 Sandal(凉鞋)
6 Shirt(汗衫)
7 Sneaker(运动鞋)
8 Bag(包)
9 Ankle boot(踝靴)

数据集下载:https://github.com/zalandoresearch/fashion-mnist
这样我们就可以直接模仿mnist_cnn去做了。

下面就是代码详解:

代码中需要注意的点就是这里我是已经下载了fashion_mnist数据集,所以我这里没有利用类似mnist中load_data()这个函数,而是直接从自己下载的文件夹中读取,具体代码如下:


from tensorflow.examples.tutorials.mnist import input_data  
MNIST_data_folder = "C:\\Users
好的,以下是使用 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联邦学习。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值