我已经在MobileNet
中实现了自己的TensorFlow
版本,并希望通过与官方tensorflow_hub
版本进行比较来进行验证。
我可以轻松地完成一些工作:
URL = "https://tfhub.dev/google/imagenet/mobilenet_v1_100_224/feature_vector/4"
model = tf.keras.Sequential([
hub.KerasLayer(URL, True, input_shape=(IMG_SIZE, IMG_SIZE, 3)),
Layers.Dropout(0.2),
Layers.Dense(len(class_names))
])
但是该模型已经过训练。
我尝试致电initializer
,但tensorflow_hub.KerasLayer
没有。
我还尝试过使用glorot_uniform()
和RandomUniform()
重置所有权重,但是随后该模型根本无法学习(当我对权重进行相同的随机化时,我的模型也不会学到)。>
您可以重新初始化预先训练的模型吗?
答案 0 :(得分:0)
许多搜索仅提供了用于重置已拥有的层的方法,或将其恢复到开始使用模型时的状态。
这可能还远未完成,但是也许有人可以建立它!
import tensorflow as tf
import tensorflow.keras.backend as K
def untrain_layer(layer):
initial_weights = layer.weights
new_weights = []
for w in initial_weights:
print(w.name)
if "beta" in w.name:
new_weights.append(K.eval(tf.keras.initializers.zeros())(w.shape))
elif "gamma" in w.name:
new_weights.append(K.eval(tf.keras.initializers.ones())(w.shape))
elif "moving_mean" in w.name:
new_weights.append(K.eval(tf.keras.initializers.zeros())(w.shape))
elif "moving_variance" in w.name:
new_weights.append(K.eval(tf.keras.initializers.ones())(w.shape))
else:
new_weights.append(K.eval(tf.keras.initializers.glorot_uniform())(w.shape))
layer.set_weights(new_weights)
使用:
import tensorflow_hub as hub
feature_extractor = hub.KerasLayer(URL, True, input_shape=(IMG_SIZE, IMG_SIZE, 3))
untrain_keraslayer(feature_extractor)