SHARE
TWEET

Untitled

a guest Jun 20th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. import tensorflow as tf
  3. from tensorflow import keras
  4. from keras.models import Sequential, load_model
  5. from keras.layers import Dense, Activation, Dropout, Add
  6. from keras import metrics, Input, Model, optimizers
  7. from keras.utils.generic_utils import get_custom_objects
  8. import keras.backend as K
  9. from keras.initializers import Initializer
  10.      
  11. class myInit( Initializer ):
  12.     def __init__(self, matrix):
  13.         self.matrix = matrix
  14.  
  15.     def __call__(self, shape, dtype=None):
  16.     # array filled with matrix parameter'
  17.         return K.variable(value = self.matrix, dtype=dtype )
  18.  
  19.     def get_config(self):
  20.         return {
  21.             'matrix' : self.matrix
  22.         }
  23.      
  24. val = np.ones((2, 2))
  25.  
  26. input_l=Input(shape=(2,))
  27. hidden=Dropout(rate=0.3,seed=0)(input_l)
  28. x1 = Dense(2, kernel_initializer=myInit(val),
  29.                 activation=None, )(hidden)
  30. x2 = Dense(2, activation='relu')(hidden)
  31. energy=Add()([x1,x2])
  32. output=Activation('softmax')(energy)  
  33. model = Model(input_l,output)
  34.  
  35. model.compile(loss='categorical_crossentropy', optimizer='adam' , metrics=['categorical_accuracy'])
  36. model_info=model.get_config()
  37.  
  38. model.save("savedmodel_ex.h5")
  39. model = load_model("savedmodel_ex.h5", custom_objects={'myInit':myInit})
  40.      
  41. ---------------------------------------------------------------------------
  42. TypeError                                 Traceback (most recent call last)
  43. <ipython-input-20-99f620c51ed9> in <module>()
  44.      12
  45.      13 model.save("savedmodel_ex.h5")
  46. ---> 14 model = load_model("savedmodel_ex.h5", custom_objects={'myInit':myInit})
  47.  
  48. /lib/python2.7/site-packages/keras/models.pyc in load_model(filepath, custom_objects, compile)
  49.     268             raise ValueError('No model found in config file.')
  50.     269         model_config = json.loads(model_config.decode('utf-8'))
  51. --> 270         model = model_from_config(model_config, custom_objects=custom_objects)
  52.     271
  53.     272         # set weights
  54.  
  55. /lib/python2.7/site-packages/keras/models.pyc in model_from_config(config, custom_objects)
  56.     345                         'Maybe you meant to use '
  57.     346                         '`Sequential.from_config(config)`?')
  58. --> 347     return layer_module.deserialize(config, custom_objects=custom_objects)
  59.     348
  60.     349
  61.  
  62. /lib/python2.7/site-packages/keras/layers/__init__.pyc in deserialize(config, custom_objects)
  63.      53                                     module_objects=globs,
  64.      54                                     custom_objects=custom_objects,
  65. ---> 55                                     printable_module_name='layer')
  66.  
  67. /lib/python2.7/site-packages/keras/utils/generic_utils.pyc in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
  68.     142                 return cls.from_config(config['config'],
  69.     143                                        custom_objects=dict(list(_GLOBAL_CUSTOM_OBJECTS.items()) +
  70. --> 144                                                            list(custom_objects.items())))
  71.     145             with CustomObjectScope(custom_objects):
  72.     146                 return cls.from_config(config['config'])
  73.  
  74. /lib/python2.7/site-packages/keras/engine/topology.pyc in from_config(cls, config, custom_objects)
  75.    2533                 if layer in unprocessed_nodes:
  76.    2534                     for node_data in unprocessed_nodes.pop(layer):
  77. -> 2535                         process_node(layer, node_data)
  78.    2536
  79.    2537         name = config.get('name')
  80.  
  81. /lib/python2.7/site-packages/keras/engine/topology.pyc in process_node(layer, node_data)
  82.    2490             if input_tensors:
  83.    2491                 if len(input_tensors) == 1:
  84. -> 2492                     layer(input_tensors[0], **kwargs)
  85.    2493                 else:
  86.    2494                     layer(input_tensors, **kwargs)
  87.  
  88. /lib/python2.7/site-packages/keras/engine/topology.pyc in __call__(self, inputs, **kwargs)
  89.     590                                          '`layer.build(batch_input_shape)`')
  90.     591                 if len(input_shapes) == 1:
  91. --> 592                     self.build(input_shapes[0])
  92.     593                 else:
  93.     594                     self.build(input_shapes)
  94.  
  95. /lib/python2.7/site-packages/keras/layers/core.pyc in build(self, input_shape)
  96.     862                                       name='kernel',
  97.     863                                       regularizer=self.kernel_regularizer,
  98. --> 864                                       constraint=self.kernel_constraint)
  99.     865         if self.use_bias:
  100.     866             self.bias = self.add_weight(shape=(self.units,),
  101.  
  102. /lib/python2.7/site-packages/keras/legacy/interfaces.pyc in wrapper(*args, **kwargs)
  103.      89                 warnings.warn('Update your `' + object_name +
  104.      90                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
  105. ---> 91             return func(*args, **kwargs)
  106.      92         wrapper._original_function = func
  107.      93         return wrapper
  108.  
  109. /lib/python2.7/site-packages/keras/engine/topology.pyc in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
  110.     411         if dtype is None:
  111.     412             dtype = K.floatx()
  112. --> 413         weight = K.variable(initializer(shape),
  113.     414                             dtype=dtype,
  114.     415                             name=name,
  115.  
  116. <ipython-input-17-463931c2b557> in __call__(self, shape, dtype)
  117.       8     def __call__(self, shape, dtype=None):
  118.       9     # array filled with matrix parameter'
  119. ---> 10         return K.variable(value = self.matrix, dtype=dtype )
  120.      11
  121.      12     def get_config(self):
  122.  
  123. /lib/python2.7/site-packages/keras/backend/tensorflow_backend.pyc in variable(value, dtype, name, constraint)
  124.     394         v._uses_learning_phase = False
  125.     395         return v
  126. --> 396     v = tf.Variable(value, dtype=tf.as_dtype(dtype), name=name)
  127.     397     if isinstance(value, np.ndarray):
  128.     398         v._keras_shape = value.shape
  129.  
  130. /lib/python2.7/site-packages/tensorflow/python/ops/variables.pyc in __call__(cls, *args, **kwargs)
  131.     211   def __call__(cls, *args, **kwargs):
  132.     212     if cls is VariableV1:
  133. --> 213       return cls._variable_v1_call(*args, **kwargs)
  134.     214     elif cls is Variable:
  135.     215       return cls._variable_v2_call(*args, **kwargs)
  136.  
  137. /lib/python2.7/site-packages/tensorflow/python/ops/variables.pyc 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)
  138.     174         use_resource=use_resource,
  139.     175         synchronization=synchronization,
  140. --> 176         aggregation=aggregation)
  141.     177
  142.     178   def _variable_v2_call(cls,
  143.  
  144. /lib/python2.7/site-packages/tensorflow/python/ops/variables.pyc in <lambda>(**kwargs)
  145.     153                         aggregation=VariableAggregation.NONE):
  146.     154     """Call on Variable class. Useful to force the signature."""
  147. --> 155     previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
  148.     156     for getter in ops.get_default_graph()._variable_creator_stack:  # pylint: disable=protected-access
  149.     157       previous_getter = _make_getter(getter, previous_getter)
  150.  
  151. /lib/python2.7/site-packages/tensorflow/python/ops/variable_scope.pyc in default_variable_creator(next_creator, **kwargs)
  152.    2493         caching_device=caching_device, name=name, dtype=dtype,
  153.    2494         constraint=constraint, variable_def=variable_def,
  154. -> 2495         expected_shape=expected_shape, import_scope=import_scope)
  155.    2496
  156.    2497
  157.  
  158. /lib/python2.7/site-packages/tensorflow/python/ops/variables.pyc in __call__(cls, *args, **kwargs)
  159.     215       return cls._variable_v2_call(*args, **kwargs)
  160.     216     else:
  161. --> 217       return super(VariableMetaclass, cls).__call__(*args, **kwargs)
  162.     218
  163.     219
  164.  
  165. /lib/python2.7/site-packages/tensorflow/python/ops/variables.pyc in __init__(self, initial_value, trainable, collections, validate_shape, caching_device, name, variable_def, dtype, expected_shape, import_scope, constraint)
  166.    1393           dtype=dtype,
  167.    1394           expected_shape=expected_shape,
  168. -> 1395           constraint=constraint)
  169.    1396
  170.    1397   def __repr__(self):
  171.  
  172. /lib/python2.7/site-packages/tensorflow/python/ops/variables.pyc in _init_from_args(self, initial_value, trainable, collections, validate_shape, caching_device, name, dtype, expected_shape, constraint)
  173.    1513         else:
  174.    1514           self._initial_value = ops.convert_to_tensor(
  175. -> 1515               initial_value, name="initial_value", dtype=dtype)
  176.    1516           # pylint: disable=protected-access
  177.    1517           if self._initial_value.op._get_control_flow_context() is not None:
  178.  
  179. /lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in convert_to_tensor(value, dtype, name, preferred_dtype)
  180.    1037     ValueError: If the `value` is a tensor not of given `dtype` in graph mode.
  181.    1038   """
  182. -> 1039   return convert_to_tensor_v2(value, dtype, preferred_dtype, name)
  183.    1040
  184.    1041
  185.  
  186. /lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in convert_to_tensor_v2(value, dtype, dtype_hint, name)
  187.    1095       name=name,
  188.    1096       preferred_dtype=dtype_hint,
  189. -> 1097       as_ref=False)
  190.    1098
  191.    1099
  192.  
  193. /lib/python2.7/site-packages/tensorflow/python/framework/ops.pyc in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx, accept_symbolic_tensors)
  194.    1173
  195.    1174     if ret is None:
  196. -> 1175       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  197.    1176
  198.    1177     if ret is NotImplemented:
  199.  
  200. /lib/python2.7/site-packages/tensorflow/python/framework/constant_op.pyc in _constant_tensor_conversion_function(v, dtype, name, as_ref)
  201.     302                                          as_ref=False):
  202.     303   _ = as_ref
  203. --> 304   return constant(v, dtype=dtype, name=name)
  204.     305
  205.     306
  206.  
  207. /lib/python2.7/site-packages/tensorflow/python/framework/constant_op.pyc in constant(value, dtype, shape, name)
  208.     243   """
  209.     244   return _constant_impl(value, dtype, shape, name, verify_shape=False,
  210. --> 245                         allow_broadcast=True)
  211.     246
  212.     247
  213.  
  214. /lib/python2.7/site-packages/tensorflow/python/framework/constant_op.pyc in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
  215.     281       tensor_util.make_tensor_proto(
  216.     282           value, dtype=dtype, shape=shape, verify_shape=verify_shape,
  217. --> 283           allow_broadcast=allow_broadcast))
  218.     284   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
  219.     285   const_tensor = g.create_op(
  220.  
  221. /lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.pyc in make_tensor_proto(values, dtype, shape, verify_shape, allow_broadcast)
  222.     464       nparray = np.empty(shape, dtype=np_dt)
  223.     465     else:
  224. --> 466       _AssertCompatible(values, dtype)
  225.     467       nparray = np.array(values, dtype=np_dt)
  226.     468       # check to them.
  227.  
  228. /lib/python2.7/site-packages/tensorflow/python/framework/tensor_util.pyc in _AssertCompatible(values, dtype)
  229.     369     else:
  230.     370       raise TypeError("Expected %s, got %s of type '%s' instead." %
  231. --> 371                       (dtype.name, repr(mismatch), type(mismatch).__name__))
  232.     372
  233.     373
  234.  
  235. TypeError: Expected float32, got {u'type': u'ndarray', u'value': [[1.0, 1.0], [1.0, 1.0]]} of type 'dict' instead.
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top