我正在研究在估算器的model_fn中使用预训练的keras.applications模型的问题。
在我的研究组中,我们使用Tensorflow估计器是因为它们通过并行训练和评估,训练的热启动,易于使用等方式提供了许多优势。因此,我需要一个可以在模型的估算器。
基本上,我想在model_fn中使用预训练图,尽管我可以使用来自keras.applications的模型。不幸的是,到目前为止,我无法以适当的方式将keras.applications模型插入到model_fn中。
我想使用不带顶层(resnet50,mobilenet,nasnet ...)的可视提取器来提取特征向量,后来我可能想对提取进行微调。这将排除使用视觉提取器作为model_fn之外的预处理步骤。
在对我的真实数据集进行了大量尝试之后,我恢复到了很好的旧MNIST,并提出了一个最小的示例来表明我在寻找什么。我在这里查看了stackoverflow,最初跟随this explanation。
在下面的示例中,我尝试将具有移动网络架构的MNIST数据集归类为可视提取器。有两个使用这些功能的示例版本和一个完全不使用keras模型的示例。该代码非常接近TF官方custom_estimator示例。仅缩小数据集以使其易于装入内存,然后将图像放大并转换为rgb以适应网络结构。
示例案例1和2导致停滞的训练损失和评估的恒定损失。第三种情况显示,没有模型,损失的确减少了(尽管总体性能很差。可以预料到)在这个例子中,我并不是为了追求高性能而拍摄!我只是想表明自己遇到的困难,希望有人能提供帮助。
想法和进一步的想法:
我还在github上打开了issue,因为在我看来该功能应该可以工作。
在下面,您可以找到独立的示例。复制/粘贴后,它应该立即可用。非常感谢您的帮助!
import tensorflow as tf
import numpy as np
from keras.datasets import mnist
# switch to example 1/2/3
EXAMPLE_CASE = 3
# flag for initial weights loading of keras model
_W_INIT = True
def dense_net(features, labels, mode, params):
# --- code to load a keras application ---
# commenting in this line leads to a bump in the loss everytime the
# evaluation is run, this indicating that keras does not handle well the
# two sessions of the estimator API
# tf.keras.backend.set_learning_phase(mode == tf.estimator.ModeKeys.TRAIN)
global _W_INIT
model = tf.keras.applications.MobileNet(
input_tensor=features,
input_shape=(128, 128, 3),
include_top=False,
pooling='avg',
weights='imagenet' if _W_INIT else None)
# only initialize weights once
if _W_INIT:
_W_INIT = False
# switch cases
if EXAMPLE_CASE == 1:
# model.output is the same as model.layers[-1].output
img = model.layers[-1].output
elif EXAMPLE_CASE == 2:
img = model(features)
elif EXAMPLE_CASE == 3:
# do not use keras features
img = tf.keras.layers.Flatten()(features)
else:
raise NotImplementedError
# --- regular code from here on ---
for units in params['dense_layers']:
img = tf.keras.layers.Dense(units=units, activation='relu')(img)
logits = tf.keras.layers.Dense(units=10,
activation='relu')(img)
# compute predictions
probs = tf.nn.softmax(logits)
predicted_classes = tf.argmax(probs, 1)
# compute loss
loss = tf.losses.sparse_softmax_cross_entropy(labels, logits)
acc = tf.metrics.accuracy(labels, predicted_classes)
metrics = {'accuracy': acc}
tf.summary.scalar('accuarcy', acc[1])
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=metrics)
# create training operation
assert mode == tf.estimator.ModeKeys.TRAIN
optimizer = tf.train.AdagradOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
def prepare_dataset(in_tuple, n):
feats = in_tuple[0][:n, :, :]
labels = in_tuple[1][:n]
feats = feats.astype(np.float32)
feats /= 255
labels = labels.astype(np.int32)
return (feats, labels)
def _parse_func(features, labels):
feats = tf.expand_dims(features, -1)
feats = tf.image.grayscale_to_rgb(feats)
feats = tf.image.resize_images(feats, (128, 128))
return (feats, labels)
def load_mnist(n_train=10000, n_test=3000):
train, test = mnist.load_data()
train = prepare_dataset(train, n_train)
test = prepare_dataset(test, n_test)
return train, test
def train_input_fn(imgs, labels, batch_size):
dataset = tf.data.Dataset.from_tensor_slices((imgs, labels))
dataset = dataset.map(_parse_func)
dataset = dataset.shuffle(500)
dataset = dataset.repeat().batch(batch_size)
return dataset
def eval_input_fn(imgs, labels, batch_size):
dataset = tf.data.Dataset.from_tensor_slices((imgs, labels))
dataset = dataset.map(_parse_func)
dataset = dataset.batch(batch_size)
return dataset
def main(m_dir=None):
# fetch data
(x_train, y_train), (x_test, y_test) = load_mnist()
train_spec = tf.estimator.TrainSpec(
input_fn=lambda: train_input_fn(
x_train, y_train, 30),
max_steps=150)
eval_spec = tf.estimator.EvalSpec(
input_fn=lambda: eval_input_fn(
x_test, y_test, 30),
steps=100,
start_delay_secs=0,
throttle_secs=0)
run_cfg = tf.estimator.RunConfig(
model_dir=m_dir,
tf_random_seed=2,
save_summary_steps=2,
save_checkpoints_steps=10,
keep_checkpoint_max=1)
# build network
classifier = tf.estimator.Estimator(
model_fn=dense_net,
params={
'dense_layers': [256]},
config=run_cfg)
# fit the model
tf.estimator.train_and_evaluate(
classifier,
train_spec,
eval_spec)
if __name__ == "__main__":
main()