无法在Tensorflow工作流程中冻结Keras图层

时间:2017-05-16 11:49:14

标签: tensorflow keras

我正在尝试在Tensorflow工作流程中冻结Keras图层。这就是我定义图表的方式:

import tensorflow as tf
from keras.layers import Dropout, Dense, Embedding, Flatten
from keras import backend as K
from keras.objectives import binary_crossentropy


import tensorflow as tf
sess = tf.Session()

from keras import backend as K
K.set_session(sess)

labels = tf.placeholder(tf.float32, shape=(None, 1))
user_id_input = tf.placeholder(tf.float32, shape=(None, 1))
item_id_input = tf.placeholder(tf.float32, shape=(None, 1))



max_user_id = all_ratings['user_id'].max()
max_item_id = all_ratings['item_id'].max()

embedding_size = 30
user_embedding = Embedding(output_dim=embedding_size, input_dim=max_user_id+1,
                           input_length=1, name='user_embedding', trainable=all_trainable)(user_id_input)
item_embedding = Embedding(output_dim=embedding_size, input_dim=max_item_id+1,
                           input_length=1, name='item_embedding', trainable=all_trainable)(item_id_input)



user_vecs = Flatten()(user_embedding)
item_vecs = Flatten()(item_embedding)


input_vecs = concatenate([user_vecs, item_vecs])

x = Dense(30, activation='relu')(input_vecs)
x1 = Dropout(0.5)(x)
x2 = Dense(30, activation='relu')(x1)
y = Dense(1, activation='sigmoid')(x2)

loss = tf.reduce_mean(binary_crossentropy(labels, y))

train_step = tf.train.AdamOptimizer(0.004).minimize(loss)

然后我只训练模型:

with sess.as_default():

train_step.run(..)

当可训练标志设置为True时,一切正常。然后,当我将其设置为False时,它不会冻结图层。

我还尝试使用train_step_freeze = tf.train.AdamOptimizer(0.004).minimize(loss, var_list=[user_embedding])最小化我要训练的变量,然后我得到:

('Trying to optimize unsupported type ', <tf.Tensor 'Placeholder_33:0' shape=(?, 1) dtype=float32>)

是否可以在Tensorflow中使用Keras图层并冻结它们?

修改

为了清楚说明,我想使用Tensorflow训练模型,而不是使用model.fit()。在Tensorflow中执行此操作的方法似乎是将var_list=[]传递给minimize()方法。但是我这样做时出错:

('Trying to optimize unsupported type ', <tf.Tensor 'Placeholder_33:0' shape=(?, 1) dtype=float32>)

2 个答案:

答案 0 :(得分:3)

我终于找到了一种方法。

TensorFlow无需明确冻结Keras模型,而是让您可以选择指定要训练的变量。

在下面的示例中,我从Keras实例化了一个预训练的VGG16模型,在该模型上定义了几层,然后冻结了该模型(即,仅训练Keras模型之后的层):

import tensorflow as tf
from tensorflow.python.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.python.keras import backend as K
import numpy as np

inputs = tf.placeholder(dtype=tf.float32, shape=(None, 224, 224, 3))
labels = tf.placeholder(dtype=tf.float32, shape=(None, 1))
model = VGG16(include_top=False, weights='imagenet')

features = model(preprocess_input(inputs))

# Define the further layers

conv = tf.layers.Conv2D(filters=1, kernel_size=(3, 3), strides=(2, 2), activation=tf.nn.relu, use_bias=True)
conv_output = conv(features)
flat = tf.layers.Flatten()
flat_output = flat(conv_output)
dense = tf.layers.Dense(1, activation=tf.nn.tanh)
dense_output = dense(flat_output)

# Define the loss and training ops

loss = tf.losses.mean_squared_error(labels, dense_output)
optimizer = tf.train.AdamOptimizer()

# Specify which variables you want to train in `var_list`
train_op = optimizer.minimize(loss, var_list=[conv.variables, flat.variables, dense.variables])

要使用此方法,您将必须为每个层实例化一个对象,因为这将使您可以使用layer_name.variables显式访问该层的变量。另外,您可以使用低级API并定义自己的tf.Variable对象,并使用它们创建图层。

您可以轻松地验证上述方法是否有效:

sess = K.get_session()
K.set_session(sess)

image = np.random.randint(0, 255, size=(1, 224, 224, 3))

for _ in range(100):

    old_features = sess.run(features, feed_dict={inputs: image})
    sess.run(train_op, feed_dict={inputs: np.random.randint(0, 255, size=(2, 224, 224, 3)), labels: np.random.randint(0, 10, size=(2, 1))})
    new_features = sess.run(features, feed_dict={inputs: image})

    print(np.all(old_features == new_features))

这将打印True一百次,这意味着在运行训练操作时模型的权重不会改变。

答案 1 :(得分:0)

如果在训练之前再次编译模型,Keras只会使图层真正无法控制。

现在,我没有看到你在任何地方编译你的模型,而你正在将Keras与TensorFlow命令混合使用。

如果您希望Keras正常工作,您必须使用Keras命令。

在Keras中创建模型:

除了定义输入图层之外,你做了正确的事情y。在第一个嵌入层之前,您需要:

from keras.layers import Input

labels = Input((None, 1)) #is this really an input?????
user_id_input = Input((None, 1))
item_id_input = Input((None, 1))

然后在Keras中创建一个模型:

from keras.models import Model

#supposing you want it to start with two inputs and the output being y
model = Model([user_id_input, item_id_input], y)

然后使用您想要的优化器和损失编译模型(必须在此步骤之前使层无法处理,或者在更改该属性时再次编译):

model.compile(optimizer='adam',loss='binary_crossentropy')

对于培训,您还可以使用Keras命令进行培训:

model.fit([Xuser,Xitem],Y, epochs=..., batch_size=...., ....)
#where Xuser and Xitem are actual training input data and Y contains the actual labels. 
相关问题