使用策略¶
Flower allows full customization of the learning process through the Strategy
abstraction. A number of built-in strategies are provided in the core framework.
有三种方法可以自定义 Flower 在服务器端协调学习过程的方式:
Use an existing strategy, for example,
FedAvg
使用回调函数定制现有策略
实施新策略
使用现有策略¶
Flower 内置了许多流行的联邦学习策略。内置策略的实例化方法如下:
import flwr as fl
strategy = fl.server.strategy.FedAvg()
fl.server.start_server(config=fl.server.ServerConfig(num_rounds=3), strategy=strategy)
This creates a strategy with all parameters left at their default values and passes it
to the start_server
function. It is usually recommended to adjust a few parameters
during instantiation:
import flwr as fl
strategy = fl.server.strategy.FedAvg(
fraction_fit=0.1, # Sample 10% of available clients for the next round
min_fit_clients=10, # Minimum number of clients to be sampled for the next round
min_available_clients=80, # Minimum number of clients that need to be connected to the server before a training round can start
)
fl.server.start_server(config=fl.server.ServerConfig(num_rounds=3), strategy=strategy)
使用回调函数定制现有策略¶
现有的策略提供了多种自定义行为的方法。回调函数允许策略在执行过程中调用用户提供的代码。
配置客户匹配和客户评估¶
The server can pass new configuration values to the client each round by providing a
function to on_fit_config_fn
. The provided function will be called by the strategy
and must return a dictionary of configuration key values pairs that will be sent to the
client. It must return a dictionary of arbitrary configuration values client.fit
and
client.evaluate
functions during each round of federated learning.
import flwr as fl
def get_on_fit_config_fn() -> Callable[[int], Dict[str, str]]:
"""Return a function which returns training configurations."""
def fit_config(server_round: int) -> Dict[str, str]:
"""Return a configuration with static batch size and (local) epochs."""
config = {
"learning_rate": str(0.001),
"batch_size": str(32),
}
return config
return fit_config
strategy = fl.server.strategy.FedAvg(
fraction_fit=0.1,
min_fit_clients=10,
min_available_clients=80,
on_fit_config_fn=get_on_fit_config_fn(),
)
fl.server.start_server(config=fl.server.ServerConfig(num_rounds=3), strategy=strategy)
The on_fit_config_fn
can be used to pass arbitrary configuration values from server
to client, and potentially change these values each round, for example, to adjust the
learning rate. The client will receive the dictionary returned by the
on_fit_config_fn
in its own client.fit()
function.
Similar to on_fit_config_fn
, there is also on_evaluate_config_fn
to customize
the configuration sent to client.evaluate()
配置服务器端评估¶
Server-side evaluation can be enabled by passing an evaluation function to
evaluate_fn
.
实施新策略¶
编写完全自定义的策略涉及的内容较多,但灵活性最高。阅读 `实施策略 <how-to-implement-strategies.html>_ 指南,了解更多信息。