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)文章
Python實現(xiàn)輸出某區(qū)間范圍內(nèi)全部素數(shù)的方法
這篇文章主要介紹了Python實現(xiàn)輸出某區(qū)間范圍內(nèi)全部素數(shù)的方法,涉及Python數(shù)值運算、排序、判斷等相關(guān)操作技巧,需要的朋友可以參考下2018-05-05
Python解析網(wǎng)頁源代碼中的115網(wǎng)盤鏈接實例
這篇文章主要介紹了Python解析網(wǎng)頁源代碼中的115網(wǎng)盤鏈接實例,主要采用了正則表達式re模塊來實現(xiàn)該功能,需要的朋友可以參考下2014-09-09
Python發(fā)起請求提示UnicodeEncodeError錯誤代碼解決方法
這篇文章主要介紹了Python發(fā)起請求提示UnicodeEncodeError錯誤代碼解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04
Python+OpenCV 實現(xiàn)圖片無損旋轉(zhuǎn)90°且無黑邊
今天小編就為大家分享一篇Python+OpenCV 實現(xiàn)圖片無損旋轉(zhuǎn)90°且無黑邊,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python獲取指定時間段內(nèi)特定規(guī)律的日期列表
這篇文章主要介紹了python獲取指定時間段內(nèi)特定規(guī)律的日期列表,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04

