Как я могу изменить обучаемую переменную в тензорном потоке? - PullRequest
0 голосов
/ 11 декабря 2019

Я пытаюсь использовать модель хаба KerasLayer, хочу заморозить нижние слои и обучить верхние слои. Но я не могу изменить обучаемость переменной в предварительно обученной модели. Я просто могу выбрать обучаемое False или True, когда загружаю модель. Кто-нибудь может мне помочь?

from __future__ import absolute_import, division, print_function, unicode_literals

# Install TensorFlow
try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass

import tensorflow as tf
from tensorflow import keras
import tensorflow_datasets as tfds
import tensorflow_hub as hub
import numpy as np


dataset = tfds.load(name="cats_vs_dogs", split=tfds.Split.TRAIN, as_supervised=True)

IMG_SIZE = 96
num_epochs = 5
dataset = dataset.map(lambda img, label: (tf.image.resize(img, [IMG_SIZE, IMG_SIZE]) / 255.0, label)).shuffle(12500).batch(32)

hub_model = hub.KerasLayer('https://tfhub.dev/google/imagenet/mobilenet_v2_050_96/classification/4', input_shape=(IMG_SIZE, IMG_SIZE, 3),trainable=True)

for i in hub_model.variables:
  if "expanded_conv_16" in i.name or "expanded_conv_15" in i.name:
    print(i.name,i.trainable)
  else:
    i=tf.Variable(i,trainable=False)
  # print(i.name)
  # if '15' in i.name:
  # # i=tf.Variable(i,trainable=False)
  #   print(i.name,i.trainable)

# see it doesn't work! And I also cann't make i.trainable=False
for i in hub_model.variables:
  print(i.name)

def train():   
    return model.fit(dataset, epochs=num_epochs, verbose=1)



model = keras.Sequential([
    hub_model,
    tf.keras.layers.Dense(2, tf.nn.softmax)
])
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
                    loss=tf.keras.losses.sparse_categorical_crossentropy,
                    metrics=[tf.keras.metrics.sparse_categorical_accuracy])

# It will cost many times when train all model, And I want to train the top layers, not only the last Layers
history = train()

Спасибо, кто-нибудь приходит, чтобы помочь мне!

...