首页 文章

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

提问于
浏览
1

我正试图在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图层并冻结它们?

EDIT

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

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

2 回答

  • 0

    我终于找到了办法 .

    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 一百次,这意味着在运行训练操作时模型的权重不会改变 .

  • 2

    如果在训练之前再次编译模型,Keras将只使图层真正无法处理 .

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

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

    Creating a model in 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.
    

相关问题