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

Syz*_*ygy 2 keras tensorflow

我正在尝试冻结 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)
Run Code Online (Sandbox Code Playgroud)

然后我只是训练模型:

with sess.as_default():

train_step.run(..)
Run Code Online (Sandbox Code Playgroud)

当可训练标志设置为 时,一切工作正常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>)
Run Code Online (Sandbox Code Playgroud)

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

编辑

为了让事情变得清楚,我想使用 Tensorflow 来训练模型,而不是使用model.fit(). 在 Tensorflow 中执行此操作的方法似乎是传递var_list=[]minimize()方法。但我在执行此操作时遇到错误:

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

Roh*_*ena 5

我终于找到了一种方法来做到这一点。

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])
Run Code Online (Sandbox Code Playgroud)

要使用此方法,您必须为每个层实例化一个对象,因为这将允许您使用 显式访问该层的变量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))
Run Code Online (Sandbox Code Playgroud)

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