[英]Can a Tensorflow variable be trained using the Tensorflow Keras functional API model? Can a Tensorflow operation be used in the functional API Model?
我想知道Keras模型是否使用由tf.get_variable
定義的功能性API訓練變量進行編譯/訓練? Keras培訓還可以合並Tensorflow操作嗎?
所以基本上我想用Tensorflow變量和操作定義Keras模型,然后使用
model = tf.keras.Model(inputs=inputs, outputs=predictions)
model.compile(optimizer=optimizer, loss=loss)
model.fit(data, labels, batch_size=batch_size, epochs=epochs)
訓練模型。 原因是Google的TPU需要Keras或TF.Estimator API,更推薦使用Keras,因此,我希望了解如何輕松轉換模型。
由於Tensorflow是后端,因此看起來有多種混合Keras / Tensorflow變量的方法。 這篇博客文章展示了如何使用Tensorflow圖/會話https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html訓練Keras變量
from keras.layers import Dropout
from keras import backend as K
img = tf.placeholder(tf.float32, shape=(None, 784))
labels = tf.placeholder(tf.float32, shape=(None, 10))
x = Dense(128, activation='relu')(img)
x = Dropout(0.5)(x)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
preds = Dense(10, activation='softmax')(x)
loss = tf.reduce_mean(categorical_crossentropy(labels, preds))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
with sess.as_default():
for i in range(100):
batch = mnist_data.train.next_batch(50)
train_step.run(feed_dict={img: batch[0],
labels: batch[1],
K.learning_phase(): 1})
acc_value = accuracy(labels, preds)
with sess.as_default():
print acc_value.eval(feed_dict={img: mnist_data.test.images,
labels: mnist_data.test.labels,
K.learning_phase(): 0})
而且這里還顯示Tensorflow變量可以用作Keras模型的輸入
如何使用Tensorflow張量設置功能模型的Keras層的輸入?
tf_embedding_input = ... # pre-processing output tensor
# Keras model
model = Sequential()
model.add(Input(tensor=tf_embedding_input))
model.add(Embedding(max_features, 128, input_length=maxlen))
所以我想知道Keras是否可以訓練Tensorflow變量。
我想在下面的Tensorflow體系結構中訓練embedding和softmax變量
embeddings = tf.get_variable( 'embeddings',
initializer= tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
softmax_weights = tf.get_variable( 'softmax_weights',
initializer= tf.truncated_normal([vocabulary_size, embedding_size],
stddev=1.0 / math.sqrt(embedding_size)))
softmax_biases = tf.get_variable('softmax_biases',
initializer= tf.zeros([vocabulary_size]), trainable=False )
embed = tf.nn.embedding_lookup(embeddings, train_dataset) #train data set is
embed_reshaped = tf.reshape( embed, [batch_size*num_inputs, embedding_size] )
segments= np.arange(batch_size).repeat(num_inputs)
averaged_embeds = tf.segment_mean(embed_reshaped, segments, name=None)
loss = tf.reduce_mean(
tf.nn.sampled_softmax_loss(weights=softmax_weights, biases=softmax_biases, inputs=averaged_embeds,
labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size))
由於Tensorflow Keras使用Tensorflow后端,我猜想在某種程度上可以使用和訓練Tensorflow變量,並在訓練中使用Tensorflow操作。
Google的TPU要求您的架構必須通過Estimator API或Keras API實現。 由於更推薦使用Keras API,因此可能有興趣將常規Tensorflow圖形/會話轉換為使用Keras API,並且對其代碼的更改盡可能少。
知道如何使用Keras模型編譯/訓練來合並Tensorflow操作並訓練Tensorflow變量將對此有很大幫助。
小背景:
眾所周知,Keras是一個模型級庫,為開發深度學習模型提供了高級構建塊。
最重要的是:Keras API不處理張量操作。 為此,它需要一個經過優化的張量操縱庫,被稱為Keras的“后端引擎”。
目前,Keras提供了三種后端引擎:TensorFlow后端(Google),Theano后端和CNTK后端(MSFT)。
知道如何使用Keras模型編譯/訓練來合並Tensorflow操作並訓練Tensorflow變量將對此有很大幫助。
您唯一要問自己的是Keras變量和常規Tensorflow變量之間的區別是什么。
可能是Keras變量具有元數據。 因此,為了在Keras中使用TensorFlow變量,需要對其進行轉換。
注意:TensorFlow變量作用域對Keras層或模型沒有影響。
最后,可以通過初始化Keras層(或模型)來完成變量共享。
該解決方案有幫助嗎?
您可以使用以下方式將嵌入和softmax圖層輸入Keras模型
model.add()
然后使用定義這些變量為可訓練的
model.layers[-1].trainable_weights.extend()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.