def inspect_model(model): """Print the structure of Keras `model`.""" for i, l in enumerate(model.layers): print(i, 'cls={} name={}'.format(type(l).__name__, l.name)) weights = l.get_weights() print_str = '' for weight in weights: print_str += str_shape(weight) + ' ' print(print_str) print()
def load_weights(model, filepath): """Load all weights possible into model from filepath. This is a modified version of keras load_weights that loads as much as it can if there is a mismatch between file and model. It returns the weights of the first layer in which the mismatch has happened """ print('Loading', filepath, 'to', model.name) with h5py.File(filepath, mode='r') as f: # new file format layer_names = [n.decode('utf8') for n in f.attrs['layer_names']] # we batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for name in layer_names: print(name) g = f[name] weight_names = [n.decode('utf8') for n in g.attrs['weight_names']] if len(weight_names): weight_values = [ g[weight_name] for weight_name in weight_names ] try: layer = model.get_layer(name=name) except: layer = None if not layer: print('failed to find layer', name, 'in model') print('weights', ' '.join(str_shape(w) for w in weight_values)) print('stopping to load all other layers') weight_values = [np.array(w) for w in weight_values] break symbolic_weights = layer.trainable_weights + layer.non_trainable_weights weight_value_tuples += zip(symbolic_weights, weight_values) weight_values = None K.batch_set_value(weight_value_tuples) return weight_values
def load_weights(model, filepath): """Load all weights possible into model from filepath. This is a modified version of keras load_weights that loads as much as it can if there is a mismatch between file and model. It returns the weights of the first layer in which the mismatch has happened """ print('Loading', filepath, 'to', model.name) with h5py.File(filepath, mode='r') as f: # new file format layer_names = [n.decode('utf8') for n in f.attrs['layer_names']] # we batch weight value assignments in a single backend call # which provides a speedup in TensorFlow. weight_value_tuples = [] for name in layer_names: print(name) g = f[name] weight_names = [n.decode('utf8') for n in g.attrs['weight_names']] if len(weight_names): weight_values = [g[weight_name] for weight_name in weight_names] try: layer = model.get_layer(name=name) except: layer = None if not layer: print('failed to find layer', name, 'in model') print('weights', ' '.join(str_shape(w) for w in weight_values)) print('stopping to load all other layers') weight_values = [np.array(w) for w in weight_values] break symbolic_weights = layer.trainable_weights + layer.non_trainable_weights weight_value_tuples += zip(symbolic_weights, weight_values) weight_values = None K.batch_set_value(weight_value_tuples) return weight_values