首页 文章

keras正向传递具有tensorflow变量作为输入

提问于
浏览
1

我正在尝试在另一个Keras网络(B)中使用Keras网络(A) . 我先培训网络A.然后我在网络B中使用它来执行一些正则化 . 在网络B内部我想使用 evaluatepredict 从网络A获取输出 . 不幸的是我无法使用它,因为这些函数需要一个numpy数组,而是接收一个Tensorflow变量作为输入 .

以下是我在自定义规范器中使用网络A的方法:

class CustomRegularizer(Regularizer):
    def __init__(self, model):
        """model is a keras network"""
        self.model = model

    def __call__(self, x):
        """Need to fix this part"""
        return self.model.evaluate(x, x)

如何计算带有Tensorflow变量作为输入的Keras网络的正向传递?

举个例子,这是我用numpy得到的:

x = np.ones((1, 64), dtype=np.float32)
model.predict(x)[:, :10]

输出:

array([[-0.0244251 ,  3.31579041,  0.11801113,  0.02281714, -0.11048832,
         0.13053198,  0.14661783, -0.08456061, -0.0247585 ,  
0.02538805]], dtype=float32)

使用Tensorflow

x = tf.Variable(np.ones((1, 64), dtype=np.float32))
model.predict_function([x])

输出:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-92-4ed9d86cd79d> in <module>()
      1 x = tf.Variable(np.ones((1, 64), dtype=np.float32))
----> 2 model.predict_function([x])

~/miniconda/envs/bolt/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in __call__(self, inputs)
   2266         updated = session.run(self.outputs + [self.updates_op],
   2267                               feed_dict=feed_dict,
-> 2268                               **self.session_kwargs)
   2269         return updated[:len(self.outputs)]
   2270 

~/miniconda/envs/bolt/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/miniconda/envs/bolt/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    952             np_val = subfeed_val.to_numpy_array()
    953           else:
--> 954             np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
    955 
    956           if (not is_tensor_handle_feed and

~/miniconda/envs/bolt/lib/python3.6/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    529 
    530     """
--> 531     return array(a, dtype, copy=False, order=order)
    532 
    533 

ValueError: setting an array element with a sequence.

2 回答

  • 0

    我不确定tensorflow变量的位置,但如果它在那里,你可以这样做:

    model.predict([sess.run(x)])
    

    其中 sess 是张量流会话,即 sess = tf.Session() .

  • 0

    我在keras博客文章中找到了答案 . https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html

    from keras.models import Sequential
    
    model = Sequential()
    model.add(Dense(32, activation='relu', input_dim=784))
    model.add(Dense(10, activation='softmax'))
    
    # this works! 
    x = tf.placeholder(tf.float32, shape=(None, 784))
    y = model(x)
    

相关问题