tf.keras模塊——Input、Model


tf.keras.Input()

  初始化一個keras張量

  tf.keras.Input(   shape=None,   batch_size=None,   name=None,   dtype=None,   sparse=False,   tensor=None,   **kwargs   ) 

 

    參數:
    shape:形狀元組(整數),不包括批量大小。例如,shape=(32,)表示預期輸入將是32維向量的批次。
    batch_size:可選的靜態批處理大小(整數)。
    name:圖層的可選名稱字符串。在模型中應該是唯一的(不要重復使用相同的名稱兩次)。如果沒有提供,它將自動生成。
    dtype:數據類型由輸入預期的,作為字符串(float32,float64,int32...)
    sparse:一個布爾值,指定要創建的占位符是否稀疏。
    tensor:可選的現有張量以包裝到Input圖層中。如果設置,該圖層將不會創建占位符張量。
    **kwargs:不推薦的參數支持。

 

  案例:

 x = Input(shape=(32,)) y = tf.square(x) 

 

 

tf.keras.Model()

  將layers分組為具有訓練和推理特征的對象

  兩種實例化的方式:

  1 - 使用“API”,從開始,鏈接層調用以指定模型的正向傳遞,最后從輸入和輸出創建模型:

 

 import tensorflow as tf inputs = tf.keras.Input(shape=(3,)) x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) model = tf.keras.Model(inputs=inputs, outputs=outputs) 

 

  2 - 通過繼承Model類:在這種情況下,您應該在__init__定義你的layers,並且應該在call函數里實現模型的正向傳遞。

 

  import tensorflow as tf   class MyModel(tf.keras.Model):    def __init__(self):   super(MyModel, self).__init__()   self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)   self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)   def call(self, inputs):   x = self.dense1(inputs)   return self.dense2(x)   model = MyModel() 

  tf.keras.Model.compile():模型編譯

 compile( optimizer,---> ['Adadelta', 'Adagrad', 'Adam', 'Adamax', 'FTRL', 'NAdam', 'optimizer', 'RMSprop', 'SGD'] loss=None, metrics=None, loss_weights=None, sample_weight_mode=None, weighted_metrics=None, target_tensors=None, distribute=None, **kwargs ) 

  參數:

  optimizer: 優化參數,選擇范圍我們已經在上面的代碼塊展示了。

  loss: 

    BinaryCrossentropy:計算真實標簽和預測標簽之間的交叉熵損失。     CategoricalCrossentropy:計算標簽和預測之間的交叉熵損失。     CategoricalHinge:計算y_true和y_pred之間的分類鉸鏈損失。     CosineSimilarity:計算y_true和y_pred之間的余弦相似度。     Hinge:計算y_true和y_pred之間的鉸鏈損耗。     Huber:計算y_true和y_pred之間的Huber損失。     KLDivergence:計算y_true和y_pred之間的Kullback Leibler差異損失。     LogCosh:計算預測誤差的雙曲余弦的對數。     Loss:損失基類。     MeanAbsoluteError:計算標簽和預測之間的絕對差異的平均值。     MeanAbsolutePercentageError:計算y_true和y_pred之間的平均絕對百分比誤差。     MeanSquaredError:計算標簽和預測之間的誤差平方的平均值。     MeanSquaredLogarithmicError:計算y_true和y_pred之間的均方對數誤差。     Poisson:計算y_true和y_pred之間的泊松損失。     Reduction:減少損失的類型。     SparseCategoricalCrossentropy:計算標簽和預測之間的交叉熵損失。     SquaredHinge:計算y_true和y_pred之間的平方鉸鏈損耗。 

 

  metrics: 訓練和測試期間要使用的評估指標。

    1、metrics=['accuracy']     2、多輸出模型的不同輸出指定不同的度量標准:      metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}      metrics=[['accuracy'], ['accuracy', 'mse']]      metrics=['accuracy', ['accuracy', 'mse']] 

  sample_weight_mode如果您需要進行時間步長樣本加權(2D權重),請將

    其設置為"temporal"。 None默認為采樣權重(1D)。如果模型具有多個

    輸出,則可以sample_weight_mode通過傳遞字典或模式列表在每個輸出上

    使用不同的輸出

  weighted_metrics:在訓練和測試期間由sample_weight或class_weight評估和加權的指標列表。

 

  tf.keras.Model.evaluate():模型評估

 

  evaluate(    x=None,    y=None,    batch_size=None,    verbose=1,    sample_weight=None,    steps=None,    callbacks=None,    max_queue_size=10,    workers=1,    use_multiprocessing=False   ) 

  參數:

    x: 測試自變量,可以是Numpy數組或數組列表、TensorFlow張量或張量列表、如果模型

        具有命名輸入,則dict將輸入名稱映射到相應的數組/張量、tf.data數據集或數據

        集的迭代、生成器或keras.utils.Sequence實例。

    y: 目標數據,類型同x一樣。

    batch_size: 每個批量處理的數據量。整數。默認為32。如果你的數據是 symbolic

        tensors, dataset, dataset iterators, generators, or keras.utils.

        Sequence則不需要指定該參數,因為它會生成batchs.

    verbose: 0, 1,默認為1。日志顯示,批量輸出,你可以控制輸出的間隔。

    steps: 整數或None,每輪迭代的步數。如果x是 tf.data dataset or a dataset iterator,

        and steps is None,則數據將會耗盡為止。

    max_queue_size: 默認為10,生成隊列的最大size。

    workers: 進程數。

 

  tf.keras.Model.evaluate_generator():

    在數據生成器上評估模型

 evaluate_generator( generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0 ) 

  

  tf.keras.Model.fit():在數據上擬合模型

 fit( x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False, **kwargs )
 

  參數:
    validation_split: 0,1之間的浮點數。分割部分數據用於驗證,其余用於訓練。當x

          是dataset, dataset iterator, generator or keras.utils.Sequence時該

          參數不可用。
    validation_data:指定驗證集數據:

              (x_val, y_val)、(x_val, y_val, val_sample_weights);
          dataset or a dataset iterator兩種數據對於上面兩種情況要指定

          validation_steps。
    class_weight: 指定權值分配,可以突出重點關注的類別。(對損失函數加權)
    sample_weight: 樣本加權,對損失函數加權,以獲得更好的結果。這里可以是numpy

          數組,必須保障shape是和傳入數據大小一致。應該確保在compile()中

          指定sample_weight_mode=“temporal”,dataset, dataset iterator,

          generator, or keras.utils.Sequence不支持該參數。
    initial_epoch: 整數。開始訓練的epoch(對於恢復以前的訓練運行很有用)。
    steps_per_epoch: 每個epoch的迭代步數。
    validation_steps:
    validation_freq: 指定驗證的epoch,可以為整數或者列表:如:[1,2,10]。

  tf.keras.Model.fit_generator():

  在數據生成器上擬合模型,可以減少內存消耗

 fit_generator( generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0 ) 

     這里傳入的數據必須是生成器(yield),如:

 def generate_arrays_from_file(path): while 1: f = open(path) for line in f: # create numpy arrays of input data # and labels, from each line in the file x1, x2, y = process_line(line) yield ({'input_1': x1, 'input_2': x2}, {'output': y}) f.close() model.fit_generator(generate_arrays_from_file('/my_file.txt'), steps_per_epoch=10000, epochs=10) 

  tf.keras.Model.get_layer():

  獲取圖層:根據其名稱(唯一)或索引檢索圖層

 get_layer( name=None, index=None ) 

  tf.keras.Model.load_weights():

  從TensorFlow或HDF5文件加載所有圖層權重

 load_weights( filepath, by_name=False )

  tf.keras.Model.predict():預測

 predict( x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False )
 
        

    參數:
      x:Numpy數組(或類數組)或數組列表、TensorFlow張量或張量列表、
         數據集或數據集的迭代、生成器或keras.utils.Sequence實例

  tf.keras.Model.predict_generator():

  以生成器傳入數據進行預測

 
        
 predict_generator( generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0 )

  tf.keras.Model.predict_on_batch():

  單批次樣本進行預測

 predict_on_batch(x) 
 
        

  tf.keras.Model.test_on_batch():

  單批次樣本進行測試

 test_on_batch( x, y=None, sample_weight=None, reset_metrics=True ) 

  tf.keras.Model.train_on_batch():

  單批次樣本進行訓練

 train_on_batch( x, y=None, sample_weight=None, class_weight=None, reset_metrics=True )

  tf.keras.Model.reset_metrics():重置指標的狀態

    如果True,返回的指標僅適用於此批次。如果False,指標將在批次之間有狀態地累積。

  tf.keras.Model.reset_states():

  重置狀態,需要連續調用的時候最好使用resets_states()

  tf.keras.Model.save():保存模型

 save( filepath, overwrite=True, include_optimizer=True, save_format=None ) 

   將模型保存到Tensorflow SavedModel或單個HDF5文件。

    保存文件包括:

    1、模型體系結構,允許重新實例化模型。

    2、模型權重。

    3、優化器的狀態,允許您從中斷的位置恢復訓練。

   

     參數:
    filepath: 字符串,模型保存的位置
    overwrite: 是否靜默覆蓋目標位置的現有文件,或者為用戶提供手動提示
    include_optimizer: 如果為True,則將優化器的狀態保存在一起
    save_format: 保存的類型,‘tf’,‘h5’,目前tf已經禁用了(tensorflow2.0中)

 from keras.models import load_model model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' del model # deletes the existing model # returns a compiled model # identical to the previous one model = load_model('my_model.h5') 
 
        

  tf.keras.Model.save_weights():保存所有圖層權重

 save_weights( filepath, overwrite=True, save_format=None )

  tf.keras.Model.summary():打印網絡的字符串摘要

 summary( line_length=None, positions=None, print_fn=None ) 

   參數:

    line_length: 打印行的總長度(例如,將其設置為使顯示適應不同的終端窗口大小)。

    positions: 每行中日志元素的相對或絕對位置。如果未提供,則默認為[.33, .55, .67, 1.]。

    print_fn: 打印功能。默認為print。它將在摘要的每一行上調用。您可以將其設置為自定義函

      數以捕獲字符串摘要。

 

  tf.keras.Model.to_json():

  返回包含網絡配置的JSON字符串

    要從保存文件JSON加載網絡,請使用

       keras.models.model_from_json(json_string, custom_objects={})。

  tf.keras.Model.to_yaml():

  返回包含網絡配置的yaml字符串

    要從yaml保存文件加載網絡,請使用

       keras.models.model_from_yaml(yaml_string, custom_objects={})。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM