problem with converting model used ResNet50 from h5 to pb in keras(Keras) Can't reload a trained resnet50 model from a h5 fileHow do tf.gradients() work?Keras Multi GPU example gives ResourceExhaustedErrorTensorflow converting keras model for tensorflowjsTensorFlow InvalidArgumentError/Value error occurs with small change of codeTensorflow - 'Unable to get element as bytes' errorAttributeError: 'Sequential' object has no attribute 'output_names'Convert trained Tensorflow model to a TensorFlow.JS model (Inception trained model)Predicting and Training in different threads Keras TensorflowAttributeError: 'Sequential' object has no attribute 'output_names'. Not toco problem

Python password manager

Accidentally deleted the "/usr/share" folder

What are the spoon bit of a spoon and fork bit of a fork called?

How to improve/restore vintage Peugeot bike, or is it even worth it?

Selecting a secure PIN for building access

Which industry am I working in? Software development or financial services?

What happens to the Time Stone

Enumerate Derangements

Would "lab meat" be able to feed a much larger global population

Does this article imply that Turing-Computability is not the same as "effectively computable"?

Why was the battle set up *outside* Winterfell?

Do I really need diodes to receive MIDI?

Alias to source .bashrc after it's been edited?

Is induction neccessary for proving that every injective mapping of a finite set into itself is a mapping onto itself?

What is the most remote airport from the center of the city it supposedly serves?

Should one double the thirds or the fifth in chords?

Do I have to make someone coauthor if he/she solves a problem in StackExchange, asked by myself, which is later used in my paper?

How to reply this mail from potential PhD professor?

In a vacuum triode, what prevents the grid from acting as another anode?

Roll Dice to get a random number between 1 and 150

CRT Oscilloscope - part of the plot is missing

Short story with physics professor who "brings back the dead" (Asimov or Bradbury?)

Should I replace my bicycle tires if they have not been inflated in multiple years

How did Arya get her dagger back from Sansa?



problem with converting model used ResNet50 from h5 to pb in keras


(Keras) Can't reload a trained resnet50 model from a h5 fileHow do tf.gradients() work?Keras Multi GPU example gives ResourceExhaustedErrorTensorflow converting keras model for tensorflowjsTensorFlow InvalidArgumentError/Value error occurs with small change of codeTensorflow - 'Unable to get element as bytes' errorAttributeError: 'Sequential' object has no attribute 'output_names'Convert trained Tensorflow model to a TensorFlow.JS model (Inception trained model)Predicting and Training in different threads Keras TensorflowAttributeError: 'Sequential' object has no attribute 'output_names'. Not toco problem






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm new to Neural Networks, and I'm familiar with keras only. I'm trying to create a model that works on Android. I have created a model that is .h5, so i need to convert it to .pb in order to run it on Android. I have a code to convert it, but the code didn't work as expected.



First of all, I have created many models using Keras that were built from scratch and I was doing some experiments with these models. The conversion code works perfectly fine with the previous models



After that, I tried to create a model using pre-trained model (ResNet50) with existing weights, you can find the pre-trained model here.



This model works obviously better because it wasn't built from scratch, but I couldn't convert it at all with the same convert code that I have.



This is the convert code I used:



import tensorflow as tf
from keras import backend as K
from keras.models import model_from_json, model_from_yaml
from tensorflow.python.tools import optimize_for_inference_lib,
freeze_graph
import keras.backend.tensorflow_backend as Q
-------------------------------------------------------------------------

model = tf.keras.models.load_model('great_model.h5')
model_name = 'model_70'
-------------------------------------------------------------------------

def export_model(saver, model, input_node_names, output_node_name):
tf.train.write_graph(K.get_session().graph_def, 'out',
model_name + '_graph.pbtxt')
saver.save(K.get_session(), 'out/' + model_name + '.chkp')

freeze_graph.freeze_graph('out/' + model_name + '_graph.pbtxt', None,
False, 'out/' + model_name + '.chkp', output_node_name,
"save/restore_all", "save/Const:0",
'out/frozen_' + model_name + '.pb', True, "")

input_graph_def = tf.GraphDef()
with tf.gfile.Open('out/frozen_' + model_name + '.pb', "rb") as f:
input_graph_def.ParseFromString(f.read())

output_graph_def = optimize_for_inference_lib.optimize_for_inference(
input_graph_def, input_node_names, [output_node_name],
tf.float32.as_datatype_enum)

with tf.gfile.FastGFile('out/opt_' + model_name + '.pb', "wb") as f:
f.write(output_graph_def.SerializeToString())

print("graph saved!")
--------------------------------------------------------------------------
export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
,"dense_2/Softmax")


Note: i got the Convert code from this GitHub.



As you might notice here:



model = tf.keras.models.load_model('great_model.h5')


I loaded the model using tensorflow included keras instead of using independent keras package, because thanks to this Stack Overflow question, I found out that when you want to load a model that has a pre-trained model in it, you shouldn't load it using an independent keras package, but use the tensorflow included keras one.



As for the error I mentioned before, here it is, a massive one:



WARNING:tensorflow:Error in loading the saved optimizer state. As a 
result, your model is starting with a freshly initialized optimizer.
Traceback (most recent call last):
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 1334, in _do_call
return fn(*args)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 1319, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 1407, in
_call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
localhost/conv1/bias/class tensorflow::Var does not exist.
[[node conv1/bias/Read/ReadVariableOp = ReadVariableOp[_class=
["loc:@conv1/bias"], dtype=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


During handling of the above exception, another exception occurred:



Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 37, in
<module>
export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
,"dense_2/Softmax")
File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 17, in
export_model
saver.save(K.get_session(), 'out/' + model_name + '.chkp')
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythontrainingsaver.py", line 1458, in save
raise exc
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythontrainingsaver.py", line 1441, in save
self.saver_def.filename_tensor_name: checkpoint_file)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 929, in run
run_metadata_ptr)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 1152, in _run
feed_dict_tensor, options, run_metadata)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 1328, in _do_run
run_metadata)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonclientsession.py", line 1348, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
localhost/conv1/bias/class tensorflow::Var does not exist.
[[node conv1/bias/Read/ReadVariableOp (defined at
C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]

Caused by op 'conv1/bias/Read/ReadVariableOp', defined at:
File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 12, in
<module>
model = tf.keras.models.load_model('great_model.h5')
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginesaving.py", line 230, in
load_model
model = model_from_config(model_config, custom_objects=custom_objects)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginesaving.py", line 310, in
model_from_config
return deserialize(config, custom_objects=custom_objects)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkeraslayersserialization.py", line 64, in
deserializeprintable_module_name='layer')
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
deserialize_keras_object list(custom_objects.items())))
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginesequential.py", line 339, in
from_config custom_objects=custom_objects)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkeraslayersserialization.py", line 64, in
deserialize printable_module_name='layer')
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
deserialize_keras_object list(custom_objects.items())))
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginenetwork.py", line 1302, in
from_config process_node(layer, node_data)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginenetwork.py", line 1260, in
process_node layer(input_tensors[0], **kwargs)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginebase_layer.py", line 746, in
__call__
self.build(input_shapes)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkeraslayersconvolutional.py", line 174, in
build dtype=self.dtype)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginebase_layer.py", line 609, in
add_weight aggregation=aggregation)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythontrainingcheckpointablebase.py", line 639, in
_add_variable_with_custom_getter
**kwargs_for_getter)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonkerasenginebase_layer.py", line 1977, in
make_variable aggregation=aggregation)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsvariables.py", line 183, in __call__
return cls._variable_v1_call(*args, **kwargs)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsvariables.py", line 146, in
_variable_v1_call aggregation=aggregation)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsvariables.py", line 125, in <lambda>
previous_getter = lambda **kwargs: default_variable_creator(None,
**kwargs)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsvariable_scope.py", line 2437, in
default_variable_creator
import_scope=import_scope)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsvariables.py", line 187, in __call__
return super(VariableMetaclass, cls).__call__(*args, **kwargs)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsresource_variable_ops.py", line 297, in
__init__
constraint=constraint)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsresource_variable_ops.py", line 449, in
_init_from_args
value = self._read_variable_op()
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsresource_variable_ops.py", line 727, in
_read_variable_op
self._dtype)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonopsgen_resource_variable_ops.py", line 563, in read_variable_op
"ReadVariableOp", resource=resource, dtype=dtype, name=name)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonframeworkop_def_library.py", line 787, in
_apply_op_helper
op_def=op_def)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonutildeprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonframeworkops.py", line 3274, in create_op
op_def=op_def)
File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
packagestensorflowpythonframeworkops.py", line 1770, in __init__
self._traceback = tf_stack.extract_stack()

FailedPreconditionError (see above for traceback): Error while reading
resource variable conv1/bias from Container: localhost. This could mean
that the variable was uninitialized. Not found: Resource
localhost/conv1/bias/class tensorflow::Var does not exist.
[[node conv1/bias/Read/ReadVariableOp (defined at
C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


The problem starts in this line in convert code:



saver.save(K.get_session(), 'out/' + model_name + '.chkp')


I think the solution has something to do with using functions with tesnorflow.keras instead of keras., but I don't know how to do it. I looked everywhere, but I couldn't find anything useful.



Is it possible to convert a model that has ResNet50 in it from .h5 to .pb?










share|improve this question






























    0















    I'm new to Neural Networks, and I'm familiar with keras only. I'm trying to create a model that works on Android. I have created a model that is .h5, so i need to convert it to .pb in order to run it on Android. I have a code to convert it, but the code didn't work as expected.



    First of all, I have created many models using Keras that were built from scratch and I was doing some experiments with these models. The conversion code works perfectly fine with the previous models



    After that, I tried to create a model using pre-trained model (ResNet50) with existing weights, you can find the pre-trained model here.



    This model works obviously better because it wasn't built from scratch, but I couldn't convert it at all with the same convert code that I have.



    This is the convert code I used:



    import tensorflow as tf
    from keras import backend as K
    from keras.models import model_from_json, model_from_yaml
    from tensorflow.python.tools import optimize_for_inference_lib,
    freeze_graph
    import keras.backend.tensorflow_backend as Q
    -------------------------------------------------------------------------

    model = tf.keras.models.load_model('great_model.h5')
    model_name = 'model_70'
    -------------------------------------------------------------------------

    def export_model(saver, model, input_node_names, output_node_name):
    tf.train.write_graph(K.get_session().graph_def, 'out',
    model_name + '_graph.pbtxt')
    saver.save(K.get_session(), 'out/' + model_name + '.chkp')

    freeze_graph.freeze_graph('out/' + model_name + '_graph.pbtxt', None,
    False, 'out/' + model_name + '.chkp', output_node_name,
    "save/restore_all", "save/Const:0",
    'out/frozen_' + model_name + '.pb', True, "")

    input_graph_def = tf.GraphDef()
    with tf.gfile.Open('out/frozen_' + model_name + '.pb', "rb") as f:
    input_graph_def.ParseFromString(f.read())

    output_graph_def = optimize_for_inference_lib.optimize_for_inference(
    input_graph_def, input_node_names, [output_node_name],
    tf.float32.as_datatype_enum)

    with tf.gfile.FastGFile('out/opt_' + model_name + '.pb', "wb") as f:
    f.write(output_graph_def.SerializeToString())

    print("graph saved!")
    --------------------------------------------------------------------------
    export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
    ,"dense_2/Softmax")


    Note: i got the Convert code from this GitHub.



    As you might notice here:



    model = tf.keras.models.load_model('great_model.h5')


    I loaded the model using tensorflow included keras instead of using independent keras package, because thanks to this Stack Overflow question, I found out that when you want to load a model that has a pre-trained model in it, you shouldn't load it using an independent keras package, but use the tensorflow included keras one.



    As for the error I mentioned before, here it is, a massive one:



    WARNING:tensorflow:Error in loading the saved optimizer state. As a 
    result, your model is starting with a freshly initialized optimizer.
    Traceback (most recent call last):
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 1334, in _do_call
    return fn(*args)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 1319, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 1407, in
    _call_tf_sessionrun
    run_metadata)
    tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
    while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
    localhost/conv1/bias/class tensorflow::Var does not exist.
    [[node conv1/bias/Read/ReadVariableOp = ReadVariableOp[_class=
    ["loc:@conv1/bias"], dtype=DT_FLOAT,
    _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


    During handling of the above exception, another exception occurred:



    Traceback (most recent call last):
    File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 37, in
    <module>
    export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
    ,"dense_2/Softmax")
    File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 17, in
    export_model
    saver.save(K.get_session(), 'out/' + model_name + '.chkp')
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythontrainingsaver.py", line 1458, in save
    raise exc
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythontrainingsaver.py", line 1441, in save
    self.saver_def.filename_tensor_name: checkpoint_file)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 929, in run
    run_metadata_ptr)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 1152, in _run
    feed_dict_tensor, options, run_metadata)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 1328, in _do_run
    run_metadata)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonclientsession.py", line 1348, in _do_call
    raise type(e)(node_def, op, message)
    tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
    while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
    localhost/conv1/bias/class tensorflow::Var does not exist.
    [[node conv1/bias/Read/ReadVariableOp (defined at
    C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
    ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
    _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]

    Caused by op 'conv1/bias/Read/ReadVariableOp', defined at:
    File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 12, in
    <module>
    model = tf.keras.models.load_model('great_model.h5')
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginesaving.py", line 230, in
    load_model
    model = model_from_config(model_config, custom_objects=custom_objects)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginesaving.py", line 310, in
    model_from_config
    return deserialize(config, custom_objects=custom_objects)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkeraslayersserialization.py", line 64, in
    deserializeprintable_module_name='layer')
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
    deserialize_keras_object list(custom_objects.items())))
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginesequential.py", line 339, in
    from_config custom_objects=custom_objects)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkeraslayersserialization.py", line 64, in
    deserialize printable_module_name='layer')
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
    deserialize_keras_object list(custom_objects.items())))
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginenetwork.py", line 1302, in
    from_config process_node(layer, node_data)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginenetwork.py", line 1260, in
    process_node layer(input_tensors[0], **kwargs)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginebase_layer.py", line 746, in
    __call__
    self.build(input_shapes)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkeraslayersconvolutional.py", line 174, in
    build dtype=self.dtype)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginebase_layer.py", line 609, in
    add_weight aggregation=aggregation)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythontrainingcheckpointablebase.py", line 639, in
    _add_variable_with_custom_getter
    **kwargs_for_getter)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonkerasenginebase_layer.py", line 1977, in
    make_variable aggregation=aggregation)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsvariables.py", line 183, in __call__
    return cls._variable_v1_call(*args, **kwargs)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsvariables.py", line 146, in
    _variable_v1_call aggregation=aggregation)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsvariables.py", line 125, in <lambda>
    previous_getter = lambda **kwargs: default_variable_creator(None,
    **kwargs)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsvariable_scope.py", line 2437, in
    default_variable_creator
    import_scope=import_scope)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsvariables.py", line 187, in __call__
    return super(VariableMetaclass, cls).__call__(*args, **kwargs)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsresource_variable_ops.py", line 297, in
    __init__
    constraint=constraint)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsresource_variable_ops.py", line 449, in
    _init_from_args
    value = self._read_variable_op()
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsresource_variable_ops.py", line 727, in
    _read_variable_op
    self._dtype)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonopsgen_resource_variable_ops.py", line 563, in read_variable_op
    "ReadVariableOp", resource=resource, dtype=dtype, name=name)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonframeworkop_def_library.py", line 787, in
    _apply_op_helper
    op_def=op_def)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonutildeprecation.py", line 488, in new_func
    return func(*args, **kwargs)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonframeworkops.py", line 3274, in create_op
    op_def=op_def)
    File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
    packagestensorflowpythonframeworkops.py", line 1770, in __init__
    self._traceback = tf_stack.extract_stack()

    FailedPreconditionError (see above for traceback): Error while reading
    resource variable conv1/bias from Container: localhost. This could mean
    that the variable was uninitialized. Not found: Resource
    localhost/conv1/bias/class tensorflow::Var does not exist.
    [[node conv1/bias/Read/ReadVariableOp (defined at
    C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
    ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
    _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


    The problem starts in this line in convert code:



    saver.save(K.get_session(), 'out/' + model_name + '.chkp')


    I think the solution has something to do with using functions with tesnorflow.keras instead of keras., but I don't know how to do it. I looked everywhere, but I couldn't find anything useful.



    Is it possible to convert a model that has ResNet50 in it from .h5 to .pb?










    share|improve this question


























      0












      0








      0








      I'm new to Neural Networks, and I'm familiar with keras only. I'm trying to create a model that works on Android. I have created a model that is .h5, so i need to convert it to .pb in order to run it on Android. I have a code to convert it, but the code didn't work as expected.



      First of all, I have created many models using Keras that were built from scratch and I was doing some experiments with these models. The conversion code works perfectly fine with the previous models



      After that, I tried to create a model using pre-trained model (ResNet50) with existing weights, you can find the pre-trained model here.



      This model works obviously better because it wasn't built from scratch, but I couldn't convert it at all with the same convert code that I have.



      This is the convert code I used:



      import tensorflow as tf
      from keras import backend as K
      from keras.models import model_from_json, model_from_yaml
      from tensorflow.python.tools import optimize_for_inference_lib,
      freeze_graph
      import keras.backend.tensorflow_backend as Q
      -------------------------------------------------------------------------

      model = tf.keras.models.load_model('great_model.h5')
      model_name = 'model_70'
      -------------------------------------------------------------------------

      def export_model(saver, model, input_node_names, output_node_name):
      tf.train.write_graph(K.get_session().graph_def, 'out',
      model_name + '_graph.pbtxt')
      saver.save(K.get_session(), 'out/' + model_name + '.chkp')

      freeze_graph.freeze_graph('out/' + model_name + '_graph.pbtxt', None,
      False, 'out/' + model_name + '.chkp', output_node_name,
      "save/restore_all", "save/Const:0",
      'out/frozen_' + model_name + '.pb', True, "")

      input_graph_def = tf.GraphDef()
      with tf.gfile.Open('out/frozen_' + model_name + '.pb', "rb") as f:
      input_graph_def.ParseFromString(f.read())

      output_graph_def = optimize_for_inference_lib.optimize_for_inference(
      input_graph_def, input_node_names, [output_node_name],
      tf.float32.as_datatype_enum)

      with tf.gfile.FastGFile('out/opt_' + model_name + '.pb', "wb") as f:
      f.write(output_graph_def.SerializeToString())

      print("graph saved!")
      --------------------------------------------------------------------------
      export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
      ,"dense_2/Softmax")


      Note: i got the Convert code from this GitHub.



      As you might notice here:



      model = tf.keras.models.load_model('great_model.h5')


      I loaded the model using tensorflow included keras instead of using independent keras package, because thanks to this Stack Overflow question, I found out that when you want to load a model that has a pre-trained model in it, you shouldn't load it using an independent keras package, but use the tensorflow included keras one.



      As for the error I mentioned before, here it is, a massive one:



      WARNING:tensorflow:Error in loading the saved optimizer state. As a 
      result, your model is starting with a freshly initialized optimizer.
      Traceback (most recent call last):
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1334, in _do_call
      return fn(*args)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1319, in _run_fn
      options, feed_dict, fetch_list, target_list, run_metadata)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1407, in
      _call_tf_sessionrun
      run_metadata)
      tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
      while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
      localhost/conv1/bias/class tensorflow::Var does not exist.
      [[node conv1/bias/Read/ReadVariableOp = ReadVariableOp[_class=
      ["loc:@conv1/bias"], dtype=DT_FLOAT,
      _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


      During handling of the above exception, another exception occurred:



      Traceback (most recent call last):
      File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 37, in
      <module>
      export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
      ,"dense_2/Softmax")
      File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 17, in
      export_model
      saver.save(K.get_session(), 'out/' + model_name + '.chkp')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythontrainingsaver.py", line 1458, in save
      raise exc
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythontrainingsaver.py", line 1441, in save
      self.saver_def.filename_tensor_name: checkpoint_file)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 929, in run
      run_metadata_ptr)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1152, in _run
      feed_dict_tensor, options, run_metadata)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1328, in _do_run
      run_metadata)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1348, in _do_call
      raise type(e)(node_def, op, message)
      tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
      while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
      localhost/conv1/bias/class tensorflow::Var does not exist.
      [[node conv1/bias/Read/ReadVariableOp (defined at
      C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
      ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
      _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]

      Caused by op 'conv1/bias/Read/ReadVariableOp', defined at:
      File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 12, in
      <module>
      model = tf.keras.models.load_model('great_model.h5')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginesaving.py", line 230, in
      load_model
      model = model_from_config(model_config, custom_objects=custom_objects)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginesaving.py", line 310, in
      model_from_config
      return deserialize(config, custom_objects=custom_objects)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkeraslayersserialization.py", line 64, in
      deserializeprintable_module_name='layer')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
      deserialize_keras_object list(custom_objects.items())))
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginesequential.py", line 339, in
      from_config custom_objects=custom_objects)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkeraslayersserialization.py", line 64, in
      deserialize printable_module_name='layer')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
      deserialize_keras_object list(custom_objects.items())))
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginenetwork.py", line 1302, in
      from_config process_node(layer, node_data)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginenetwork.py", line 1260, in
      process_node layer(input_tensors[0], **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginebase_layer.py", line 746, in
      __call__
      self.build(input_shapes)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkeraslayersconvolutional.py", line 174, in
      build dtype=self.dtype)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginebase_layer.py", line 609, in
      add_weight aggregation=aggregation)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythontrainingcheckpointablebase.py", line 639, in
      _add_variable_with_custom_getter
      **kwargs_for_getter)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginebase_layer.py", line 1977, in
      make_variable aggregation=aggregation)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 183, in __call__
      return cls._variable_v1_call(*args, **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 146, in
      _variable_v1_call aggregation=aggregation)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 125, in <lambda>
      previous_getter = lambda **kwargs: default_variable_creator(None,
      **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariable_scope.py", line 2437, in
      default_variable_creator
      import_scope=import_scope)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 187, in __call__
      return super(VariableMetaclass, cls).__call__(*args, **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsresource_variable_ops.py", line 297, in
      __init__
      constraint=constraint)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsresource_variable_ops.py", line 449, in
      _init_from_args
      value = self._read_variable_op()
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsresource_variable_ops.py", line 727, in
      _read_variable_op
      self._dtype)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsgen_resource_variable_ops.py", line 563, in read_variable_op
      "ReadVariableOp", resource=resource, dtype=dtype, name=name)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonframeworkop_def_library.py", line 787, in
      _apply_op_helper
      op_def=op_def)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonutildeprecation.py", line 488, in new_func
      return func(*args, **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonframeworkops.py", line 3274, in create_op
      op_def=op_def)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonframeworkops.py", line 1770, in __init__
      self._traceback = tf_stack.extract_stack()

      FailedPreconditionError (see above for traceback): Error while reading
      resource variable conv1/bias from Container: localhost. This could mean
      that the variable was uninitialized. Not found: Resource
      localhost/conv1/bias/class tensorflow::Var does not exist.
      [[node conv1/bias/Read/ReadVariableOp (defined at
      C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
      ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
      _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


      The problem starts in this line in convert code:



      saver.save(K.get_session(), 'out/' + model_name + '.chkp')


      I think the solution has something to do with using functions with tesnorflow.keras instead of keras., but I don't know how to do it. I looked everywhere, but I couldn't find anything useful.



      Is it possible to convert a model that has ResNet50 in it from .h5 to .pb?










      share|improve this question
















      I'm new to Neural Networks, and I'm familiar with keras only. I'm trying to create a model that works on Android. I have created a model that is .h5, so i need to convert it to .pb in order to run it on Android. I have a code to convert it, but the code didn't work as expected.



      First of all, I have created many models using Keras that were built from scratch and I was doing some experiments with these models. The conversion code works perfectly fine with the previous models



      After that, I tried to create a model using pre-trained model (ResNet50) with existing weights, you can find the pre-trained model here.



      This model works obviously better because it wasn't built from scratch, but I couldn't convert it at all with the same convert code that I have.



      This is the convert code I used:



      import tensorflow as tf
      from keras import backend as K
      from keras.models import model_from_json, model_from_yaml
      from tensorflow.python.tools import optimize_for_inference_lib,
      freeze_graph
      import keras.backend.tensorflow_backend as Q
      -------------------------------------------------------------------------

      model = tf.keras.models.load_model('great_model.h5')
      model_name = 'model_70'
      -------------------------------------------------------------------------

      def export_model(saver, model, input_node_names, output_node_name):
      tf.train.write_graph(K.get_session().graph_def, 'out',
      model_name + '_graph.pbtxt')
      saver.save(K.get_session(), 'out/' + model_name + '.chkp')

      freeze_graph.freeze_graph('out/' + model_name + '_graph.pbtxt', None,
      False, 'out/' + model_name + '.chkp', output_node_name,
      "save/restore_all", "save/Const:0",
      'out/frozen_' + model_name + '.pb', True, "")

      input_graph_def = tf.GraphDef()
      with tf.gfile.Open('out/frozen_' + model_name + '.pb', "rb") as f:
      input_graph_def.ParseFromString(f.read())

      output_graph_def = optimize_for_inference_lib.optimize_for_inference(
      input_graph_def, input_node_names, [output_node_name],
      tf.float32.as_datatype_enum)

      with tf.gfile.FastGFile('out/opt_' + model_name + '.pb', "wb") as f:
      f.write(output_graph_def.SerializeToString())

      print("graph saved!")
      --------------------------------------------------------------------------
      export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
      ,"dense_2/Softmax")


      Note: i got the Convert code from this GitHub.



      As you might notice here:



      model = tf.keras.models.load_model('great_model.h5')


      I loaded the model using tensorflow included keras instead of using independent keras package, because thanks to this Stack Overflow question, I found out that when you want to load a model that has a pre-trained model in it, you shouldn't load it using an independent keras package, but use the tensorflow included keras one.



      As for the error I mentioned before, here it is, a massive one:



      WARNING:tensorflow:Error in loading the saved optimizer state. As a 
      result, your model is starting with a freshly initialized optimizer.
      Traceback (most recent call last):
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1334, in _do_call
      return fn(*args)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1319, in _run_fn
      options, feed_dict, fetch_list, target_list, run_metadata)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1407, in
      _call_tf_sessionrun
      run_metadata)
      tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
      while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
      localhost/conv1/bias/class tensorflow::Var does not exist.
      [[node conv1/bias/Read/ReadVariableOp = ReadVariableOp[_class=
      ["loc:@conv1/bias"], dtype=DT_FLOAT,
      _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


      During handling of the above exception, another exception occurred:



      Traceback (most recent call last):
      File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 37, in
      <module>
      export_model(tf.train.Saver() ,model ,["conv2d_1_input"]
      ,"dense_2/Softmax")
      File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 17, in
      export_model
      saver.save(K.get_session(), 'out/' + model_name + '.chkp')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythontrainingsaver.py", line 1458, in save
      raise exc
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythontrainingsaver.py", line 1441, in save
      self.saver_def.filename_tensor_name: checkpoint_file)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 929, in run
      run_metadata_ptr)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1152, in _run
      feed_dict_tensor, options, run_metadata)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1328, in _do_run
      run_metadata)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonclientsession.py", line 1348, in _do_call
      raise type(e)(node_def, op, message)
      tensorflow.python.framework.errors_impl.FailedPreconditionError: Error
      while reading resource variable conv1/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource
      localhost/conv1/bias/class tensorflow::Var does not exist.
      [[node conv1/bias/Read/ReadVariableOp (defined at
      C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
      ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
      _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]

      Caused by op 'conv1/bias/Read/ReadVariableOp', defined at:
      File "C:/Users/User/PycharmProjects/tensorflow/convert.py", line 12, in
      <module>
      model = tf.keras.models.load_model('great_model.h5')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginesaving.py", line 230, in
      load_model
      model = model_from_config(model_config, custom_objects=custom_objects)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginesaving.py", line 310, in
      model_from_config
      return deserialize(config, custom_objects=custom_objects)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkeraslayersserialization.py", line 64, in
      deserializeprintable_module_name='layer')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
      deserialize_keras_object list(custom_objects.items())))
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginesequential.py", line 339, in
      from_config custom_objects=custom_objects)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkeraslayersserialization.py", line 64, in
      deserialize printable_module_name='layer')
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasutilsgeneric_utils.py", line 173, in
      deserialize_keras_object list(custom_objects.items())))
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginenetwork.py", line 1302, in
      from_config process_node(layer, node_data)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginenetwork.py", line 1260, in
      process_node layer(input_tensors[0], **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginebase_layer.py", line 746, in
      __call__
      self.build(input_shapes)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkeraslayersconvolutional.py", line 174, in
      build dtype=self.dtype)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginebase_layer.py", line 609, in
      add_weight aggregation=aggregation)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythontrainingcheckpointablebase.py", line 639, in
      _add_variable_with_custom_getter
      **kwargs_for_getter)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonkerasenginebase_layer.py", line 1977, in
      make_variable aggregation=aggregation)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 183, in __call__
      return cls._variable_v1_call(*args, **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 146, in
      _variable_v1_call aggregation=aggregation)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 125, in <lambda>
      previous_getter = lambda **kwargs: default_variable_creator(None,
      **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariable_scope.py", line 2437, in
      default_variable_creator
      import_scope=import_scope)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsvariables.py", line 187, in __call__
      return super(VariableMetaclass, cls).__call__(*args, **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsresource_variable_ops.py", line 297, in
      __init__
      constraint=constraint)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsresource_variable_ops.py", line 449, in
      _init_from_args
      value = self._read_variable_op()
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsresource_variable_ops.py", line 727, in
      _read_variable_op
      self._dtype)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonopsgen_resource_variable_ops.py", line 563, in read_variable_op
      "ReadVariableOp", resource=resource, dtype=dtype, name=name)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonframeworkop_def_library.py", line 787, in
      _apply_op_helper
      op_def=op_def)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonutildeprecation.py", line 488, in new_func
      return func(*args, **kwargs)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonframeworkops.py", line 3274, in create_op
      op_def=op_def)
      File "C:UsersUserAppDataLocalProgramsPythonPython36libsite-
      packagestensorflowpythonframeworkops.py", line 1770, in __init__
      self._traceback = tf_stack.extract_stack()

      FailedPreconditionError (see above for traceback): Error while reading
      resource variable conv1/bias from Container: localhost. This could mean
      that the variable was uninitialized. Not found: Resource
      localhost/conv1/bias/class tensorflow::Var does not exist.
      [[node conv1/bias/Read/ReadVariableOp (defined at
      C:/Users/User/PycharmProjects/tensorflow/convert.py:12) =
      ReadVariableOp[_class=["loc:@conv1/bias"], dtype=DT_FLOAT,
      _device="/job:localhost/replica:0/task:0/device:CPU:0"](conv1/bias)]]


      The problem starts in this line in convert code:



      saver.save(K.get_session(), 'out/' + model_name + '.chkp')


      I think the solution has something to do with using functions with tesnorflow.keras instead of keras., but I don't know how to do it. I looked everywhere, but I couldn't find anything useful.



      Is it possible to convert a model that has ResNet50 in it from .h5 to .pb?







      python tensorflow keras deep-learning resnet






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 22 at 22:05









      karel

      2,35392832




      2,35392832










      asked Mar 22 at 21:18









      CayldenCaylden

      12




      12






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307911%2fproblem-with-converting-model-used-resnet50-from-h5-to-pb-in-keras%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307911%2fproblem-with-converting-model-used-resnet50-from-h5-to-pb-in-keras%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현