Go back to the English version of the documentation创建初始模型
创建初始模型
Last updated: 2024年10月07日
参与方可以通过遵循一组示例在训练之前创建并保存初始模型。
请考虑与模型类型匹配的配置示例。
保存 Tensorflow 模型
import tensorflow as tf
from tensorflow.keras import *
from tensorflow.keras.layers import *
import numpy as np
import os
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10)
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
# Create an instance of the model
model = MyModel()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True)
optimizer = tf.keras.optimizers.Adam()
acc = tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy')
model.compile(optimizer=optimizer, loss=loss_object, metrics=[acc])
img_rows, img_cols = 28, 28
input_shape = (None, img_rows, img_cols, 1)
model.compute_output_shape(input_shape=input_shape)
dir = "./model_architecture"
if not os.path.exists(dir):
os.makedirs(dir)
model.save(dir)
如果选择 Tensorflow 作为模型框架,那么需要将 Keras 模型保存为 SavedModel
格式。 可以使用 tf.keras.model.save()
以 SavedModel
格式保存 Keras 模型。
要压缩文件,请运行命令 zip -r mymodel.zip model_architecture
。 .zip
文件的内容必须包含:
mymodel.zip
└── model_architecture
├── assets
├── keras_metadata.pb
├── saved_model.pb
└── variables
├── variables.data-00000-of-00001
└── variables.index
保存 Scikit-learn 模型
SKLearn 分类
# SKLearn classification
from sklearn.linear_model import SGDClassifier
import numpy as np
import joblib
model = SGDClassifier(loss='log', penalty='l2')
model.classes_ = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# You must specify the class label for IBM Federated Learning using model.classes. Class labels must be contained in a numpy array.
# In the example, there are 10 classes.
joblib.dump(model, "./model_architecture.pickle")
SKLearn 回归
# Sklearn regression
from sklearn.linear_model import SGDRegressor
import pickle
model = SGDRegressor(loss='huber', penalty='l2')
with open("./model_architecture.pickle", 'wb') as f:
pickle.dump(model, f)
SKLearn Kmeans
# SKLearn Kmeans
from sklearn.cluster import KMeans
import joblib
model = KMeans()
joblib.dump(model, "./model_architecture.pickle")
您需要通过运行命令 zip mymodel.zip model_architecture.pickle
来创建包含选取格式的模型的 .zip
文件。 .zip
文件的内容必须包含:
mymodel.zip
└── model_architecture.pickle
保存 PyTorch 模型
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Flatten(start_dim=1, end_dim=-1),
nn.Linear(in_features=784, out_features=256, bias=True),
nn.ReLU(),
nn.Linear(in_features=256, out_features=256, bias=True),
nn.ReLU(),
nn.Linear(in_features=256, out_features=256, bias=True),
nn.ReLU(),
nn.Linear(in_features=256, out_features=100, bias=True),
nn.ReLU(),
nn.Linear(in_features=100, out_features=50, bias=True),
nn.ReLU(),
nn.Linear(in_features=50, out_features=10, bias=True),
nn.LogSoftmax(dim=1),
).double()
torch.save(model, "./model_architecture.pt")
您需要创建包含选取格式的模型的 .zip
文件。 运行命令 zip mymodel.zip model_architecture.pt
。 .zip
文件的内容应包含:
mymodel.zip
└── model_architecture.pt