public void copyWeightsToLayer ( org . deeplearning4j . nn . api . Layer layer ) throws InvalidKerasConfigurationException { if ( this . getNumParams ( ) > 0 ) { String dl4jLayerName = layer . conf ( ) . getLayer ( ) . getLayerName ( ) ; String kerasLayerName = this . getLayerName ( ) ; String msg = "Error when attempting to copy weights from Keras layer " + kerasLayerName + " to DL4J layer " + dl4jLayerName ; if ( getWeights ( ) == null ) throw new InvalidKerasConfigurationException ( msg + "(weights is null)" ) ; Set < String > paramsInLayer = new HashSet <> ( layer . paramTable ( ) . keySet ( ) ) ; Set < String > paramsInKerasLayer = new HashSet <> ( this . weights . keySet ( ) ) ; /* Check for parameters in layer for which we don't have weights. */ paramsInLayer . removeAll ( paramsInKerasLayer ) ; if ( ! paramsInLayer . isEmpty ( ) ) { String joinedParamsInLayer = StringUtils . join ( paramsInLayer , ", " ) ; throw new InvalidKerasConfigurationException ( msg + "(no stored weights for parameters: " + joinedParamsInLayer + ")" ) ; } /* Check for parameters NOT in layer for which we DO have weights. */ paramsInKerasLayer . removeAll ( layer . paramTable ( ) . keySet ( ) ) ; if ( ! paramsInKerasLayer . isEmpty ( ) ) { String joinedParamsInKerasLayer = StringUtils . join ( paramsInKerasLayer , ", " ) ; throw new InvalidKerasConfigurationException ( msg + "(found no parameters named: " + joinedParamsInKerasLayer + ")" ) ; } /* Copy weights. */ for ( String paramName : layer . paramTable ( ) . keySet ( ) ) { try { layer . setParam ( paramName , this . weights . get ( paramName ) ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) ) ; throw new InvalidKerasConfigurationException ( e . getMessage ( ) + "\nTried to set weights for layer with name " + this . getLayerName ( ) + ", of " + layer . conf ( ) . getLayer ( ) . getClass ( ) + ".\n" + "Failed to set weights for parameter " + paramName + "\n" + "Expected shape for this parameter: " + layer . getParam ( paramName ) . shapeInfoToString ( ) + ", \ngot: " + this . weights . get ( paramName ) . shapeInfoToString ( ) ) ; } } } }
Copy Keras layer weights to DL4J Layer .