簡體   English   中英

NameError:名稱“ feature_extractor_url”在加載keras模型時未定義

[英]NameError: name 'feature_extractor_url' is not defined on loading keras model

我正在嘗試加載保存的keras模型

model= tf.keras.models.load_model("my_model.h5",
custom_objects=None,
compile=True)
model.summary()

並得到以下錯誤

Traceback (most recent call last):
File "C:\Users\admin\Desktop\phd python 

projects\tensorflow_img_class\src\tensorflow ui.py", line 45, in <module>
    compile=True
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\saving\save.py", line 146, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py", line 212, in load_model_from_hdf5
    custom_objects=custom_objects)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\saving\model_config.py", line 55, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\layers\serialization.py", line 89, in deserialize
    printable_module_name='layer')
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\utils\generic_utils.py", line 192, in deserialize_keras_object
    list(custom_objects.items())))
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 353, in from_config
    model.add(layer)
  File "C:\Python37\lib\site-packages\tensorflow\python\training\tracking\base.py", line 460, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\sequential.py", line 174, in add
    layer(x)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 632, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
  File "C:\Python37\lib\site-packages\tensorflow\python\keras\layers\core.py", line 782, in call
    return self.function(inputs, **arguments)
  File "C:/Users/admin/Desktop/phd python projects/tensorflow_img_class/src/tensorflow_img_class.py", line 35, in feature_extractor
    feature_extractor_module = hub.Module(feature_extractor_url)
NameError: name 'feature_extractor_url' is not defined

有關此問題的更多詳細信息。 我按照之前的鏈接文章中的建議打開了這篇文章。

該模型的代碼是

image_generator = tf.compat.v1.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)
data_root = tf.compat.v1.keras.utils.get_file('Annotated_Image_Classes', 'https://github.com/PawanKaur/Viz-Image-Classification/tree/master/Annotated%20Image%20Classes.tqz',
                                              untar=True)  
feature_extractor_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2" 

def feature_extractor(x):
  feature_extractor_module = hub.Module(feature_extractor_url)
  return feature_extractor_module(x)
IMAGE_SIZE = hub.get_expected_image_size(hub.Module(feature_extractor_url))

image_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SIZE)
for image_batch,label_batch in image_data:
  print("Image batch shape: ", image_batch.shape)
  print("Label batch shape: ", label_batch.shape)
  break

features_extractor_layer = layers.Lambda(feature_extractor, input_shape=IMAGE_SIZE+[3])
features_extractor_layer.trainable = False

model = tf.keras.Sequential([
  features_extractor_layer,
  layers.Dense(image_data.num_classes, activation='softmax')
])
model.summary()

sess = tf.compat.v1.keras.backend.get_session()
init = tf.compat.v1.global_variables_initializer()  
sess.run(init)

result = model.predict(image_batch)
result.shape
model.compile(
  optimizer=tf.train.AdamOptimizer(), 
  loss='categorical_crossentropy',
  metrics=['accuracy'])

class CollectBatchStats(tf.keras.callbacks.Callback):
  def __init__(self):
    self.batch_losses = []
    self.batch_acc = []

  def on_batch_end(self, batch, logs=None):
    self.batch_losses.append(logs['loss'])
    self.batch_acc.append(logs['acc'])

steps_per_epoch = image_data.samples//image_data.batch_size
batch_stats = CollectBatchStats()
model.fit((item for item in image_data), epochs=18, 
                    steps_per_epoch=steps_per_epoch,
                    callbacks = [batch_stats])    
model.save('my_model.h5')

基本上,我是按照此處的轉移學習說明創建此模型的。 我正在對此建模以在我的圖像數據上運行。 之后,我只需要在另一個程序中打開並查看此經過預先訓練和保存的模型,但是到目前為止,我還不能這樣做。 任何幫助將是可觀的。

只需在導入語句后在加載模型腳本中添加feature_extractor_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/feature_vector/2"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM