Python Tensorflow 运行时错误 - 找不到文件

时间:2021-02-20 17:09:32

标签: python python-3.x tensorflow

我正在尝试构建一个对象检测模型(按照本教程 - https://www.youtube.com/watch?v=IOI0o3Cxv9Q&list=PLCto5fUZy7l06S0bdMRHLgWvcOzk4shhF&index=4&t=204s&ab_channel=NicholasRenotte)我已经完成了他所做的一切,TensorFlow 安装正确,python 也是如此,我的文件层次结构都是正确的,但我得到了一个尝试使用 jupyter notebook 训练我的模型时出现运行时错误。 这是错误:-

RuntimeError                              Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\py_checkpoint_reader.py in NewCheckpointReader(filepattern)
     94   try:
---> 95     return CheckpointReader(compat.as_bytes(filepattern))
     96   # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the

RuntimeError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for Tensorflow/workspace/models/my_ssd_mobnet/ckpt-6

During handling of the above exception, another exception occurred:

NotFoundError                             Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\tracking\util.py in restore(self, save_path, options)
   2259     try:
-> 2260       status = self.read(save_path, options=options)
   2261     except errors_impl.NotFoundError:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\tracking\util.py in read(self, save_path, options)
   2147     options = options or checkpoint_options.CheckpointOptions()
-> 2148     return self._saver.restore(save_path=save_path, options=options)
   2149 

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\tracking\util.py in restore(self, save_path, options)
   1291       return InitializationOnlyStatus(self._graph_view, ops.uid())
-> 1292     reader = py_checkpoint_reader.NewCheckpointReader(save_path)
   1293     graph_building = not context.executing_eagerly()

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\py_checkpoint_reader.py in NewCheckpointReader(filepattern)
     98   except RuntimeError as e:
---> 99     error_translator(e)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\py_checkpoint_reader.py in error_translator(e)
     34       'matching files for') in error_message:
---> 35     raise errors_impl.NotFoundError(None, None, error_message)
     36   elif 'Sliced checkpoints are not supported' in error_message or (

NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for Tensorflow/workspace/models/my_ssd_mobnet/ckpt-6

During handling of the above exception, another exception occurred:

NotFoundError                             Traceback (most recent call last)
<ipython-input-249-f5bf27ce595e> in <module>
      5 # Restore checkpoint
      6 ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
----> 7 ckpt.restore(os.path.join(CHECKPOINT_PATH, 'ckpt-6')).expect_partial()
      8 
      9 @tf.function

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\training\tracking\util.py in restore(self, save_path, options)
   2263           None, None,
   2264           "Could not find checkpoint or SavedModel at {}."
-> 2265           .format(orig_save_path))
   2266     # Create the save counter now so it gets initialized with other variables
   2267     # when graph building. Creating it earlier would lead to errors when using,

NotFoundError: Could not find checkpoint or SavedModel at Tensorflow/workspace/models/my_ssd_mobnet/ckpt-6.

这是我的 jupyter 文件中的代码:-

WORKSPACE_PATH = 'Tensorflow/workspace'
SCRIPTS_PATH = 'Tensorflow/scripts'
APIMODEL_PATH = 'Tensorflow/models'
ANNOTATION_PATH = WORKSPACE_PATH+'/annotations'
IMAGE_PATH = WORKSPACE_PATH+'/images'
MODEL_PATH = WORKSPACE_PATH+'/models'
PRETRAINED_MODEL_PATH = WORKSPACE_PATH+'/pre-trained-models'
CONFIG_PATH = MODEL_PATH+'/my_ssd_mobnet/pipeline.config'
CHECKPOINT_PATH = MODEL_PATH+'/my_ssd_mobnet/'

labels = [{'name':'tite', 'id':1}, {'name':'xaxis', 'id':2}, {'name':'yaxis', 'id':3}, {'name':'key', 'id':4}, {'name':'bar', 'id':5}]

with open(ANNOTATION_PATH + '\label_map.pbtxt', 'w') as f:
    for label in labels:
        f.write('item { \n')
        f.write('\tname:\'{}\'\n'.format(label['name']))
        f.write('\tid:{}\n'.format(label['id']))
        f.write('}\n')

!python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x {IMAGE_PATH + '/train'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/train.record'}
!python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x{IMAGE_PATH + '/test'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/test.record'}

!cd Tensorflow && git clone https://github.com/tensorflow/models
CUSTOM_MODEL_NAME = 'my_ssd_mobnet' 
!mkdir {'Tensorflow\workspace\models\\'+CUSTOM_MODEL_NAME}
!cp {PRETRAINED_MODEL_PATH+'/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config'} {MODEL_PATH+'/'+CUSTOM_MODEL_NAME}

import tensorflow as tf
from object_detection.utils import config_util
from object_detection.protos import pipeline_pb2
from google.protobuf import text_format

CONFIG_PATH = MODEL_PATH+'/'+CUSTOM_MODEL_NAME+'/pipeline.config'
config = config_util.get_configs_from_pipeline_file(CONFIG_PATH)



pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.io.gfile.GFile(CONFIG_PATH, "r") as f:                                                                                                                                                                                                                     
proto_str = f.read()                                                                                                                                                                                                                                          
text_format.Merge(proto_str, pipeline_config)  

ipeline_config.model.ssd.num_classes = 5
pipeline_config.train_config.batch_size = 24
pipeline_config.train_config.fine_tune_checkpoint = PRETRAINED_MODEL_PATH+'/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/checkpoint/ckpt-0'
pipeline_config.train_config.fine_tune_checkpoint_type = "detection"
pipeline_config.train_input_reader.label_map_path= ANNOTATION_PATH + '/label_map.pbtxt'
pipeline_config.train_input_reader.tf_record_input_reader.input_path[:] = [ANNOTATION_PATH + '/train.record']
pipeline_config.eval_input_reader[0].label_map_path = ANNOTATION_PATH + '/label_map.pbtxt'
pipeline_config.eval_input_reader[0].tf_record_input_reader.input_path[:] = [ANNOTATION_PATH + '/test.record']


config_text = text_format.MessageToString(pipeline_config)                                                                                                                                                                                                        
    with tf.io.gfile.GFile(CONFIG_PATH, "wb") as f:                                                                                                                                                                                                                     
    f.write(config_text)   

print("""python {}/research/object_detection/model_main_tf2.py --model_dir={}/{} -- 
pipeline_config_path={}/{}/pipeline.config --num_train_steps=5000""".format(APIMODEL_PATH, MODEL_PATH,CUSTOM_MODEL_NAME,MODEL_PATH,CUSTOM_MODEL_NAME))

import os
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils
from object_detection.builders import model_builder


# Load pipeline config and build a detection model
configs = config_util.get_configs_from_pipeline_file(CONFIG_PATH)
detection_model = model_builder.build(model_config=configs['model'], is_training=False)

# Restore checkpoint
ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
ckpt.restore(os.path.join(CHECKPOINT_PATH, 'ckpt-6')).expect_partial()

@tf.function
def detect_fn(image):
    image, shapes = detection_model.preprocess(image)
    prediction_dict = detection_model.predict(image, shapes)
    detections = detection_model.postprocess(prediction_dict, shapes)
    return detections

 #This is where the runtime error happens 

 import cv2 
 import numpy as np
 category_index = label_map_util.create_category_index_from_labelmap(ANNOTATION_PATH+'/label_map.pbtxt')
 cap.release()

 # Setup capture
 cap = cv2.VideoCapture(0)
 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
 height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))


while True: 
ret, frame = cap.read()
image_np = np.array(frame)

input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)

num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
              for key, value in detections.items()}
detections['num_detections'] = num_detections

# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

label_id_offset = 1
image_np_with_detections = image_np.copy()

viz_utils.visualize_boxes_and_labels_on_image_array(
            image_np_with_detections,
            detections['detection_boxes'],
            detections['detection_classes']+label_id_offset,
            detections['detection_scores'],
            category_index,
            use_normalized_coordinates=True,
            max_boxes_to_draw=5,
            min_score_thresh=.5,
            agnostic_mode=False)

cv2.imshow('object detection',  cv2.resize(image_np_with_detections, (800, 600)))

if cv2.waitKey(1) & 0xFF == ord('q'):
    cap.release()
    break

detections = detect_fn(input_tensor)
from matplotlib import pyplot as plt

0 个答案:

没有答案
相关问题