欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

keras K.function獲取某層的輸出操作

 更新時間:2020年06月29日 08:43:48   作者:脫貧&&脫單&&不脫發(fā)  
這篇文章主要介紹了keras K.function獲取某層的輸出操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

如下所示:

from keras import backend as K
from keras.models import load_model

models = load_model('models.hdf5')
image=r'image.png'
images=cv2.imread(r'image.png')
image_arr = process_image(image, (224, 224, 3))
image_arr = np.expand_dims(image_arr, axis=0)
layer_1 = K.function([base_model.get_input_at(0)], [base_model.get_layer('layer_name').output])
f1 = layer_1([image_arr])[0]

加載訓練好并保存的網(wǎng)絡(luò)模型

加載數(shù)據(jù)(圖像),并將數(shù)據(jù)處理成array形式

指定輸出層

將處理后的數(shù)據(jù)輸入,然后獲取輸出

其中,K.function有兩種不同的寫法:

1. 獲取名為layer_name的層的輸出

layer_1 = K.function([base_model.get_input_at(0)], [base_model.get_layer('layer_name').output]) #指定輸出層的名稱

2. 獲取第n層的輸出

layer_1 = K.function([model.get_input_at(0)], [model.layers[5].output]) #指定輸出層的序號(層號從0開始)

另外,需要注意的是,書寫不規(guī)范會導致報錯:

報錯:

TypeError: inputs to a TensorFlow backend function should be a list or tuple

將該句:

f1 = layer_1(image_arr)[0]

修改為:

f1 = layer_1([image_arr])[0]

補充知識:keras.backend.function()

如下所示:

def function(inputs, outputs, updates=None, **kwargs):
 """Instantiates a Keras function.
 Arguments:
   inputs: List of placeholder tensors.
   outputs: List of output tensors.
   updates: List of update ops.
   **kwargs: Passed to `tf.Session.run`.
 Returns:
   Output values as Numpy arrays.
 Raises:
   ValueError: if invalid kwargs are passed in.
 """
 if kwargs:
  for key in kwargs:
   if (key not in tf_inspect.getargspec(session_module.Session.run)[0] and
     key not in tf_inspect.getargspec(Function.__init__)[0]):
    msg = ('Invalid argument "%s" passed to K.function with Tensorflow '
        'backend') % key
    raise ValueError(msg)
 return Function(inputs, outputs, updates=updates, **kwargs)

這是keras.backend.function()的源碼。其中函數(shù)定義開頭的注釋就是官方文檔對該函數(shù)的解釋。

我們可以發(fā)現(xiàn)function()函數(shù)返回的是一個Function對象。下面是Function類的定義。

class Function(object):
 """Runs a computation graph.
 Arguments:
   inputs: Feed placeholders to the computation graph.
   outputs: Output tensors to fetch.
   updates: Additional update ops to be run at function call.
   name: a name to help users identify what this function does.
 """

 def __init__(self, inputs, outputs, updates=None, name=None,
        **session_kwargs):
  updates = updates or []
  if not isinstance(inputs, (list, tuple)):
   raise TypeError('`inputs` to a TensorFlow backend function '
           'should be a list or tuple.')
  if not isinstance(outputs, (list, tuple)):
   raise TypeError('`outputs` of a TensorFlow backend function '
           'should be a list or tuple.')
  if not isinstance(updates, (list, tuple)):
   raise TypeError('`updates` in a TensorFlow backend function '
           'should be a list or tuple.')
  self.inputs = list(inputs)
  self.outputs = list(outputs)
  with ops.control_dependencies(self.outputs):
   updates_ops = []
   for update in updates:
    if isinstance(update, tuple):
     p, new_p = update
     updates_ops.append(state_ops.assign(p, new_p))
    else:
     # assumed already an op
     updates_ops.append(update)
   self.updates_op = control_flow_ops.group(*updates_ops)
  self.name = name
  self.session_kwargs = session_kwargs

 def __call__(self, inputs):
  if not isinstance(inputs, (list, tuple)):
   raise TypeError('`inputs` should be a list or tuple.')
  feed_dict = {}
  for tensor, value in zip(self.inputs, inputs):
   if is_sparse(tensor):
    sparse_coo = value.tocoo()
    indices = np.concatenate((np.expand_dims(sparse_coo.row, 1),
                 np.expand_dims(sparse_coo.col, 1)), 1)
    value = (indices, sparse_coo.data, sparse_coo.shape)
   feed_dict[tensor] = value
  session = get_session()
  updated = session.run(
    self.outputs + [self.updates_op],
    feed_dict=feed_dict,
    **self.session_kwargs)
  return updated[:len(self.outputs)]

所以,function函數(shù)利用我們之前已經(jīng)創(chuàng)建好的comuptation graph。遵循計算圖,從輸入到定義的輸出。這也是為什么該函數(shù)經(jīng)常用于提取中間層結(jié)果。

以上這篇keras K.function獲取某層的輸出操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Matplotlib自定義坐標軸刻度的實現(xiàn)示例

    Matplotlib自定義坐標軸刻度的實現(xiàn)示例

    這篇文章主要介紹了Matplotlib自定義坐標軸刻度的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06
  • scrapy spider的幾種爬取方式實例代碼

    scrapy spider的幾種爬取方式實例代碼

    這篇文章主要介紹了scrapy spider的幾種爬取方式實例代碼,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • Python+PyQt5來實現(xiàn)文件高速查找

    Python+PyQt5來實現(xiàn)文件高速查找

    這篇文章主要為大家詳細介紹了如何模擬Everything,即通過python+PyQt5來實現(xiàn)可視化文件的高速查找,文中的示例代碼講解詳細,需要的可以參考一下
    2023-07-07
  • 深入了解Python enumerate和zip

    深入了解Python enumerate和zip

    這篇文章主要介紹了Python enumerate和zip的相關(guān)資料,文中講解非常細致,幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07
  • Python如何獲取pid和進程名字

    Python如何獲取pid和進程名字

    這篇文章主要介紹了Python如何獲取pid和進程名字的方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Python設(shè)計模式之職責鏈模式原理與用法實例分析

    Python設(shè)計模式之職責鏈模式原理與用法實例分析

    這篇文章主要介紹了Python設(shè)計模式之職責鏈模式,結(jié)合具體實例形式分析了Python責任鏈模式的概念、原理、定義與使用方法,需要的朋友可以參考下
    2019-01-01
  • python初學者,用python實現(xiàn)基本的學生管理系統(tǒng)(python3)代碼實例

    python初學者,用python實現(xiàn)基本的學生管理系統(tǒng)(python3)代碼實例

    這篇文章主要介紹了用python實現(xiàn)學生管理系統(tǒng),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04
  • python實現(xiàn)學生信息管理系統(tǒng)

    python實現(xiàn)學生信息管理系統(tǒng)

    這篇文章主要為大家詳細介紹了python實現(xiàn)學生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • Python同步遍歷多個列表的示例

    Python同步遍歷多個列表的示例

    今天小編就為大家分享一篇Python同步遍歷多個列表的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-02-02
  • python通過opencv實現(xiàn)圖片裁剪原理解析

    python通過opencv實現(xiàn)圖片裁剪原理解析

    這篇文章主要介紹了python通過opencv實現(xiàn)圖片裁剪原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01

最新評論