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設(shè)計模式之職責鏈模式原理與用法實例分析
這篇文章主要介紹了Python設(shè)計模式之職責鏈模式,結(jié)合具體實例形式分析了Python責任鏈模式的概念、原理、定義與使用方法,需要的朋友可以參考下2019-01-01python初學者,用python實現(xiàn)基本的學生管理系統(tǒng)(python3)代碼實例
這篇文章主要介紹了用python實現(xiàn)學生管理系統(tǒng),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04python通過opencv實現(xiàn)圖片裁剪原理解析
這篇文章主要介紹了python通過opencv實現(xiàn)圖片裁剪原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-01-01