def load_model_from_file(hdf5_model_filepath, display_summary=True): """ Load model from file """ hdf5_file = h5py.File(hdf5_model_filepath, mode='r') model = model_pb2.Model() model.id = str(uuid.uuid4()) model.name = 'MyModel' model.keras_version = hdf5_file.attrs['keras_version'] model.backend = hdf5_file.attrs['backend'] model.model_config = hdf5_file.attrs['model_config'] f = hdf5_file['model_weights'] layers = {} for layer_name in f.attrs['layer_names']: g = f[layer_name] layers[layer_name] = {} for weight_name in g.attrs['weight_names']: weight_value = g[weight_name].value layers[layer_name][weight_name] = weight_value hdf5_file.close() conv_layer_weights = layers[b'conv2d'][b'conv2d/kernel:0'] conv_layer_biases = layers[b'conv2d'][b'conv2d/bias:0'] dense_layer_weights = layers[b'dense'][b'dense/kernel:0'] dense_layer_biases = layers[b'dense'][b'dense/bias:0'] pred_layer_weights = layers[b'pred'][b'pred/kernel:0'] pred_layer_biases = layers[b'pred'][b'pred/bias:0'] if (display_summary): print("Model Summary:") print("=========================") print(f"Conv Layer: \nweight shape: {conv_layer_weights.shape}\nbias shape: {conv_layer_biases.shape} ") print(f"Dense Layer: \nweight shape: {dense_layer_weights.shape}\nbias shape: {dense_layer_biases.shape} ") print(f"Pred Layer: \nweight shape: {pred_layer_weights.shape}\nbias shape: {pred_layer_biases.shape} ") return layers
def main(): model = mpb2.Model() model.type = "cnn" conv1 = model.function.add() max_pool1 = model.function.add() relu1 = model.function.add() conv2 = model.function.add() conv2_drop = model.function.add() max_pool2 = model.function.add() relu2 = model.function.add() view = model.function.add() fc1 = model.function.add() relu3 = model.function.add() dropout = model.function.add() fc2 = model.function.add() log_softmax = model.function.add() conv1.function = "Conv2d" conv1.init_arg.extend(["1", "10", "5"]) max_pool1.function = "max_pool2d" max_pool1.inp.extend(["2"]) relu1.function = "relu" conv2.function = "Conv2d" conv2.init_arg.extend(["10", "20", "5"]); conv2_drop.function = "Dropout2d" conv2_drop.init_arg.extend([""]) max_pool2.function = "max_pool2d" max_pool2.inp.extend(["2"]) relu2.function = "relu" view.function = "view" view.init_arg.extend(["-1", "num_flat_features"]) fc1.function = "Linear" fc1.init_arg.extend(["num_flat_features", "50"]) relu3.function = "relu" dropout.function = "dropout" dropout.inp.extend(["0.5","training", "False"]) fc2.function = "Linear" fc2.init_arg.extend(["50", "10"]) log_softmax.function = "log_softmax" log_softmax.inp.extend(["1"]) # Write the new model to disk. f = open(sys.argv[1], "wb+") f.write(model.SerializeToString()) f.close()
def create_model(self): """Initializes a model from the protobuf definition. """ self.model = model_pb2.Model() self.model.id = str(uuid.uuid4()) self.model.name = self.name
def read_proto_model(file): model = mpb2.Model() f = open(file, "rb") model.ParseFromString(f.read()) return model