本文介绍了使用tensorflow变量作为输入的keras正向传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use a Keras network (A) within another Keras network (B). I train network A first. Then I'm using it in network B to perform some regularization. Inside network B I would like to use evaluate or predict to get the output from network A. Unfortunately I haven't been able to get this to work since those functions expect a numpy array, instead it is receiving a Tensorflow variable as input.

这是我在自定义正则化器中使用网络A的方式:

Here is how I'm using network A inside a custom regularizer:

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网络计算前向通行证?

How can I compute a forward pass with a Keras network with a Tensorflow variable as input?

作为一个例子,这是我从numpy得到的:

As an example, here's what I get with 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

With 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.

推荐答案

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

I found my answer in a keras blog post. 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)

这篇关于使用tensorflow变量作为输入的keras正向传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 23:38