如何使用Python編譯Tensorflow模型?


在Tensorflow中建立的模型可以使用`compile`方法進行編譯。損失函式使用`SparseCategoricalCrossentropy`方法計算。

瞭解更多: 什麼是TensorFlow以及Keras如何與TensorFlow一起建立神經網路?

我們使用Google Colaboratory執行以下程式碼。Google Colab或Colaboratory幫助在瀏覽器上執行Python程式碼,無需任何配置,並可免費訪問GPU(圖形處理單元)。Colaboratory構建在Jupyter Notebook之上。

print("The model is being compiled")
model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
   metrics=['accuracy'])
print("The architecture of the model")
model.summary()

程式碼來源:https://www.tensorflow.org/tutorials/images/classification

輸出

The model is being compiled
The architecture of the model
Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #  
=================================================================
rescaling_1 (Rescaling)      (None, 180, 180, 3)       0        
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 180, 180, 16)      448      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 90, 90, 16)        0        
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 90, 90, 32)        4640    
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 45, 45, 32)        0        
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 45, 45, 64)        18496    
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 22, 22, 64)        0        
_________________________________________________________________
flatten_1 (Flatten)          (None, 30976)             0        
_________________________________________________________________
dense_2 (Dense)              (None, 128)               3965056  
_________________________________________________________________
dense_3 (Dense)              (None, 5)                 645      
=================================================================
Total params: 3,989,285
Trainable params: 3,989,285
Non-trainable params: 0
_________________________________________________________________

解釋

  • 使用了`optimizers.Adam`最佳化器和`losses.SparseCategoricalCrossentropy`損失函式。
  • 可以透過傳遞`metrics`引數來檢視每個訓練週期的訓練和驗證準確率。
  • 編譯模型後,可以使用`summary`方法顯示模型架構的摘要。

更新於: 2021年2月20日

204 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告