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

时间:2017-10-11 00:31:00

标签: python tensorflow keras

我正在尝试在另一个Keras网络(B)中使用Keras网络(A)。我先培训网络A.然后我在网络B中使用它来执行一些正则化。内部网络BI希望使用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 :(得分:1)

我在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)

答案 1 :(得分:0)

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

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

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