public static Model copyWeightsToModel ( Model model , Map < String , KerasLayer > kerasLayers ) throws InvalidKerasConfigurationException { /* Get list if layers from model. */ Layer [ ] layersFromModel ; if ( model instanceof MultiLayerNetwork ) layersFromModel = ( ( MultiLayerNetwork ) model ) . getLayers ( ) ; else layersFromModel = ( ( ComputationGraph ) model ) . getLayers ( ) ; /* Iterate over layers in model, setting weights when relevant. */ Set < String > layerNames = new HashSet <> ( kerasLayers . keySet ( ) ) ; for ( org . deeplearning4j . nn . api . Layer layer : layersFromModel ) { String layerName = layer . conf ( ) . getLayer ( ) . getLayerName ( ) ; if ( ! kerasLayers . containsKey ( layerName ) ) throw new InvalidKerasConfigurationException ( "No weights found for layer in model (named " + layerName + ")" ) ; kerasLayers . get ( layerName ) . copyWeightsToLayer ( layer ) ; layerNames . remove ( layerName ) ; } for ( String layerName : layerNames ) { if ( kerasLayers . get ( layerName ) . getNumParams ( ) > 0 ) throw new InvalidKerasConfigurationException ( "Attemping to copy weights for layer not in model (named " + layerName + ")" ) ; } return model ; }
Helper function to import weights from nested Map into existing model . Depends critically on matched layer and parameter names . In general this seems to be straightforward for most Keras models and layersOrdered but there may be edge cases .