TensorFlow.Keras.Model class 详解

Class: tf.keras.Model

tf.keras.Model(
    *args, 
    **kwargs
)

*args:

  • inputs: The input(s) of the model: a keras.Input object or list of keras.Input objects.
  • outputs: The output(s) of the model. See Functional API example below.
  • name: String, the name of the model.

Methods

Model.compile()

Configures the model for training.

设置training参数

compile(
    optimizer='rmsprop',        # [str] define optimizer
    loss=None,                  # [str] define loss type
    metrics=None,               # [list or dict] define evaluation metrics, typically is 'accuracy'
    loss_weights=None,          # [list or dict] define the weights of different losses
    weighted_metrics=None,      # weights of evaluation metrics
    run_eagerly=None,           # [Bool] 
    steps_per_execution=None,   # [int] The number of batches to run during each tf.function call. ?
    jit_compile=None,           # ?
    **kwargs
)

Model.compute_loss()

Compute the total loss, validate it, and return it.

计算loss值

compute_loss(
    x=None,                 # input data
    y=None,                 # target data (label)
    y_pred=None,            # predictions returned by the model
    sample_weight=None      # sample_weight
)

Model.compute_metrics()

Update metric states and collect all metrics to be returned.

更新一次metrics,并返回所有metrics的值 (metrics?)

compute_metrics(
    x, y, y_pred, sample_weight
)

Model.evaluate()

Returns the loss value & metrics values for the model in test mode.

返回loss值和model中metrics的值

evaluate(
    x=None,                     # [npy_array, tensor, dict, tf.data] input
    y=None,                     # [npy_array, tensor, dict, tf.data] target data
    batch_size=None,            # [int] Number of samples per batch of computation [32]
    verbose='auto',             # [0,1,2] 0 = silent, 1 = progress bar, 2 = single line. 进度条
    sample_weight=None,         # sample_weight
    steps=None,                 # Total number of steps (batches of samples) before declaring the evaluation round finished. (needed batches concept)
    callbacks=None,             # ?
    max_queue_size=10,          # [int] Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue.
    workers=1,                  # [int] Used for generator or keras.utils.Sequence input only. Tthreads
    use_multiprocessing=False,  # [Bool] Used for generator or keras.utils.Sequence input only. Use process-based threading.
    return_dict=False,          # [Bool] true=return a dict; false=return a list
    **kwargs
)

Model.fit()

Trains the model for a fixed number of epochs (iterations on a dataset).

训练模型(有限次)

fit(
    x=None,                         #* input data
    y=None,                         #* target data
    batch_size=None,                #* [int] Number of samples per gradient update. (每个循环参与计算的样品数)
    epochs=1,                       #* [int] Number of epochs to train the model. 训练循环次数
    verbose='auto',                 #* [0,1,2] 进度条模式
    callbacks=None,                 # List of keras.callbacks.Callback instances
    validation_split=0.0,           #* [float between 0-1] Fraction of the training data to be used as validation data. 在训练集中划分为validation set的比例。
    validation_data=None,           # override validation_split; 
    shuffle=True,                   #* [Bool] shuffle training data every epoch
    class_weight=None,              # [dict] ?
    sample_weight=None,             # [npy_array]
    initial_epoch=0,                # [int] 从第几个循环开始训练,适合续跑的时候
    steps_per_epoch=None,           # [int or None] ?
    validation_steps=None,          # [int] Only relevant if validation_data is provided and is a tf.data dataset
    validation_batch_size=None,     # [int or None] Number of samples per validation batch.[default=batch_size]
    validation_freq=1,              # [int] Only relevant if validation data is provided. 每几个epoch,validation一次
    max_queue_size=10,              # [int] Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue.
    workers=1,                      # [int] Used for generator or keras.utils.Sequence input only. Tthreads
    use_multiprocessing=False       # [Bool] Used for generator or keras.utils.Sequence input only. Use process-based threading.
)

[Return a History object]

Tips:

  • validation_data:
    Note the fact that the validation loss of data provided using validation_split or validation_data is not affected by regularization layers like noise and dropout.
  • class_weight:
    Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to “pay more attention” to samples from an under-represented class.

Model.get_layer()

Retrieves a layer based on either its name (unique) or index.

依据名称或index返回某一层

get_layer(
    name=None,      # [str] name of layer
    index=None      # [int] index of layer
)

[return layer instance]


Model.get_weight_paths()

Retrieve all the variables and their paths for the model.

返回一个字典,key是variable path, value是tf.Variable instance


Model.load_weights()

Loads all layer weights, either from a TensorFlow or an HDF5 weight file.

从tf或HDF5文件中加载权重

load_weights(
    filepath,               # [str] path to weights file to load
    by_name=False,          # [Bool] load weights by layer name
    skip_mismatch=False, 
    options=None
)

Model.make_predict_function()

Creates a function that executes one step of inference.

自己做一个predict function

make_predict_function(
    force=False
)

[return function]

Tips:

This method is called by Model.predict and Model.predict_on_batch.


Model.make_test_function()

Creates a function that executes one step of evaluation.

自己做一个evaluation function

make_test_function(
    force=False
)

[return function]

Tips:

This method is called by Model.evaluate and Model.test_on_batch.


Model.make_train_function()

Creates a function that executes one step of training.

自己做一个training function

make_train_function(
    force=False
)

[return function]

Tips:

This method is called by Model.fit and Model.train_on_batch.


Model.predict()

Generates output predictions for the input samples.

利用已知模型,生成输入值的预测值

predict(
    x,                          # input data    
    batch_size=None,            # [int] 
    verbose='auto',             # [0,1,2]
    steps=None,                 # [int]
    callbacks=None,             # ?
    max_queue_size=10,          
    workers=1,
    use_multiprocessing=False
)

[return numpy_array]

Tips:

Computation is done in batches. This method is designed for batch processing of large numbers of inputs. It is not intended for use inside of loops that iterate over your data and process small numbers of inputs at a time.

计算分批完成。此方法专为批量处理大量输入而设计。它不适用于迭代数据和一次处理少量输入的循环内部。


Model.predict_on_batch()

Returns predictions for a single batch of samples.

返回单批样本的预测值

predict_on_batch(
    x
)

Model.predict_step()

This method is called by Model.make_predict_function.

predict_step(
    data
)

Model.reset_metrics()

Resets the state of all the metrics in the model.

重置model的所有metrics为0

reset_metrics()

Model.reset_states()

reset_states()

Model.save()

Saves the model to Tensorflow SavedModel or a single HDF5 file.

保存model参数到Tensorflow的SavedModel或者一个HDF5文件

save(
    filepath,                   # [str] h5文件保存路径
    overwrite=True,             # [bool] overwrite existing file or not
    include_optimizer=True,     # [bool] save optimizer state or not
    save_format=None,           # ["tf", "h5"] indicating whether to save the model to Tensorflow SavedModel or HDF5.
    signatures=None,            # only functions (save signatures) with save_format="tf"
    options=None,
    save_traces=True
)

Model.save_spec() ??

save_spec(
    dynamic_batch=True
)

Model.save_weights()

Saves all layer weights.

以h5格式或TensorFlow格式保存所有weights

save_weights(
    filepath,           # [str] file path
    overwrite=True,     # [bool] overwrite or not
    save_format=None,   # ["tf", "h5"]
    options=None
)

Tips:

When saving in HDF5 format, the weight file has:

layer_names (attribute), a list of strings (ordered names of model layers).
For every layer, a group named layer.name
For every such layer group, a group attribute weight_names, a list of strings (ordered names of weights tensor of the layer).
For every weight in the layer, a dataset storing the weight value, named after the weight tensor.


Model.summary()

Prints a string summary of the network.

输出network的summary

summary(
    line_length=None,       # 每行长度,以适应不同显示器的大小
    positions=None,         # default [.33, .55, .67, 1.]
    print_fn=None,          # Print function to use. Defaults to `print`
    expand_nested=False,    # 是否展开嵌套的network
    show_trainable=False,   # 是否显示layer is trainable
    layer_range=None        # [start_layer_name, end_layer_name] 起始的层名和结束的层名,表示会print出来的层范围(both inclusive)
)

Model.test_on_batch()

test_on_batch(
    x,                      # input data
    y=None,                 # target data
    sample_weight=None,     # 
    reset_metrics=True,     # [bool] 
    return_dict=False
)

[return test_loss]


Model.test_step()

test_step(
    data
)

This method is called by Model.make_test_function.


Model.to_json()

Returns a JSON string containing the network configuration.

返回一个包含nerwork configuration的json文件

to_json(
    **kwargs
)

[return a JSON string]
To load a network from a JSON save file, use keras.models.model_from_json(json_string, custom_objects={}).
可以从JSON文件加载一个network


Model.to_yaml()

Returns a yaml string containing the network configuration.

返回一个包含nerwork configuration的yaml文件

to_yaml(
    **kwargs
)

[return a yaml str]
To load a network from a yaml save file, use keras.models.model_from_yaml(yaml_string, custom_objects={}).
可以从yaml文件加载一个network


Model.train_on_batch()

Runs a single gradient update on a single batch of data.

用一小部分数据训练一步

train_on_batch(
    x,                      # input data
    y=None,                 # target data
    sample_weight=None,     # sample_weight
    class_weight=None,      
    reset_metrics=True,
    return_dict=False
)

Model.train_step()

train_step(
    data
)

This method is called by Model.make_train_function.



Model.Methods()归纳分类:

  1. Model build and construction:
    • compile
    • fit
    • evaluate
    • predict
    • summary
    • compute_loss
    • compute_metrics
    • train_on_batch
    • test_on_batch
    • predict_on_batch
  2. Model IO:
    • save_weights
    • load_weights
    • save (load_models 在tf.keras.models.load_models)
    • to_json
    • to_yaml
  3. Assisted Methods: (初学者不太重要)
    • get_layer
    • get_weight_paths
    • make_predict_function
    • make_test_function
    • make_train_function
    • reset_metrics
    • reset_states


有问题可以参考官方教程:

https://tensorflow.google.cn/api_docs/python/tf/keras/Model?hl=en

你可能感兴趣的:(机器学习,tensorflow,keras,人工智能,机器学习)