如何使用TensorFlow Hub和代碼示例


內容已失效,使用教程可見TensorflowHub官網      

任何深度學習框架,為了獲得成功,必須提供一系列最先進的模型,以及在流行和廣泛接受的數據集上訓練的權重,即與訓練模型。

      TensorFlow現在已經提出了一個更好的框架,稱為TensorFlow Hub,它非常易於使用且組織良好。使用TensorFlow Hub,您可以通過幾行代碼導入大型和流行的模型,自信地執行廣泛使用的傳輸學習活動。TensorFlow Hub非常靈活,可以托管您的模型以供其他用戶使用。TensorFlow Hub中的這些模型稱為模塊。在本文中,讓我們看看如何使用TensorFlow Hub模塊的基礎知識,它是各種類型和代碼示例。

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

前置知識

      接下來,讓我們看一些可用於了解TensorFlow Hub模塊更多細節的重要方面和功能。

1)模塊實例化:由TensorFlow Hub網站托管用於不同目的(圖像分類,文本嵌入等)的不同模型(Inception,ResNet,ElMo等)組成的各種模塊。用戶必須瀏覽模塊目錄,然后在完成其目的和模型后,需要復制托管模型的URL。然后,用戶可以像這樣實例化他的模塊:

import tensorflow_hub as hub

module = hub.Module(<<Module URL as string>>, trainable=True)

除了URL參數,另一個最值得注意的參數是'trainable'。如果用戶希望微調/修改模型的權重,則必須將此參數設置為True 。

2)簽名:模塊的簽名指定了每個模塊的作用。如果未明確提及簽名,則所有模塊都帶有“默認”簽名並使用它。對於大多數模塊,當使用“默認”簽名時,模型的內部層將從用戶中抽象出來。用於列出模塊的所有簽名名稱的函數是get_signature_names()。

import tensorflow_hub as hub

module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
print(module.get_signature_names())
# ['default', 'image_classification', 'image_feature_vector']
3)預期輸入:每個模塊都有一組預期輸入,具體取決於所使用模塊的簽名。雖然大多數模塊都記錄了TensorFlow Hub網站中的預期輸入集(特別是“默認”簽名),但有些模塊沒有。在這種情況下,使用get_input_info_dict()更容易獲得預期輸入及其大小和數據類型。
import tensorflow_hub as hub

module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
print(module.get_input_info_dict())   # When no signature is given, considers it as 'default'
# {'images': <hub.ParsedTensorInfo shape=(?, 299, 299, 3) dtype=float32 is_sparse=False>}

print(module.get_input_info_dict(signature='image_feature_vector'))
# {'images': <hub.ParsedTensorInfo shape=(?, 299, 299, 3) dtype=float32 is_sparse=False>}

4)預期輸出:為了在構建TensorFlow Hub模型之后構建圖的剩余部分,有必要知道預期的輸出類型。get_output_info_dict()函數用於此目的。請注意,對於“默認”簽名,通常只有一個輸出,但是當您使用非默認簽名時,圖表的多個圖層將向您公開。

import tensorflow_hub as hub

module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
print(module.get_output_info_dict())  # When no signature is given, considers it as 'default'
# {'default': <hub.ParsedTensorInfo shape=(?, 1001) dtype=float32 is_sparse=False>}

print(module.get_output_info_dict(signature='image_classification'))
# {'InceptionV3/global_pool': <hub.ParsedTensorInfo shape=(?, 1, 1, 2048) dtype=float32 is_sparse=False>,
# 'InceptionV3/Logits': <hub.ParsedTensorInfo shape=(?, 1001) dtype=float32 is_sparse=False>,
#  'InceptionV3/Conv2d_2b_3x3': <hub.ParsedTensorInfo shape=(?, 147, 147, 64) dtype=float32 is_sparse=False>
# ..... Several other exposed layers...... }

5)收集所需的模塊層:實例化模塊后,必須從模塊中提取所需的層/輸出並將其添加到圖形中。以下是一些方法:

import tensorflow as tf
import tensorflow_hub as hub

images = tf.placeholder(tf.float32, (None, 299, 299, 3))

module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
logits1 = module(dict(images=images))    # implies default signature
print(logits1)
# Tensor("module_apply_default/InceptionV3/Logits/SpatialSqueeze:0", shape=(?, 1001), dtype=float32)

module_features = module(dict(images=images), signature='image_classification', as_dict=True)
# module_features stores all layers in key-value pairs
logits2 = module_features['InceptionV3/Logits']
print(logits2)
# Tensor("module_apply_image_classification/InceptionV3/Logits/SpatialSqueeze:0", shape=(?, 1001), dtype=float32)

global_pool = module_features['InceptionV3/global_pool']
print(global_pool)
# Tensor("module_apply_image_classification/InceptionV3/Logits/GlobalPool:0", shape=(?, 1, 1, 2048), dtype=float32)
6)初始化TensorFlow Hub操作:模塊中存在的所有操作的結果輸出權重/值由TensorFlow Hub以表格格式托管。這需要使用tf.tables_initializer()以及常規變量的初始化來初始化。代碼塊如下所示:
import tensorflow as tf

with tf.Session() as sess:
    sess.run([tf.tables_initializer(), <<other initializers>>])

代碼骨架

      一旦構建了包含模塊,學習算法優化器,目標函數,自定義層等的完整圖形,這就是代碼的圖形部分的框架。

 1 import tensorflow as tf
 2 import tensorflow_hub as hub
 3 
 4 << Create Placeholders >>
 5 << Create Dataset and Iterators >>
 6 
 7 module1 = hub.Module(<< Module URL >>)
 8 logits1 = module1(<< input_dict >>)
 9 
10 module2 = hub.Module(<< Module URL >>)
11 module2_features = module2(<< input_dict >>, signature='default', as_dict=True)
12 logits2 = module2_features['default']
13 
14 << Remaining graph, learning algorithms, objective function, etc >>
15 
16 with tf.Session() as sess:
17     sess.run([tf.tables_initializer(), << other initializers >>])
18 
19     << Remaining training pipeline >>

      我正在使用兩個模塊。第一個模塊使用最小的代碼構建,隱式使用默認簽名和層。在第二個模塊中,我明確指定了默認簽名和圖層。以類似的方式,我們可以指定非默認簽名和圖層。

      現在我們已經研究了如何在圖中集成模塊,讓我們在撰寫本文時研究TensorFlow Hub中存在的各種類型的模塊。(模塊將在TensorFlow Hub中不斷添加/更新)在每個示例中,我已將其與Dataset和Iterator管道集成,並與Saved_Model一起保存。(您可以通過代碼示例查看我關於Dataset和Iterator使用情況的 詳細帖子

1)圖像分類模塊

      顧名思義,這些模塊集用於圖像分類。在這類模塊中,給出了完整的網絡架構。這包括用於分類的最終密集連接層。在這個類別的代碼示例中,我將使用Inception V3模塊將Kaggle的貓狗分類問題分類為1001個ImageNet類。

import tensorflow as tf
import tensorflow_hub as hub

from Dataset import Dataset

tf.reset_default_graph()
dataset = Dataset()

module = hub.Module('https://tfhub.dev/google/imagenet/inception_v3/classification/1')
logits = module(dict(images=dataset.img_data))

softmax = tf.nn.softmax(logits)
top_predictions = tf.nn.top_k(softmax, top_k, name='top_predictions')

2)特征向量模塊

      這與圖像分類模塊非常相似,唯一的區別是模塊不包括最終的密集分類層。在這個類別的代碼示例中,我將針對Hackerearth的多標簽動物屬性分類問題微調Resnet-50模塊。 在微調操作期間,除了定制附加的密集層之外,通常還需要優化模塊的最終層。在這種情況下,您必須找到要微調的范圍或變量的名稱。我附加了代碼的相關部分以在特征向量模塊中執行此類過程。

 1 module = hub.Module('https://tfhub.dev/google/imagenet/resnet_v2_50/feature_vector/1',
 2                     trainable=True)   # Trainable is True since we are going to fine-tune the model
 3 module_features = module(dict(images=dataset.image_data), signature="image_feature_vector",
 4                          as_dict=True)
 5 features = module_features["default"]
 6 
 7 with tf.variable_scope('CustomLayer'):
 8     weight = tf.get_variable('weights', initializer=tf.truncated_normal((2048, n_class)))
 9     bias = tf.get_variable('bias', initializer=tf.ones((n_class)))
10     logits = tf.nn.xw_plus_b(features, weight, bias)
11 
12 # Find out the names of all variables present in graph
13 print(tf.all_variables())
14 
15 # After finding the names of variables or scope, gather the variables you wish to fine-tune
16 var_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='CustomLayer')
17 var_list2 = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='module/resnet_v2_50/block4')
18 var_list.extend(var_list2)
19 
20 # Pass this set of variables into your optimiser
21 optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss, var_list=var_list)

      如果模塊圖中的節點沒有直觀命名(非常不可能的情況),則必須弄清楚模塊的體系結構,然后將它們映射到正在打印的節點。
在代碼示例中,我已經調整了最后幾層變量屬於'resnet_v2_50 / block4'的變量范圍。通過10個時期的訓練,你可以毫不費力地獲得這個問題的F1分數0.95819。

3)視頻分類模塊

      視頻分類是指對視頻片段中發生的活動的性質進行分類。在代碼示例中,我已經在Inception 3D模塊上訓練了包含27個類的20BN-Jester數據集再說一次,只有3個訓練時期,我的准確率達到了91.45%。模塊代碼的相關部分如下所示。

import tensorflow as tf
import tensorflow_hub as hub

from Dataset import Dataset
dataset = Dataset()

module = hub.Module("https://tfhub.dev/deepmind/i3d-kinetics-400/1", trainable=True)
features = module(dict(rgb_input=dataset.image_data))

n_class = 27
with tf.variable_scope('CustomLayer'):
    weight = tf.get_variable('weights',
                             initializer=tf.truncated_normal((400, n_class)))
    bias = tf.get_variable('bias', initializer=tf.ones((n_class)))
    logits = tf.nn.xw_plus_b(features, weight, bias)

 為了測試模型的准確性,我構建了一個簡單的實時視頻分類應用程序,這里是一個小視頻

4)文本嵌入模型

      TensorFlow Hub提供了多個文本嵌入模塊,不僅包括英語,還包括德語,韓語,日語等其他幾種語言(在撰寫本文時),其中許多都在句子層面而不是在單詞層面生成嵌入。在代碼示例中,我參與了 Kaggle對電影評論的情緒分析。使用 ELMO嵌入模塊,我使用分別在句子級別和單詞級別生成的嵌入來訓練網絡。該網絡由單層雙向LSTM組成。在句子層面,經過6個時期的訓練后,達到的准確率為65%。附加模塊代碼的相關部分。
 1 module = hub.Module('https://tfhub.dev/google/elmo/2', trainable=True)
 2 embeddings = module(dict(text=dataset.text_data))
 3 embeddings = tf.expand_dims(embeddings, axis=1)
 4 
 5 with tf.variable_scope('Layer1'):
 6     cell_fw1 = tf.nn.rnn_cell.LSTMCell(num_units=128, state_is_tuple=True)
 7     cell_bw1 = tf.nn.rnn_cell.LSTMCell(num_units=128, state_is_tuple=True)
 8 
 9     outputs1, states1 = tf.nn.bidirectional_dynamic_rnn(
10         cell_fw=cell_fw1,
11         cell_bw=cell_bw1,
12         inputs=embeddings)
13 
14 rnn_output = tf.reshape(outputs1[0], (-1, 128))
15 
16 with tf.variable_scope('Layer2'):
17     weight2 = tf.get_variable('weight', initializer=tf.truncated_normal((128, n_class)))
18     bias2 = tf.get_variable('bias', initializer=tf.ones(n_class))
19     logits = tf.nn.xw_plus_b(rnn_output, weight2, bias2)

5)圖像增強模塊

      圖像增強是流水話訓練中的一個重要組成部分,可以提高模型的准確性。所有圖像增強模塊(在編寫本文時)都沒有任何變量,因此,這些模塊不具有可調性/可訓練性。使用'from_decoded_images'的簽名,您可以直接將圖像提供給這些模塊。下面示出了示例代碼塊以及生成的增強圖像。

 1 import tensorflow as tf
 2 import tensorflow_hub as hub
 3 import tensorflow.contrib.image           # Needed for Image Augmentation modules
 4 
 5 from Dataset import Dataset
 6 dataset = Dataset()
 7 
 8 module = hub.Module('https://tfhub.dev/google/image_augmentation/nas_svhn/1')
 9 input_dict = dict(image_size=image_size,       # Output Image size
10                   images=dataset.img_data,     # Has the image in Numpy data format 
11                   augmentation=True)
12 aug_images = module(input_dict, signature='from_decoded_images')

      圖像增強真正的作用體現在圖像分類和特征向量時,在先前訓練的使用特征向量模塊的 多標簽動物屬性分類問題中,我添加了 crop_color圖像增強模塊,並且在相同數量的歷元中,我的F1得分提高到0.96244。在這個代碼示例中,我使用默認簽名,它將期望編碼形式的圖像作為其輸入。現在,當我的圖像增強模塊將輸入圖像調整為固定大小以供 Resnet50模塊進一步處理時,我已經保存了我之前已經完成的顯式調整圖像大小的工作。 
     您還可以查看我之前撰寫的 關於圖像增強的文章,其中涵蓋了基本類型的增強。

6)對象檢測模塊

      對象檢測模塊不支持微調,因此如果您有自己的數據集,則必須從頭開始執行培訓。目前也不支持批量處理數據。在代碼示例中,我將僅使用Inception-ResNet V2模塊上的FasterRCNN對圖像進行推斷。我附上了下面模塊生成的代碼和圖像的模塊部分。

import tensorflow as tf
import tensorflow_hub as hub

from Dataset import Dataset
dataset = Dataset()

module = hub.Module('https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1')
detector = module(dict(images=dataset.image_data), as_dict=True)

class_entities = detector['detection_class_entities']
boxes = detector['detection_boxes']
scores = detector['detection_scores']
class_labels = detector['detection_class_labels']
class_names = detector['detection_class_names']

7)生成器模型

      這些對應於生成性對抗網絡(GAN)。一些模塊沒有暴露其網絡的Discriminator部分。就像對象檢測一樣,即使在代碼示例中,我也只是在進行推理。使用在CelebA數據集上訓練的Progressive GAN模塊,我將生成新面孔。我附上了下面模塊生成的代碼和圖像的模塊部分 。

1 import tensorflow as tf
2 import tensorflow_hub as hub
3 
4 from Dataset import Dataset
5 dataset = Dataset()
6 
7 module = hub.Module("https://tfhub.dev/google/progan-128/1")
8 images = module(dataset.latent_vector_space)

對應的模型在TensorFlow Hub官網也有示例,可以在Colab上復現。例如,目標檢測Colab

 

 

原文鏈接:https://medium.com/ymedialabs-innovation/how-to-use-tensorflow-hub-with-code-examples-9100edec29af


免責聲明!

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



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