Подкласс TF / keras отлично работает в Eager Execution, и без него выдает огромную ошибку, которую невозможно отследить? - PullRequest
1 голос
/ 02 мая 2019

Я научился писать пользовательские слои из keras.io.Вот оно:

class modrelu(Layer):
    def __init__(self, **kwargs):
        super(modrelu, self).__init__(**kwargs)

    def build(self, input_shape):
        print(input_shape)
        self.b = self.add_weight(name='brad', shape=(input_shape[0][1],), initializer='uniform',
                                      trainable=True)
        super(modrelu, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        assert isinstance(x, list)
        ip_r, ip_i = x
        comp= tf.complex(ip_r, ip_i) 
        ABS= tf.math.abs(comp)
        ANG= tf.math.angle(comp)

        ABS= tf.nn.relu( self.b + ABS) 

        op_i=  ABS * tf.sin(ANG) #K.dot ??
        op_r= ABS * tf.cos(ANG)
        return [op_r, op_i]

    def compute_output_shape(self, input_shape):
        assert isinstance(input_shape, list)
        shape_a, shape_b = input_shape
        return [shape_a, shape_b]


act= modrelu()
a=tf.constant(np.array([[1,2], [4,4]]), dtype='float32')
b=tf.constant(np.array([[3,4], [5, -1]]), dtype='float32')
act([a,b])

При запуске в Eager, я получаю хорошие результаты.Без этого режима я получаю очень странную ошибку, которую я даже не могу проследить, с чего она началась, она в другом мире.Вот оно:

--------------------------------------------------------------------------- TypeError Traceback (последний вызов был последним) ~ \ AppData \Локальные \ conda \ conda \ envs \ py36 \ lib \ site-packages \ tenorflow \ python \ framework \ tenor_util.py в make_tensor_proto (значения, dtype, shape, verify_shape) 526 пытаются: -> 527 str_values ​​= [compat.as_bytes (x) для x в proto_values] 528, за исключением ошибки TypeError:

~ \ AppData \ Local \ conda \ conda \ envs \ py36 \ lib \ site-packages \ensorflowflow \ python \ framework \ensor_util.py в (.0) 526 try: -> 527 str_values ​​= [compat.as_bytes (x) для x в proto_values] 528 за исключением TypeError:

~ \ AppData \ Local \ conda \ conda \ envs \ py36 \ lib \ site-packages \ tenorflow \ python \ util \ compat.py в as_bytes (bytes_or_text, кодировка) 60 повысить TypeError ('Ожидаемая двоичная или Unicode-строка, получено% r'% ---> 61 (bytes_or_text,)) 62

TypeError: Ожидаемая двоичная или Unicode-строка, полученная Dimension (2)

Во время обработки вышеупомянутого исключения возникает другое исключениеed:

TypeError Traceback (последний вызов был последним) в 2 a = tf.constant (np.array ([[1,2], [4,4]]), dtype = 'float32') 3b = tf.constant (np.array ([[3,4], [5, -1]]), dtype = 'float32') ----> 4 act ([a, b])

~ \ AppData \ Local \ conda \ conda \ envs \ py36 \ lib \ site-packages \ tenorsflow \ python \ keras \ engine \ base_layer.py в , вызов (self, input, * args, ** kwargs) 744 # пользователь вручную переписал метод сборки, нужно ли нам 745 # собрать его.-> 746 self.build (input_shapes) 747 # Мы должны установить self.built, так как пользовательские функции сборки не ограничены 748 # для установки self.built.

в сборке (self, input_shape) 7 print (input_shape) 8 self.b = self.add_weight (name = 'brad', shape = (input_shape [0] [1],), инициализатор = "равномерный", ----> 9 обучаемый = True) 10 # self.b = K.variable (значение = np.random.rand (input_shape [0] [1]) - 0,5, dtype = 'float32') # 11 super (modrelu, self) .build (input_shape) # Обязательно вызовите этов конце

~ \ AppData \ Local \ conda \ conda \ envs \ py36 \ lib \ site-packages \ tenorflow \ python \ keras \ engine \ base_layer.py в add_weight (self, name, shape, dtype, инициализатор, регуляризатор, обучаемый, ограничение, разделитель, use_resource, синхронизация, агрегация, ** kwargs) 607 коллекций = коллекции, 608 синхронизация = синхронизация, -> 609 агрегация = агрегация) 610 backend.track_variable (переменная) 611

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ обучение \ checkpointable \ base.py в _add_variable_with_custom_getter (self, name, shape, dtype, initializer, getter, overwrite, ** kwargs_for_getter) 637 new_variable = getter (638 name = имя, shape = shape, dtype = dtype, initializer = initializer, -> 639 ** kwargs_for_getter) 640 641 # Если мы установим инициализатор и обработаем переменную, отслеживание не будет

~ \ AppData \ Local \ conda \ conda \ envs \ py36 \ lib \ site-packages \ensororflow\ python \ keras \ engine \ base_layer.py в make_variable (имя, форма, dtype, инициализатор, partition_info, обучаемое, caching_device, validate_shape, ограничение, use_resource, коллекции, синхронизация, агрегация, разделитель) 1975
collection = collection, 1976
синхронизация = синхронизация, -> агрегация 1977 = агрегация) прибыль 1978 г. v 1979

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ OPS \ variables.py в звоните (cls, * args, ** kwargs) 181 def call (cls, * args, ** kwargs): 182, если cls - переменная V1: -> 183 return cls._variable_v1_call (* args, ** kwargs) 184 elif cls является переменной: 185 return cls._variable_v2_call (* args, ** kwargs)

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ OPS \ variables.py в _variable_v1_call (cls, initial_value, обучаемый, коллекции, validate_shape, caching_device, name, variable_def, dtype, Ожидаемая форма, import_scope, ограничение, use_resource, синхронизация, агрегация) 144 use_resource = use_resource, 145 синхронизация = синхронизация, -> 146 агрегация = агрегация) 147 148 def _variable_v2_call (cls,

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ OPS \ variables.py в (** кваргс) 123 агрегация = VariableAggregation.NONE): 124 "" "Вызовите переменную класса. Полезно для принудительной подписи." "" -> 125 previous_getter = lambda ** kwargs: default_variable_creator (Нет, ** kwargs) 126 для получения в ops.get_default_graph () ._ variable_creator_stack: # pylint: отключить = защищенный доступ 127 previous_getter = _make_getter (getter, previous_getter)

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ OPS \ variable_scope.py в default_variable_creator (next_creator, ** kwargs) 2435
caching_device = caching_device, name = name, dtype = dtype, 2436
ограничение = ограничение, variable_def = variable_def, -> 2437 import_scope = import_scope) 2438 else: 2439 возвращаемых переменных .RefVariable (

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ OPS \ variables.py в звоните (cls, * args, ** kwargs) 185 return cls._variable_v2_call (* args, ** kwargs) 186 еще: -> 187 return super (VariableMetaclass, cls). call (* args, ** kwargs) 188 189

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайт-пакеты \ tensorflow \ питон \ OPS \ resource_variable_ops.py в init (self, initial_value, обучаемый, коллекции, validate_shape, caching_device, name, dtype, variable_def, import_scope, ограничение) 295 имя = имя, 296 dtype = dtype, -> 297 ограничение = ограничение) 298 299 # pylint: отключить = неиспользованный аргумент

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайт-пакеты \ tensorflow \ питон \ OPS \ resource_variable_ops.py в _init_from_args (self, initial_value, обучаемое, коллекции, validate_shape, caching_device, name, dtype, ограничение) 407 с ops.name_scope («Инициализатор»), ops.device (Нет): 408 initial_value = ops.convert_to_tensor ( -> 409 initial_value (), если init_from_fn иначе initial_value, 410 name = "initial_value", dtype = dtype) 411 self._handle = eager_safe_variable_handle (

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ keras \ двигатель \ base_layer.py in () 1957 инициализатор = инициализатор (dtype = dtype)
1958 init_val = lambda: initializer (# pylint: отключить = G-длинный-Lambda -> форма 1959 года, dtype = dtype, partition_info = partition_info) 1960 variable_dtype = dtype.base_dtype 1961, если use_resource Нет:

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайт-пакеты \ tensorflow \ питон \ OPS \ init_ops.py в вызов (self, shape, dtype, partition_info) 253 dtype = self.dtype254 return random_ops.random_uniform ( -> 255 формы, self.minval, self.maxval, dtype, seed = self.seed) 256 257 def get_config (self):

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайт-пакеты \ tensorflow \ питон \ OPS \ random_ops.py в random_uniform (форма, minval, maxval, dtype, seed, name) 233 maxval = 1 234 с ops.name_scope (name, "random_uniform", [shape, minval, maxval]) в качестве имени: -> 235 shape = _ShapeTensor (shape) 236 minval = ops.convert_to_tensor (minval, dtype = dtype, name = "min") 237 maxval = ops.convert_to_tensor (maxval, dtype = dtype, name = "max")

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайт-пакеты \ tensorflow \ питон \ OPS \ random_ops.py в _ShapeTensor (форма) 42 еще: 43 dtype = нет ---> 44 return ops.convert_to_tensor (shape, dtype = dtype, name = "shape") 45 46

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ Framework \ ops.py в convert_to_tensor (значение, тип, имя, предпочтительный тип) 1048
имя = имя, 1049 предпочитаемый_д тип = предпочтительный_дит, -> 1050 as_ref = False) 1051 1052

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ Framework \ ops.py в internal_convert_to_tensor (значение, dtype, name, as_ref, fav__dtype, ctx) 1144 1145, если ret равен None: -> 1146 ret = translation_func (значение, dtype = dtype, name = name, as_ref = as_ref) 1147 1148, если ret не NotImplemented:

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ Framework \ constant_op.py в _constant_tensor_conversion_function (v, dtype, name, as_ref) 227 as_ref = False): 228 _ = as_ref -> 229 возвращаемая константа (v, dtype = dtype, name = name) 230 231

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ Framework \ constant_op.py в константе (значение, dtype, форма, имя, verify_shape) 206 tenor_value.tensor.CopyFrom ( 207 tenor_util.make_tensor_proto ( -> 208 значений, dtype = dtype, shape = shape, verify_shape = verify_shape)) 209 dtype_value = attr_value_pb2.AttrValue (type = tenor_value.tensor.dtype) 210 const_tensor = g.create_op (

~ \ AppData \ Local \ Конда \ Конда \ envs \ py36 \ Lib \ сайта-пакеты \ tensorflow \ питон \ Framework \ tensor_util.py в make_tensor_proto (значения, dtype, shape, verify_shape) 529 повысить TypeError («Не удалось преобразовать объект типа% s в Tensor.» 530 "Содержание:% s. Рассмотрим приведение элементов к a" -> 531 "поддерживаемый тип." % (тип (значения), значения)) 532 tenor_proto.string_val.extend (str_values) 533 вернуть тензор_прото

TypeError: Не удалось преобразовать объект типа в Tensor. Содержание: (Размер (2),). Рассмотрим приведение элементов к поддерживаемым тип.

1 Ответ

2 голосов
/ 02 мая 2019

Вы получаете форму как TensorShape экземпляр. Вы можете использовать атрибут as_list(), чтобы преобразовать его в список Python, если выполнение не требует:

if tf.executing_eagerly():
    shape = (input_shape[0][1], )
else:
    shape = (input_shape[0].as_list()[1], )

В вашем коде это будет так:

import tensorflow as tf
from tensorflow.keras.layers import Layer
import numpy as np

class modrelu(Layer):
    def __init__(self, **kwargs):
        super(modrelu, self).__init__(**kwargs)

    def build(self, input_shape):
        if tf.executing_eagerly():
            shape = (input_shape[0][1])
        else:
            shape = (input_shape[0].as_list()[1], )
        self.b = self.add_weight(name='brad',
                                 shape=shape,
                                 initializer='uniform',
                                 trainable=True)
        super(modrelu, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        assert isinstance(x, list)
        ip_r, ip_i = x
        comp = tf.complex(ip_r, ip_i) 
        ABS = tf.math.abs(comp)
        ANG = tf.math.angle(comp)
        ABS = tf.nn.relu( self.b + ABS) 
        op_i =  ABS * tf.sin(ANG) #K.dot ??
        op_r = ABS * tf.cos(ANG)
        return [op_r, op_i]

    def compute_output_shape(self, input_shape):
        assert isinstance(input_shape, list)
        shape_a, shape_b = input_shape
        return [shape_a, shape_b]

act = modrelu()
a = tf.constant(np.array([[1,2], [4,4]]), dtype='float32')
b = tf.constant(np.array([[3,4], [5, -1]]), dtype='float32')
act([a,b])
# [<tf.Tensor 'modrelu_6/mul_1:0' shape=(2, 2) dtype=float32>,
#  <tf.Tensor 'modrelu_6/mul:0' shape=(2, 2) dtype=float32>]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...