首页 > 解决方案 > 在keras中将张量转换为numpy数组

问题描述

我想将形状 (?,224,224,3) 的张量转换为 keras 中的 numpy 数组。

Tensor("add_1/add_3:0", shape=(?, 224, 224, 3), dtype=float32)

我的基本 CNN 代码如下:

final_model = Model(input=[img_input], output=[act1,act2,act3,act4,act5])
addops(final_model)    

def addops(model):
        output = model.output
        factor = 2
        for i in range(len(output)):
                output[i] = UpSampling2D(size = (factor**i,factor**i),interpolation='bilinear')(output[i])
                output[i] = (ZeroPadding2D((1,1)))(output[i])
                output[i] = (Conv2D(3,(3,3)))(output[i])
        out = Add()([output[0],output[1],output[2],output[3],output[4]])
        print(out)
        sess = tf.InteractiveSession()
        outarray = tf.Variable(out).eval()
        print(outarray)

基本上,我采用预训练模型并捕获一些中间层的特征图,并对它们进行这些转换以将它们重塑为输入图像的大小。稍后,我将这些重塑的特征图添加到单个张量中。我想将上述程序中名为“out”的张量转换为 numpy 数组。这是我正在尝试实施的项目的一部分,但我在这里感到震惊。

当我运行此代码时,出现以下错误

ValueError: initial_value must have a shape specified: Tensor("add_1/add_3:0", shape=(?, 224, 224, 3), dtype=float32)

如果我不初始化会话并仅将张量“输出”作为输出,则程序将被编译。我尝试了其他几种方法,并在 Stack Overflow 上提到了各种问题,但都没有给我所需的结果。将上述代码中的这个张量“输出”转换为 numpy 数组的最佳方法是什么。

注意:我想稍后将此 numpy 数组转换为图像。我很高兴知道是否有任何方法可以直接将此张量转换为图像。

EDIT1:我传递了一个图像来填充形状中的 initial_value,但现在我看到另一个错误,这基本上是将此张量转换为 numpy 数组的问题。

    def addops(model,image):
        image = load_img(image,target_size=(224,224))
        image = img_to_array(image)
        image = np.expand_dims(image,axis=0)
        val =model.predict(image)
#       print(val)
        output = val
        factor = 2
        for i in range(len(output)):
                output[i] = tf.convert_to_tensor(output[i],np.float32)
                output[i] = UpSampling2D(size = (factor**i,factor**i),interpolation='bilinear')(output[i])
                output[i] = (ZeroPadding2D((1,1)))(output[i])
                output[i] = (Conv2D(3,(3,3)))(output[i])
        out = Add()([output[0],output[1],output[2],output[3],output[4]])
        print(out)
        sess = tf.InteractiveSession()
        sess.run(tf.global_variables_initializer())
        sess.run(tf.local_variables_initializer())
        outarray = tf.Variable(out).eval()
        print(outarray)

错误信息是:

    Using TensorFlow backend.
WARNING:tensorflow:From /home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
2019-09-23 02:39:52.684145: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2019-09-23 02:39:52.690019: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3493110000 Hz
2019-09-23 02:39:52.692198: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x51c36f0 executing computations on platform Host. Devices:
2019-09-23 02:39:52.692254: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
WARNING:tensorflow:From /home/ssindhu/deeplab_env/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
Instructions for updating:
Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.
/home/ssindhu/hypercolumns.py:107: UserWarning: Update your `Model` call to the Keras 2 API: `Model(inputs=[<tf.Tenso..., outputs=[<tf.Tenso...)`
  final_model = Model(input=[img_input], output=[act1,act2,act3,act4,act5])
Frontend weights loaded.
Tensor("add_1/add_3:0", shape=(1, 224, 224, 3), dtype=float32)
Traceback (most recent call last):
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1334, in _do_call
    return fn(*args)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1319, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1407, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Variable
         [[{{node _retval_Variable_0_0}}]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "training.py", line 18, in <module>
    gethypercols(model,'JPEGImages/2007_000033.jpg')
  File "/home/ssindhu/hypercolumns.py", line 34, in gethypercols
    outarray = tf.Variable(out).eval()
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 1695, in eval
    return self._variable.eval(session=session)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 695, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 5181, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1152, in _run
    feed_dict_tensor, options, run_metadata)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1328, in _do_run
    run_metadata)
  File "/home/ssindhu/deeplab_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1348, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Variable
         [[{{node _retval_Variable_0_0}}]]

它说我正在尝试使用未初始化的值变量。我已经看到我们必须为 tensorflow 初始化会话中的变量,所以我也包含了这些行。但我仍然看到同样的错误。我怎么能解决这个问题。

标签: pythonnumpytensorflowkerasconv-neural-network

解决方案


如果要计算张量的值(这里out是张量),只需在会话中运行张量,无需从中创建变量。您可以out在会话中运行。

变量用于存储模型的可训练(和其他)参数。您所做的是创建一个应该初始化的新变量out并在没有初始化的情况下运行它。


推荐阅读