save_vars¶
- paddle.fluid.io. save_vars ( executor, dirname, main_program=None, vars=None, predicate=None, filename=None ) [source]
-
- Api_attr
-
Static Graph
This API saves specific variables in the Program to files.
There are two ways to specify the variables to be saved: set variables in a list and assign it to the vars, or use the predicate function to select variables that make predicate(variable) == True. The first way has a higher priority.
The dirname is used to specify the folder where to save variables. If you prefer to save variables in separate files in the dirname folder, do not set filename. If you prefer to save all variables in a single file, use filename to specify it.
- Parameters
-
executor (Executor) – The executor to run for saving variables.
dirname (str, optional) – The folder where to save variables. When you need to save the parameter to the memory, set it to None.
main_program (Program, optional) – The program whose variables will be saved. If it is None, the default main program will be used automatically. Default: None
vars (list[Variable], optional) – The list contains all variables to be saved. Default: None
predicate (function, optional) – The function selects the variables that make predicate(variable) == True. Default: None
filename (str, optional) – If you prefer to save all variables in a single file, use filename to specify it. Otherwise, let filename be None. Default: None
- Returns
-
- When saving parameters to a file, returns None.
-
When saving parameters to memory, returns a binary string containing parameters.
- Return type
-
str
- Raises
-
TypeError – If main_program is not an instance of Program nor None.
Examples
import paddle import paddle.fluid as fluid paddle.enable_static() main_prog = fluid.Program() startup_prog = fluid.Program() with fluid.program_guard(main_prog, startup_prog): data = fluid.layers.data(name="img", shape=[64, 784], append_batch_size=False) w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32', name='fc_w') b = fluid.layers.create_parameter(shape=[200], dtype='float32', name='fc_b') hidden_w = fluid.layers.matmul(x=data, y=w) hidden_b = fluid.layers.elementwise_add(hidden_w, b) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(startup_prog) # The first usage: use `vars` to set the saved variables. var_list = [w, b] path = "./my_paddle_vars" fluid.io.save_vars(executor=exe, dirname=path, vars=var_list, filename="vars_file") # w and b will be save in a file named "var_file". # The second usage: use `predicate` to select the saved variable. def name_has_fc(var): res = "fc" in var.name return res param_path = "./my_paddle_model" fluid.io.save_vars(executor=exe, dirname=param_path, main_program=main_prog, vars=None, predicate = name_has_fc) # all variables whose names contain "fc " are saved.