Keras switch backend: theano --> tensorflow

1. Switch the backend and modify the theano field in the ~/ .keras
/keras.json file to tensorflow.
Official document: https://keras.io/backend/ The operation will go wrong because the convolution in tensorflow is actually related, and the convolution in theano is the real convolution! ! ! ! Therefore, when switching backend, the convolution kernel needs to be flipped. See : https://github.com/fchollet/keras/wiki/Converting-convolution-kernels-from-Theano-to-TensorFlow-and-vice-versa general conversion The code is as follows (theano and tensorflow are converted to each other):








from keras import backend as K
from keras.utils.np_utils import convert_kernel

model = model_from_json(open(os.path.join('.', 'model.json')).read())
model.load_weights(os.path.join('.',  'model_weights.h5'))



for layer in model.layers:
   if layer.__class__.__name__ in ['Convolution1D', 'Convolution2D','Convolution3D', 'AtrousConvolution2D']:
      original_w = K.get_value(layer.W)
      converted_w = convert_kernel(original_w)
      K.set_value(layer.W, converted_w)


print('running')   
K.get_session().run(ops)
print('saving')    
model.save_weights('model_weights_anotherBackend.h5')


The tensoflow dedicated conversion code is as follows:
from keras import backend as K
from keras.utils.np_utils import convert_kernel
import tensorflow as tf

model = model_from_json(open(os.path.join('.', 'model.json')).read())
model.load_weights(os.path.join('.',  'model_weights.h5'))
ops = []
for layer in model.layers:
    if layer.__class__.__name__ in ['Convolution1D', 'Convolution2D', 'Convolution3D', 'AtrousConvolution2D']:
        original_w = K.get_value(layer.W)
        print(layer.W.name)
        print('\t',end='')
        print(layer.W.get_shape().to_list())
        converted_w = convert_kernel(original_w)
        ops.append(tf.assign(layer.W, converted_w).op)

print('running')   
K.get_session().run(ops)
print('saving')    
model.save_weights('model_weights_tensorflow.h5')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326485515&siteId=291194637