FATE —— 二.2.2 Homo-NN内置数据集

2023-12-19 11:10
文章标签 数据 内置 2.2 nn fate homo

本文主要是介绍FATE —— 二.2.2 Homo-NN内置数据集,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

在FATE-1.10中,提供了表、nlp_标记器和图像三个数据集,以满足表数据、文本数据和图像数据的基本需求

表数据集

TableDataset在table.py下提供,用于处理csv格式的数据,并将自动从数据中解析id和标签。以下是一些源代码,用于了解此数据集类的用法:

class TableDataset(Dataset):"""A Table Dataset, load data from a give csv path, or transform FATE DTableParameters----------label_col str, name of label column in csv, if None, will automatically take 'y' or 'label' or 'target' as labelfeature_dtype dtype of feature, supports int, long, float, doublelabel_dtype: dtype of label, supports int, long, float, doublelabel_shape: list or tuple, the shape of labelflatten_label: bool, flatten extracted label column or not, default is False"""def __init__(self,label_col=None,feature_dtype='float',label_dtype='float',label_shape=None,flatten_label=False):

标记器数据集

TokenizerDataset是在nlp_tokenizer.py下提供的,它是基于Transformer的BertTokenizer开发的,它可以从csv中读取字符串,同时自动分割文本并将其转换为单词id。

class TokenizerDataset(Dataset):"""A Dataset for some basic NLP Tasks, this dataset will automatically transform raw text into word indicesusing BertTokenizer from transformers library,see https://huggingface.co/docs/transformers/model_doc/bert?highlight=berttokenizer for details of BertTokenizerParameters----------truncation bool, truncate word sequence to 'text_max_length'text_max_length int, max length of word sequencestokenizer_name_or_path str, name of bert tokenizer(see transformers official for details) or path to localtransformer tokenizer folderreturn_label bool, return label or not, this option is for host dataset, when running hetero-NN"""def __init__(self, truncation=True, text_max_length=128,tokenizer_name_or_path="bert-base-uncased",return_label=True):

图像数据集

ImageDataset在image.py下提供,用于简单处理图像数据。它是基于torchvision的ImageFolder开发的。可以看出,使用了该数据集的参数:

class ImageDataset(Dataset):"""A basic Image Dataset built on pytorch ImageFolder, supports simple image transformGiven a folder path, ImageDataset will load images from this folder, images in thisfolder need to be organized in a Torch-ImageFolder format, seehttps://pytorch.org/vision/main/generated/torchvision.datasets.ImageFolder.html for details.Image name will be automatically taken as the sample id.Parameters----------center_crop : bool, use center crop transformercenter_crop_shape: tuple or listgenerate_id_from_file_name: bool, whether to take image name as sample idfile_suffix: str, default is '.jpg', if generate_id_from_file_name is True, will remove this suffix from file name,result will be the sample idreturn_label: bool, return label or not, this option is for host dataset, when running hetero-NNfloat64: bool, returned image tensors will be transformed to double precisionlabel_dtype: str, long, float, or double, the dtype of return label"""def __init__(self, center_crop=False, center_crop_shape=None,generate_id_from_file_name=True, file_suffix='.jpg',return_label=True, float64=False, label_dtype='long'):

使用内置数据集

使用FATE的内置数据集与使用用户自定义数据集完全相同。在这里,我们使用我们的图像数据集和一个具有对流层的新模型来再次解决MNIST手写识别任务,作为示例。

如果您没有MNIST数据集,可以参考前面的教程并下载:Homo-NN自定义数据集

from federatedml.nn.dataset.image import ImageDataset
dataset = ImageDataset()
dataset.load('/mnt/hgfs/mnist/')  # 根据自己得文件位置进行调整
from torch import nn
import torch as t
from torch.nn import functional as F
from pipeline.component.nn.backend.torch.operation import Flatten# a new model with conv layer, it can work with our ImageDataset
model = t.nn.Sequential(nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5),nn.MaxPool2d(kernel_size=3),nn.Conv2d(in_channels=12, out_channels=12, kernel_size=3),nn.AvgPool2d(kernel_size=3),Flatten(start_dim=1),nn.Linear(48, 32),nn.ReLU(),nn.Linear(32, 10),nn.Softmax(dim=1))

本地测试

在本地测试的情况下,将跳过所有联合过程,并且模型将不执行fed平均
from federatedml.nn.homo.trainer.fedavg_trainer import FedAVGTrainer
trainer = FedAVGTrainer(epochs=5, batch_size=256, shuffle=True, data_loader_worker=8, pin_memory=False) # 参数
trainer.set_model(model)
trainer.local_mode() 
optimizer = t.optim.Adam(model.parameters(), lr=0.01)
loss = t.nn.CrossEntropyLoss()
trainer.train(train_set=dataset,optimizer=optimizer, loss=loss)

它可以工作,现在可以执行联合任务了

具有内置数据集的Homo NN任务

import torch as t
from torch import nn
from pipeline import fate_torch_hook
from pipeline.component import HomoNN
from pipeline.backend.pipeline import PipeLine
from pipeline.component import Reader, Evaluation, DataTransform
from pipeline.interface import Data, Modelt = fate_torch_hook(t)
import os
# bind data path to name & namespace
fate_project_path = os.path.abspath('../')
host = 10000
guest = 9999
arbiter = 10000
pipeline = PipeLine().set_initiator(role='guest', party_id=guest).set_roles(guest=guest, host=host,arbiter=arbiter)data_0 = {"name": "mnist_guest", "namespace": "experiment"}
data_1 = {"name": "mnist_host", "namespace": "experiment"}
# 这里需要根据自己得版本作出调整,否则文件参数上传失败会报错
data_path_0 = fate_project_path + '/examples/data/mnist_train'
data_path_1 = fate_project_path + '/examples/data/mnist_train'
pipeline.bind_table(name=data_0['name'], namespace=data_0['namespace'], path=data_path_0)
pipeline.bind_table(name=data_1['name'], namespace=data_1['namespace'], path=data_path_1)

{'namespace': 'experiment', 'table_name': 'mnist_host'}

# 定义reader
reader_0 = Reader(name="reader_0")
reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=data_0)
reader_0.get_party_instance(role='host', party_id=host).component_param(table=data_1)
from pipeline.component.homo_nn import DatasetParam, TrainerParam # a new model with conv layer, it can work with our ImageDataset
model = t.nn.Sequential(nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5),nn.MaxPool2d(kernel_size=3),nn.Conv2d(in_channels=12, out_channels=12, kernel_size=3),nn.AvgPool2d(kernel_size=3),Flatten(start_dim=1),nn.Linear(48, 32),nn.ReLU(),nn.Linear(32, 10),nn.Softmax(dim=1))nn_component = HomoNN(name='nn_0',model=model, # modelloss=t.nn.CrossEntropyLoss(),  # lossoptimizer=t.optim.Adam(model.parameters(), lr=0.01), # optimizerdataset=DatasetParam(dataset_name='image', label_dtype='long'),  # datasettrainer=TrainerParam(trainer_name='fedavg_trainer', epochs=2, batch_size=1024, validation_freqs=1),torch_seed=100 # random seed)
pipeline.add_component(reader_0)
pipeline.add_component(nn_component, data=Data(train_data=reader_0.output.data))
pipeline.add_component(Evaluation(name='eval_0', eval_type='multi'), data=Data(data=nn_component.output.data))
pipeline.compile()
pipeline.fit()

这篇关于FATE —— 二.2.2 Homo-NN内置数据集的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/weixin_62375097/article/details/128590283
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/511947

相关文章

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro

Nginx添加内置模块过程

《Nginx添加内置模块过程》文章指导如何检查并添加Nginx的with-http_gzip_static模块:确认该模块未默认安装后,需下载同版本源码重新编译,备份替换原有二进制文件,最后重启服务验... 目录1、查看Nginx已编辑的模块2、Nginx官网查看内置模块3、停止Nginx服务4、Nginx

Python实现数据可视化图表生成(适合新手入门)

《Python实现数据可视化图表生成(适合新手入门)》在数据科学和数据分析的新时代,高效、直观的数据可视化工具显得尤为重要,下面:本文主要介绍Python实现数据可视化图表生成的相关资料,文中通过... 目录前言为什么需要数据可视化准备工作基本图表绘制折线图柱状图散点图使用Seaborn创建高级图表箱线图热

MySQL数据脱敏的实现方法

《MySQL数据脱敏的实现方法》本文主要介绍了MySQL数据脱敏的实现方法,包括字符替换、加密等方法,通过工具类和数据库服务整合,确保敏感信息在查询结果中被掩码处理,感兴趣的可以了解一下... 目录一. 数据脱敏的方法二. 字符替换脱敏1. 创建数据脱敏工具类三. 整合到数据库操作1. 创建服务类进行数据库

MySQL中处理数据的并发一致性的实现示例

《MySQL中处理数据的并发一致性的实现示例》在MySQL中处理数据的并发一致性是确保多个用户或应用程序同时访问和修改数据库时,不会导致数据冲突、数据丢失或数据不一致,MySQL通过事务和锁机制来管理... 目录一、事务(Transactions)1. 事务控制语句二、锁(Locks)1. 锁类型2. 锁粒