Написание пользовательского слоя Keras TypeError: Ожидаемая двоичная или Unicode строка, полученная Dimension (3) - PullRequest
0 голосов
/ 22 марта 2020

Я пытался написать свой собственный слой в соответствии с keras do c: https://keras.io/layers/writing-your-own-keras-layers/, но он выдает ошибку типа: Ожидаемая двоичная или Unicode строка, полученная Dimension (3). Я предоставил вам полный код для воспроизведения ошибки. Пожалуйста, дайте мне знать, если вы знаете, как справиться с этим.

Обратите внимание, что я использую версию tenorflow, как показано ниже:

tensorboard                        1.13.1   
tensorflow                         1.14.0rc1
tensorflow-estimator               1.14.0   
tensorflow-probability             0.7.0    

Я использую tenorflow.keras в качестве бэкэнда. Пожалуйста, помогите устранить эту ошибку в этой среде, вместо того, чтобы предлагать обновление до другой версии tenorflow.

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from tensorflow.keras import layers

# Build simple model
a = layers.Input(shape=2)
b = layers.Dense(3)(a)
m = keras.Model(a,b)
m.compile(optimizer='sgd', loss = 'mean_squared_error')

# Build custom layer according to keras document: https://keras.io/layers/writing-your-own-keras-layers/
class NewLayer(Layer):
    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(NewLayer,self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel',
                                      shape =(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True
                                      )
        super(NewLayer, self).build(input_shape) # Be sure to call this at the end

# try to do computation on new layer (created by custom layer)
newlayer = NewLayer(4)
newoutput = newlayer(b) # <-- this gives error

Для вашего сведения, полный вывод ошибки приведен ниже:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape, allow_broadcast)
    557     try:
--> 558       str_values = [compat.as_bytes(x) for x in proto_values]
    559     except TypeError:

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py in <listcomp>(.0)
    557     try:
--> 558       str_values = [compat.as_bytes(x) for x in proto_values]
    559     except TypeError:

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/util/compat.py in as_bytes(bytes_or_text, encoding)
     64     raise TypeError('Expected binary or unicode string, got %r' %
---> 65                     (bytes_or_text,))
     66 

TypeError: Expected binary or unicode string, got Dimension(3)

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-6bb36fcaaf24> in <module>
     28 # try to do computation on new layer (created by custom layer)
     29 newlayer = NewLayer(4)
---> 30 newoutput = newlayer(b) # <-- this gives error

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    589           # Build layer if applicable (if the `build` method has been
    590           # overridden).
--> 591           self._maybe_build(inputs)
    592 
    593           # Wrapping `call` function in autograph to allow for dynamic control

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in _maybe_build(self, inputs)
   1879       # operations.
   1880       with tf_utils.maybe_init_scope(self):
-> 1881         self.build(input_shapes)
   1882     # We must set self.built since user defined build functions are not
   1883     # constrained to set self.built.

<ipython-input-1-6bb36fcaaf24> in build(self, input_shape)
     22                                       shape =(input_shape[1], self.output_dim),
     23                                       initializer='uniform',
---> 24                                       trainable=True
     25                                       )
     26         super(NewLayer, self).build(input_shape) # Be sure to call this at the end

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint, partitioner, use_resource, synchronization, aggregation, **kwargs)
    382         collections=collections_arg,
    383         synchronization=synchronization,
--> 384         aggregation=aggregation)
    385     backend.track_variable(variable)
    386 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/training/tracking/base.py in _add_variable_with_custom_getter(self, name, shape, dtype, initializer, getter, overwrite, **kwargs_for_getter)
    661         dtype=dtype,
    662         initializer=initializer,
--> 663         **kwargs_for_getter)
    664 
    665     # If we set an initializer and the variable processed it, tracking will not

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer_utils.py in make_variable(name, shape, dtype, initializer, trainable, caching_device, validate_shape, constraint, use_resource, collections, synchronization, aggregation, partitioner)
    153       synchronization=synchronization,
    154       aggregation=aggregation,
--> 155       shape=variable_shape if variable_shape.rank else None)
    156 
    157 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/variables.py in __call__(cls, *args, **kwargs)
    257   def __call__(cls, *args, **kwargs):
    258     if cls is VariableV1:
--> 259       return cls._variable_v1_call(*args, **kwargs)
    260     elif cls is Variable:
    261       return cls._variable_v2_call(*args, **kwargs)

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/variables.py in _variable_v1_call(cls, initial_value, trainable, collections, validate_shape, caching_device, name, variable_def, dtype, expected_shape, import_scope, constraint, use_resource, synchronization, aggregation, shape)
    218         synchronization=synchronization,
    219         aggregation=aggregation,
--> 220         shape=shape)
    221 
    222   def _variable_v2_call(cls,

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/variables.py in <lambda>(**kwargs)
    196                         shape=None):
    197     """Call on Variable class. Useful to force the signature."""
--> 198     previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
    199     for _, getter in ops.get_default_graph()._variable_creator_stack:  # pylint: disable=protected-access
    200       previous_getter = _make_getter(getter, previous_getter)

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/variable_scope.py in default_variable_creator(next_creator, **kwargs)
   2493         synchronization=synchronization,
   2494         aggregation=aggregation,
-> 2495         shape=shape)
   2496   else:
   2497     return variables.RefVariable(

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/variables.py in __call__(cls, *args, **kwargs)
    261       return cls._variable_v2_call(*args, **kwargs)
    262     else:
--> 263       return super(VariableMetaclass, cls).__call__(*args, **kwargs)
    264 
    265 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/resource_variable_ops.py in __init__(self, initial_value, trainable, collections, validate_shape, caching_device, name, dtype, variable_def, import_scope, constraint, distribute_strategy, synchronization, aggregation, shape)
    458           synchronization=synchronization,
    459           aggregation=aggregation,
--> 460           shape=shape)
    461 
    462   def __repr__(self):

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/resource_variable_ops.py in _init_from_args(self, initial_value, trainable, collections, caching_device, name, dtype, constraint, synchronization, aggregation, shape)
    602           with ops.name_scope("Initializer"), device_context_manager(None):
    603             initial_value = ops.convert_to_tensor(
--> 604                 initial_value() if init_from_fn else initial_value,
    605                 name="initial_value", dtype=dtype)
    606           # Don't use `shape or initial_value.shape` since TensorShape has

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer_utils.py in <lambda>()
    133           (type(init_ops.Initializer), type(init_ops_v2.Initializer))):
    134         initializer = initializer()
--> 135       init_val = lambda: initializer(shape, dtype=dtype)
    136       variable_dtype = dtype.base_dtype
    137   if use_resource is None:

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/init_ops.py in __call__(self, shape, dtype, partition_info)
    281       dtype = self.dtype
    282     return random_ops.random_uniform(
--> 283         shape, self.minval, self.maxval, dtype, seed=self.seed)
    284 
    285   def get_config(self):

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/random_ops.py in random_uniform(shape, minval, maxval, dtype, seed, name)
    237     maxval = 1
    238   with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name:
--> 239     shape = _ShapeTensor(shape)
    240     minval = ops.convert_to_tensor(minval, dtype=dtype, name="min")
    241     maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max")

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/ops/random_ops.py in _ShapeTensor(shape)
     42   else:
     43     dtype = None
---> 44   return ops.convert_to_tensor(shape, dtype=dtype, name="shape")
     45 
     46 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in convert_to_tensor(value, dtype, name, preferred_dtype, dtype_hint)
   1085   preferred_dtype = deprecation.deprecated_argument_lookup(
   1086       "dtype_hint", dtype_hint, "preferred_dtype", preferred_dtype)
-> 1087   return convert_to_tensor_v2(value, dtype, preferred_dtype, name)
   1088 
   1089 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in convert_to_tensor_v2(value, dtype, dtype_hint, name)
   1143       name=name,
   1144       preferred_dtype=dtype_hint,
-> 1145       as_ref=False)
   1146 
   1147 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx, accept_symbolic_tensors, accept_composite_tensors)
   1222 
   1223     if ret is None:
-> 1224       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1225 
   1226     if ret is NotImplemented:

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    303                                          as_ref=False):
    304   _ = as_ref
--> 305   return constant(v, dtype=dtype, name=name)
    306 
    307 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name)
    244   """
    245   return _constant_impl(value, dtype, shape, name, verify_shape=False,
--> 246                         allow_broadcast=True)
    247 
    248 

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
    282       tensor_util.make_tensor_proto(
    283           value, dtype=dtype, shape=shape, verify_shape=verify_shape,
--> 284           allow_broadcast=allow_broadcast))
    285   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    286   const_tensor = g.create_op(

~/opt/anaconda3/envs/ml/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape, allow_broadcast)
    560       raise TypeError("Failed to convert object of type %s to Tensor. "
    561                       "Contents: %s. Consider casting elements to a "
--> 562                       "supported type." % (type(values), values))
    563     tensor_proto.string_val.extend(str_values)
    564     return tensor_proto

TypeError: Failed to convert object of type <class 'tuple'> to Tensor. Contents: (Dimension(3), 4). Consider casting elements to a supported type.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...