将张量转换为keras中的numpy数组

时间:2019-09-23 09:09:50

标签: python numpy tensorflow keras conv-neural-network

我想将形状(?,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)

如果我不初始化会话并仅将张量 'out' 作为输出,则会编译程序。我尝试了其他几种方法,并提到了有关Stack Overflow的各种问题,但没有一个给我所需的结果。在上面的代码中将此张量 'out' 转换为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初始化变量,所以我也包括了这些行,但是仍然看到相同的错误。我该怎么解决。

1 个答案:

答案 0 :(得分:1)

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

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