Tensorflow的妙用:模型「拿來即用」

向大家推薦一個 TensorFlow 工具———TensorFlow Hub,它包含各種預訓練模型的綜合程式碼庫,這些模型稍作調整便可部署到任何設備上。只需幾行程式碼即可重複使用經過訓練的模型,例如 BERT 和 Faster R-CNN。

用TensorFlow Hub實現一些牛X的應用,簡直和把大象裝進冰箱一樣簡單。

第一步:安裝 TensorFlow Hub

Tensorflow_hub 庫可與 TensorFlow 一起安裝(建議直接上TF2),

pip install "tensorflow>=2.0.0"
pip install --upgrade tensorflow-hub

使用時

import tensorflow as tf
import tensorflow_hub as hub

第二步:從 TF Hub 下載模型

TensorFlow Hub 在 hub.tensorflow.google.cn(或//tfhub.dev) 中提供了一個開放的訓練模型存儲庫。tensorflow_hub 庫可以從這個存儲庫和其他基於 HTTP 的機器學習模型存儲庫中載入模型。

從 下載並解壓縮模型後,tensorflow_hub 庫會將這些模型快取到文件系統上。下載位置默認為本地臨時目錄,但可以通過設置環境變數 TFHUB_CACHE_DIR(推薦)或傳遞命令行標記 --tfhub_cache_dir 進行自定義。

os.environ['TFHUB_CACHE_DIR'] = '/home/user/workspace/tf_cache'

值得注意的是,TensorFlow Hub Module僅為我們提供了包含模型體系結構的圖形以及在某些數據集上訓練的權重。大多數模組允許訪問模型的內部層,可以根據不同的用例使用。但是,有些模組不能精細調整。在開始開發之前,建議在TensorFlow Hub網站中查看有關該模組的說明。

以目標檢測為例:動幾下滑鼠。。。
//hub.tensorflow.google.cn/

拿來直接用

module_handle = "//hub.tensorflow.google.cn/google/faster_rcnn/openimages_v4/inception_resnet_v2/1" 
detector = hub.load(module_handle).signatures['default']
def load_img(path):
  img = tf.io.read_file(path)
  img = tf.image.decode_jpeg(img, channels=3)
  return img
def run_detector(detector, path):
  img = load_img(path)

  converted_img  = tf.image.convert_image_dtype(img, tf.float32)[tf.newaxis, ...]
  start_time = time.time()
  result = detector(converted_img)
  end_time = time.time()

  result = {key:value.numpy() for key,value in result.items()}

  print("Found %d objects." % len(result["detection_scores"]))
  print("Inference time: ", end_time-start_time)

  image_with_boxes = draw_boxes(
      img.numpy(), result["detection_boxes"],
      result["detection_class_entities"], result["detection_scores"])

  display_image(image_with_boxes)
run_detector(detector, downloaded_image_path)

無需重複訓練,拿來即用!6不6?

參考

//tensorflow.google.cn/hub/tutorials
//tensorflow.google.cn/hub/tutorials/tf2_arbitrary_image_stylization