前言:
Keras是一個由Python編寫的開源人工神經網絡庫,可以作為Tensorflow、Microsoft-CNTK和Theano的高階應用程序接口,進行深度學習模型的設計、調試、評估、應用和可視化。
Theano于2008年誕生于蒙特利爾理工學院,其派生出了大量的深度學習Python軟件包,最著名的包括Blocks和Keras。Theano的核心是一個數學表達式的編譯器,它知道如何獲取你的結構,并使之成為一個使用numpy、高效本地庫的高效代碼,如BLAS和本地代碼(C++)在CPU或GPU上盡可能快地運行。它是為深度學習中處理大型神經網絡算法所需的計算而專門設計,是這類庫的首創之一(發展始于2007年),被認為是深度學習研究和開發的行業標準。
TensorFlow是一個基于數據流編程(dataflow programming)的符號數學系統,被廣泛應用于各類機器學習(machine learning)算法的編程實現,其前身是谷歌的神經網絡算法庫DistBelief。
Tensorflow擁有多層級結構,可部署于各類服務器、PC終端和網頁并支持GPU和TPU高性能數值計算,被廣泛應用于谷歌內部的產品開發和各領域的科學研究。
代碼:
</pre><pre code_snippet_id="1947416" snippet_file_name="blog_20161025_1_3331239" name="code" class="python">
# coding:utf-8 """ If you want to load pre-trained weights that include convolutions (layers Convolution2D or Convolution1D), be mindful of this: Theano and TensorFlow implement convolution in different ways (TensorFlow actually implements correlation, much like Caffe), and thus, convolution kernels trained with Theano (resp. TensorFlow) need to be converted before being with TensorFlow (resp. Theano). """ from keras import backend as K from keras.utils.np_utils import convert_kernel from text_classifier import keras_text_classifier import sys def th3tf( model): import tensorflow as tf ops = [] for layer in model.layers: if layer.__class__.__name__ in ['Convolution1D', 'Convolution2D']: original_w = K.get_value(layer.W) converted_w = convert_kernel(original_w) ops.append(tf.assign(layer.W, converted_w).op) K.get_session().run(ops) return model def tf2th(model): for layer in model.layers: if layer.__class__.__name__ in ['Convolution1D', 'Convolution2D']: original_w = K.get_value(layer.W) converted_w = convert_kernel(original_w) K.set_value(layer.W, converted_w) return model def conv_layer_converted(tf_weights, th_weights, m = 0): """ :param tf_weights: :param th_weights: :param m: 0-tf2th, 1-th3tf :return: """ if m == 0: # tf2th tc = keras_text_classifier(weights_path=tf_weights) model = tc.loadmodel() model = tf2th(model) model.save_weights(th_weights) elif m == 1: # th3tf tc = keras_text_classifier(weights_path=th_weights) model = tc.loadmodel() model = th3tf(model) model.save_weights(tf_weights) else: print("0-tf2th, 1-th3tf") return if __name__ == '__main__': if len(sys.argv) < 4: print("python tf_weights th_weights <0|1>\n0-tensorflow to theano\n1-theano to tensorflow") sys.exit(0) tf_weights = sys.argv[1] th_weights = sys.argv[2] m = int(sys.argv[3]) conv_layer_converted(tf_weights, th_weights, m)
補充知識:keras學習之修改底層為TensorFlow還是theano
我們知道,keras的底層是TensorFlow或者theano
要知道我們是用的哪個為底層,只需要import keras即可顯示
修改方法:
打開
修改
以上這篇keras實現theano和tensorflow訓練的模型相互轉換就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。