Tensorflow: FailedPreconditionError: Попытка использовать неинициализированное значение conv2d_transpose / bias - PullRequest
0 голосов
/ 26 апреля 2020

Я пытаюсь построить модель, которая использует транспонированную операцию свертки, но когда я пытаюсь передать весовые коэффициенты и смещение в качестве параметра для функции модели, это выдает ошибку.

import tensorflow as tf
import cv2


class WeighsTest:
    def __model_1(self, plh_var1,weights,bias):
        conv = tf.nn.conv2d(plh_var1, weights["v1"], [1, 1, 1, 1], padding="SAME")
        conv = tf.add(conv, bias["b1"])
        conv = tf.nn.relu(conv)
        tran_conv = tf.layers.conv2d_transpose(conv,32, 4, 3, padding="valid")
        return tran_conv

    def train(self, input_img):
        plh = tf.placeholder(dtype=tf.float32, shape=(None, 84, 150, 3), name="input_img")

        with tf.variable_scope("test", reuse=tf.AUTO_REUSE):
            var_dict_1 = {
                "v1": tf.get_variable("v1", shape=(2, 2, 3, 32), initializer=tf.contrib.layers.xavier_initializer())
            }
            bias_1 = {
                "b1": tf.get_variable("b1", shape=32, initializer=tf.contrib.layers.xavier_initializer())
            }

        init = tf.global_variables_initializer()
        with tf.Session() as sess:
            sess.run(init)
            out_p = sess.run([self.__model_1(plh, var_dict_1, bias_1)], feed_dict={plh: [input_img]})
        return out_p


if __name__ == '__main__':
    obj = WeighsTest()
    img = cv2.imread('./1.jpg')
    output = obj.train(img)

дается трассировка ниже

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 1365, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 1350, in _run_fn
    target_list, run_metadata)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 1443, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value conv2d_transpose/bias
     [[{{node conv2d_transpose/bias/read}}]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/strange/DEV/Python_Projects/slmv/testing_unit.py", line 43, in <module>
    output = obj.train(img)
  File "/home/strange/DEV/Python_Projects/slmv/testing_unit.py", line 36, in train
    out_p = sess.run([self.__model_1(x1, var_dict_1, bias_1)], feed_dict={x1: [input_img]})
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 956, in run
    run_metadata_ptr)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 1180, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 1359, in _do_run
    run_metadata)
  File "/usr/local/lib/python3.7/dist-packages/tensorflow_core/python/client/session.py", line 1384, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value conv2d_transpose/bias
     [[node conv2d_transpose/bias/read (defined at usr/local/lib/python3.7/dist-packages/tensorflow_core/python/framework/ops.py:1748) ]]

Original stack trace for 'conv2d_transpose/bias/read':
  File "home/strange/DEV/Python_Projects/slmv/testing_unit.py", line 43, in <module>
    output = obj.train(img)
  File "home/strange/DEV/Python_Projects/slmv/testing_unit.py", line 36, in train
    out_p = sess.run([self.__model_1(x1, var_dict_1, bias_1)], feed_dict={x1: [input_img]})
  File "home/strange/DEV/Python_Projects/slmv/testing_unit.py", line 10, in __model_1
    tran_conv = tf.layers.conv2d_transpose(conv,32, 4, 3, padding="valid")
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/util/deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/layers/convolutional.py", line 1279, in conv2d_transpose
    return layer.apply(inputs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/util/deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/base_layer.py", line 1700, in apply
    return self.__call__(inputs, *args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/layers/base.py", line 548, in __call__
    outputs = super(Layer, self).__call__(inputs, *args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/base_layer.py", line 824, in __call__
    self._maybe_build(inputs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/base_layer.py", line 2146, in _maybe_build
    self.build(input_shapes)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/layers/convolutional.py", line 787, in build
    dtype=self.dtype)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/layers/base.py", line 461, in add_weight
    **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/keras/engine/base_layer.py", line 529, in add_weight
    aggregation=aggregation)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/training/tracking/base.py", line 712, in _add_variable_with_custom_getter
    **kwargs_for_getter)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variable_scope.py", line 1500, in get_variable
    aggregation=aggregation)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variable_scope.py", line 1243, in get_variable
    aggregation=aggregation)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variable_scope.py", line 567, in get_variable
    aggregation=aggregation)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variable_scope.py", line 519, in _true_getter
    aggregation=aggregation)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variable_scope.py", line 933, in _get_single_variable
    aggregation=aggregation)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variables.py", line 258, in __call__
    return cls._variable_v1_call(*args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variables.py", line 219, in _variable_v1_call
    shape=shape)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variables.py", line 197, in <lambda>
    previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variable_scope.py", line 2519, in default_variable_creator
    shape=shape)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variables.py", line 262, in __call__
    return super(VariableMetaclass, cls).__call__(*args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variables.py", line 1688, in __init__
    shape=shape)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/variables.py", line 1872, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/util/dispatch.py", line 180, in wrapper
    return target(*args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/array_ops.py", line 203, in identity
    ret = gen_array_ops.identity(input, name=name)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/ops/gen_array_ops.py", line 4239, in identity
    "Identity", input=input, name=name)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/framework/op_def_library.py", line 794, in _apply_op_helper
    op_def=op_def)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/util/deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/framework/ops.py", line 3357, in create_op
    attrs, op_def, compute_device)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/framework/ops.py", line 3426, in _create_op_internal
    op_def=op_def)
  File "usr/local/lib/python3.7/dist-packages/tensorflow_core/python/framework/ops.py", line 1748, in __init__
    self._traceback = tf_stack.extract_stack()

Важно передать смещение и веса в качестве параметров модели. Я использовал tenorflow-CPU 1.15.2 для модели. Есть идеи, как это решить? Спасибо

1 Ответ

0 голосов
/ 28 апреля 2020

Модель необходимо вызывать перед использованием tf.global_variabels_initializer() ie. функция поезда изменяется следующим образом:

def train(self, input_img):
        plh = tf.placeholder(dtype=tf.float32, shape=(None, 84, 150, 3), name="input_img")

        with tf.variable_scope("test", reuse=tf.AUTO_REUSE):
            var_dict_1 = {
                "v1": tf.get_variable("v1", shape=(2, 2, 3, 32), initializer=tf.contrib.layers.xavier_initializer())
            }
            bias_1 = {
                "b1": tf.get_variable("b1", shape=32, initializer=tf.contrib.layers.xavier_initializer())
            }

        """model is called before variable initialization"""

        model = self.__model_1(plh, var_dict_1, bias_1)

        init = tf.global_variables_initializer()
        with tf.Session() as sess:
            sess.run(init)
            out_p = sess.run([model], feed_dict={plh: [input_img]})
        return out_p

строка, указанная ниже:

out_p = sess.run([self.__model_1(plh, var_dict_1, bias_1)], feed_dict={plh: [input_img]})

заменяется на

out_p = sess.run([model], feed_dict={plh: [input_img]})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...