#python #tensorflow #object-detection #object-detection-api
#python #tensorflow #обнаружение объекта #object-detection-api
Вопрос:
Я пытаюсь создать пользовательскую модель обнаружения объектов, используя API обнаружения объектов Tensorflow. В частности, я хочу добавить оценку расстояния к каждому обнаруженному объекту. Итак, я расширил SSDMetaArch
класс и адаптировал / добавил некоторые важные части. Среди прочего:
- добавлено расстояние до входных данных
- адаптированные протоколы для обработки расстояния
- создан новый заголовок прогноза для оценок расстояния
- созданы новые потери с учетом расстояний
- адаптированный шаг постобработки для выходных расстояний
После всех этих шагов обучение, похоже, работает, и потери (включая потерю расстояния) снижаются.
Но когда я хочу оценить модель, я получаю
Ошибка выполнения: график завершен и не может быть изменен.
В частности, следующая строка в (адаптированном) visualize_boxes_and_labels_on_image_array()
методе в visualization_utils.py
(около строки 700) вызывает ошибку
#the follwing line throws the error
display_str = '{}: {}% -> {}'.format(display_str, int(100 * scores[i]), int(distances[i]))
#No error is thrown using the original code
#display_str = '{}: {}%'.format(display_str, int(100 * scores[i]))
Кажется, что просто при печати значения генерируется вышеупомянутое исключение.
Мой вопрос: Я не понимаю, почему печать значения изменит график. Не могли бы вы помочь мне понять, почему это так, и, если возможно, дать мне подсказку, как я могу избежать этого изменения графика.
Найдите полную ошибку ниже
INFO:tensorflow:Restoring parameters from E:/Data/OD_DE/tensorflow/models/modelmodel.ckpt-5103
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
2019-04-01 13:14:30.795741: W tensorflow/core/framework/op_kernel.cc:1261]
Unknown: RuntimeError: Graph is finalized and cannot be modified.
Traceback (most recent call last):
File "..libsite-packagestensorflowpythonopsscript_ops.py", line 206, in __call__
ret = func(*args)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 271, in _visualize_boxes
image, boxes, classes, scores, category_index=category_index, **kwargs)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 730, in visualize_boxes_and_labels_on_image_array
print("We were definitely here:" str(int(distances[i])))
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 525, in _slice_helper
name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 6037, in __exit__
self._name_scope.__exit__(type_arg, value_arg, traceback_arg)
File "C:UsersJDAppDataLocalContinuumAnaconda3Libcontextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "..libsite-packagestensorflowpythonframeworkops.py", line 4016, in name_scope
yield "" if new_stack is None else new_stack "/"
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 500, in _slice_helper
packed_begin, packed_end, packed_strides = (stack(begin), stack(end),
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 863, in stack
return ops.convert_to_tensor(values, name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1050, in convert_to_tensor
as_ref=False)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1146, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 229, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 214, in constant
name=name).outputs[0]
File "..libsite-packagestensorflowpythonutildeprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "..libsite-packagestensorflowpythonframeworkops.py", line 3246, in create_op
self._check_not_finalized()
File "..libsite-packagestensorflowpythonframeworkops.py", line 2919, in _check_not_finalized
raise RuntimeError("Graph is finalized and cannot be modified.")
RuntimeError: Graph is finalized and cannot be modified.
Traceback (most recent call last):
File "..libsite-packagestensorflowpythonclientsession.py", line 1334, in _do_call
return fn(*args)
File "..libsite-packagestensorflowpythonclientsession.py", line 1319, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "..libsite-packagestensorflowpythonclientsession.py", line 1407, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.UnknownError: RuntimeError: Graph is finalized and cannot be modified.
Traceback (most recent call last):
File "..libsite-packagestensorflowpythonopsscript_ops.py", line 206, in __call__
ret = func(*args)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 271, in _visualize_boxes
image, boxes, classes, scores, category_index=category_index, **kwargs)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 730, in visualize_boxes_and_labels_on_image_array
print("We were definitely here:" str(int(distances[i])))
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 525, in _slice_helper
name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 6037, in __exit__
self._name_scope.__exit__(type_arg, value_arg, traceback_arg)
File "C:UsersJDAppDataLocalContinuumAnaconda3Libcontextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "..libsite-packagestensorflowpythonframeworkops.py", line 4016, in name_scope
yield "" if new_stack is None else new_stack "/"
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 500, in _slice_helper
packed_begin, packed_end, packed_strides = (stack(begin), stack(end),
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 863, in stack
return ops.convert_to_tensor(values, name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1050, in convert_to_tensor
as_ref=False)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1146, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 229, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 214, in constant
name=name).outputs[0]
File "..libsite-packagestensorflowpythonutildeprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "..libsite-packagestensorflowpythonframeworkops.py", line 3246, in create_op
self._check_not_finalized()
File "..libsite-packagestensorflowpythonframeworkops.py", line 2919, in _check_not_finalized
raise RuntimeError("Graph is finalized and cannot be modified.")
RuntimeError: Graph is finalized and cannot be modified.
[[{{node map_1/while/PyFunc}} = PyFunc[Tin=[DT_UINT8, DT_FLOAT, DT_INT64, DT_FLOAT], Tout=[DT_UINT8], _class=["loc:@map_1/while/TensorArrayWrite/TensorArrayWriteV3"], token="pyfunc_1", _device="/job:localhost/replica:0/task:0/device:CPU:0"](map_1/while/Squeeze/_2907, map_1/while/TensorArrayReadV3_3/_2909, map_1/while/TensorArrayReadV3_4/_2911, map_1/while/TensorArrayReadV3_5/_2913)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:Program FilesJetBrainsPyCharm Community Edition 2017.2helperspydevpydevd.py", line 1596, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:Program FilesJetBrainsPyCharm Community Edition 2017.2helperspydevpydevd.py", line 1023, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:Program FilesJetBrainsPyCharm Community Edition 2017.2helperspydev_pydev_imps_pydev_execfile.py", line 18, in execfile
exec(compile(contents "n", file, 'exec'), glob, loc)
File "C:/Users/JD/tensorflowod/Lib/site-packages/tensorflow/models/research/object_detection/model_main.py", line 110, in <module>
tf.app.run()
File "..libsite-packagestensorflowpythonplatformapp.py", line 125, in run
_sys.exit(main(argv))
File "C:/Users/JD/tensorflowod/Lib/site-packages/tensorflow/models/research/object_detection/model_main.py", line 105, in main
tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])
File "..libsite-packagestensorflowpythonestimatortraining.py", line 471, in train_and_evaluate
return executor.run()
File "..libsite-packagestensorflowpythonestimatortraining.py", line 610, in run
return self.run_local()
File "..libsite-packagestensorflowpythonestimatortraining.py", line 711, in run_local
saving_listeners=saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 354, in train
loss = self._train_model(input_fn, hooks, saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1207, in _train_model
return self._train_model_default(input_fn, hooks, saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1241, in _train_model_default
saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1471, in _train_with_estimator_spec
_, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 671, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1156, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1255, in run
raise six.reraise(*original_exc_info)
File "c:usersJDappdatalocalcontinuumanaconda3libsite-packagessix.py", line 686, in reraise
raise value
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1240, in run
return self._sess.run(*args, **kwargs)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1320, in run
run_metadata=run_metadata))
File "..libsite-packagestensorflowpythontrainingbasic_session_run_hooks.py", line 582, in after_run
if self._save(run_context.session, global_step):
File "..libsite-packagestensorflowpythontrainingbasic_session_run_hooks.py", line 607, in _save
if l.after_save(session, step):
File "..libsite-packagestensorflowpythonestimatortraining.py", line 517, in after_save
self._evaluate(global_step_value) # updates self.eval_result
File "..libsite-packagestensorflowpythonestimatortraining.py", line 537, in _evaluate
self._evaluator.evaluate_and_export())
File "..libsite-packagestensorflowpythonestimatortraining.py", line 912, in evaluate_and_export
hooks=self._eval_spec.hooks)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 478, in evaluate
return _evaluate()
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 467, in _evaluate
output_dir=self.eval_dir(name))
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1591, in _evaluate_run
config=self._session_config)
File "..libsite-packagestensorflowpythontrainingevaluation.py", line 274, in _evaluate_once
session.run(eval_ops, feed_dict)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 671, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1156, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1255, in run
raise six.reraise(*original_exc_info)
File "c:usersJDappdatalocalcontinuumanaconda3libsite-packagessix.py", line 686, in reraise
raise value
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1240, in run
return self._sess.run(*args, **kwargs)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1312, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1076, in run
return self._sess.run(*args, **kwargs)
File "..libsite-packagestensorflowpythonclientsession.py", line 929, in run
run_metadata_ptr)
File "..libsite-packagestensorflowpythonclientsession.py", line 1152, in _run
feed_dict_tensor, options, run_metadata)
File "..libsite-packagestensorflowpythonclientsession.py", line 1328, in _do_run
run_metadata)
File "..libsite-packagestensorflowpythonclientsession.py", line 1348, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.UnknownError: RuntimeError: Graph is finalized and cannot be modified.
Traceback (most recent call last):
File "..libsite-packagestensorflowpythonopsscript_ops.py", line 206, in __call__
ret = func(*args)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 271, in _visualize_boxes
image, boxes, classes, scores, category_index=category_index, **kwargs)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 730, in visualize_boxes_and_labels_on_image_array
print("We were definitely here:" str(int(distances[i])))
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 525, in _slice_helper
name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 6037, in __exit__
self._name_scope.__exit__(type_arg, value_arg, traceback_arg)
File "C:UsersJDAppDataLocalContinuumAnaconda3Libcontextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "..libsite-packagestensorflowpythonframeworkops.py", line 4016, in name_scope
yield "" if new_stack is None else new_stack "/"
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 500, in _slice_helper
packed_begin, packed_end, packed_strides = (stack(begin), stack(end),
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 863, in stack
return ops.convert_to_tensor(values, name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1050, in convert_to_tensor
as_ref=False)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1146, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 229, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 214, in constant
name=name).outputs[0]
File "..libsite-packagestensorflowpythonutildeprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "..libsite-packagestensorflowpythonframeworkops.py", line 3246, in create_op
self._check_not_finalized()
File "..libsite-packagestensorflowpythonframeworkops.py", line 2919, in _check_not_finalized
raise RuntimeError("Graph is finalized and cannot be modified.")
RuntimeError: Graph is finalized and cannot be modified.
[[node map_1/while/PyFunc (defined at ..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py:439) = PyFunc[Tin=[DT_UINT8, DT_FLOAT, DT_INT64, DT_FLOAT], Tout=[DT_UINT8], _class=["loc:@map_1/while/TensorArrayWrite/TensorArrayWriteV3"], token="pyfunc_1", _device="/job:localhost/replica:0/task:0/device:CPU:0"](map_1/while/Squeeze/_2907, map_1/while/TensorArrayReadV3_3/_2909, map_1/while/TensorArrayReadV3_4/_2911, map_1/while/TensorArrayReadV3_5/_2913)]]
Caused by op 'map_1/while/PyFunc', defined at:
File "C:Program FilesJetBrainsPyCharm Community Edition 2017.2helperspydevpydevd.py", line 1596, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:Program FilesJetBrainsPyCharm Community Edition 2017.2helperspydevpydevd.py", line 1023, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:Program FilesJetBrainsPyCharm Community Edition 2017.2helperspydev_pydev_imps_pydev_execfile.py", line 18, in execfile
exec(compile(contents "n", file, 'exec'), glob, loc)
File "C:/Users/JD/tensorflowod/Lib/site-packages/tensorflow/models/research/object_detection/model_main.py", line 110, in <module>
tf.app.run()
File "..libsite-packagestensorflowpythonplatformapp.py", line 125, in run
_sys.exit(main(argv))
File "C:/Users/JD/tensorflowod/Lib/site-packages/tensorflow/models/research/object_detection/model_main.py", line 105, in main
tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])
File "..libsite-packagestensorflowpythonestimatortraining.py", line 471, in train_and_evaluate
return executor.run()
File "..libsite-packagestensorflowpythonestimatortraining.py", line 610, in run
return self.run_local()
File "..libsite-packagestensorflowpythonestimatortraining.py", line 711, in run_local
saving_listeners=saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 354, in train
loss = self._train_model(input_fn, hooks, saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1207, in _train_model
return self._train_model_default(input_fn, hooks, saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1241, in _train_model_default
saving_listeners)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1471, in _train_with_estimator_spec
_, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 671, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1156, in run
run_metadata=run_metadata)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1240, in run
return self._sess.run(*args, **kwargs)
File "..libsite-packagestensorflowpythontrainingmonitored_session.py", line 1320, in run
run_metadata=run_metadata))
File "..libsite-packagestensorflowpythontrainingbasic_session_run_hooks.py", line 582, in after_run
if self._save(run_context.session, global_step):
File "..libsite-packagestensorflowpythontrainingbasic_session_run_hooks.py", line 607, in _save
if l.after_save(session, step):
File "..libsite-packagestensorflowpythonestimatortraining.py", line 517, in after_save
self._evaluate(global_step_value) # updates self.eval_result
File "..libsite-packagestensorflowpythonestimatortraining.py", line 537, in _evaluate
self._evaluator.evaluate_and_export())
File "..libsite-packagestensorflowpythonestimatortraining.py", line 912, in evaluate_and_export
hooks=self._eval_spec.hooks)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 478, in evaluate
return _evaluate()
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 460, in _evaluate
self._evaluate_build_graph(input_fn, hooks, checkpoint_path))
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1484, in _evaluate_build_graph
self._call_model_fn_eval(input_fn, self.config))
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1520, in _call_model_fn_eval
features, labels, model_fn_lib.ModeKeys.EVAL, config)
File "..libsite-packagestensorflowpythonestimatorestimator.py", line 1195, in _call_model_fn
model_fn_results = self._model_fn(features=features, **kwargs)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionmodel_lib.py", line 443, in model_fn
eval_dict)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 931, in get_estimator_eval_metric_ops
images = self.images_from_evaluation_dict(eval_dict)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 995, in images_from_evaluation_dict
self._min_score_thresh, self._use_normalized_coordinates)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 547, in draw_side_by_side_evaluation_image
eval_dict[input_data_fields.groundtruth_distances][indx], axis=0) if input_data_fields.groundtruth_distances in eval_dict else None
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 442, in draw_bounding_boxes_on_image_tensors
images = tf.map_fn(draw_boxes, elems, dtype=tf.uint8, back_prop=False)
File "..libsite-packagestensorflowpythonopsfunctional_ops.py", line 494, in map_fn
maximum_iterations=n)
File "..libsite-packagestensorflowpythonopscontrol_flow_ops.py", line 3291, in while_loop
return_same_structure)
File "..libsite-packagestensorflowpythonopscontrol_flow_ops.py", line 3004, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "..libsite-packagestensorflowpythonopscontrol_flow_ops.py", line 2939, in _BuildLoop
body_result = body(*packed_vars_for_body)
File "..libsite-packagestensorflowpythonopscontrol_flow_ops.py", line 3260, in <lambda>
body = lambda i, lv: (i 1, orig_body(*lv))
File "..libsite-packagestensorflowpythonopsfunctional_ops.py", line 483, in compute
packed_fn_values = fn(packed_values)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 439, in draw_boxes
tf.uint8)
File "..libsite-packagestensorflowpythonopsscript_ops.py", line 457, in py_func
func=func, inp=inp, Tout=Tout, stateful=stateful, eager=False, name=name)
File "..libsite-packagestensorflowpythonopsscript_ops.py", line 281, in _internal_py_func
input=inp, token=token, Tout=Tout, name=name)
File "..libsite-packagestensorflowpythonopsgen_script_ops.py", line 132, in py_func
"PyFunc", input=input, token=token, Tout=Tout, name=name)
File "..libsite-packagestensorflowpythonframeworkop_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "..libsite-packagestensorflowpythonutildeprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "..libsite-packagestensorflowpythonframeworkops.py", line 3274, in create_op
op_def=op_def)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1770, in __init__
self._traceback = tf_stack.extract_stack()
UnknownError (see above for traceback): RuntimeError: Graph is finalized and cannot be modified.
Traceback (most recent call last):
File "..libsite-packagestensorflowpythonopsscript_ops.py", line 206, in __call__
ret = func(*args)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 271, in _visualize_boxes
image, boxes, classes, scores, category_index=category_index, **kwargs)
File "..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py", line 730, in visualize_boxes_and_labels_on_image_array
print("We were definitely here:" str(int(distances[i])))
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 525, in _slice_helper
name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 6037, in __exit__
self._name_scope.__exit__(type_arg, value_arg, traceback_arg)
File "C:UsersJDAppDataLocalContinuumAnaconda3Libcontextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "..libsite-packagestensorflowpythonframeworkops.py", line 4016, in name_scope
yield "" if new_stack is None else new_stack "/"
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 500, in _slice_helper
packed_begin, packed_end, packed_strides = (stack(begin), stack(end),
File "..libsite-packagestensorflowpythonopsarray_ops.py", line 863, in stack
return ops.convert_to_tensor(values, name=name)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1050, in convert_to_tensor
as_ref=False)
File "..libsite-packagestensorflowpythonframeworkops.py", line 1146, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 229, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "..libsite-packagestensorflowpythonframeworkconstant_op.py", line 214, in constant
name=name).outputs[0]
File "..libsite-packagestensorflowpythonutildeprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "..libsite-packagestensorflowpythonframeworkops.py", line 3246, in create_op
self._check_not_finalized()
File "..libsite-packagestensorflowpythonframeworkops.py", line 2919, in _check_not_finalized
raise RuntimeError("Graph is finalized and cannot be modified.")
RuntimeError: Graph is finalized and cannot be modified.
[[node map_1/while/PyFunc (defined at ..Libsite-packagestensorflowmodelsresearchobject_detectionutilsvisualization_utils.py:439) = PyFunc[Tin=[DT_UINT8, DT_FLOAT, DT_INT64, DT_FLOAT], Tout=[DT_UINT8], _class=["loc:@map_1/while/TensorArrayWrite/TensorArrayWriteV3"], token="pyfunc_1", _device="/job:localhost/replica:0/task:0/device:CPU:0"](map_1/while/Squeeze/_2907, map_1/while/TensorArrayReadV3_3/_2909, map_1/while/TensorArrayReadV3_4/_2911, map_1/while/TensorArrayReadV3_5/_2913)]]
Комментарии:
1. Хотя из вопроса трудно сказать, я могу предложить проверку работоспособности. Можете ли вы проверить тип «расстояний» перед печатью? Если вы получили их из строки типа ‘distances = session.run([distances_op])’, то, вероятно, они должны быть числовым массивом, а не каким-либо тензором.
Ответ №1:
Похоже, что в вашем случае distances
это тензор, и вызов distances[0]
пытается создать операцию array_slice на завершенном графике. Правильным способом обработки этого было бы передать distances
тензор вашему distances_np = session.run(distances)
или вызвать distances_np = distances.eval()
, предоставив необходимые параметры для получения какого-либо массива numpy, и только затем выполнить индексацию и / или печать distances_np
.
Комментарии:
1. Ах, это имеет смысл. Я напечатал типы оценок и расстояний и получил <класс ‘numpy.ndarray’> и <класс ‘tensorflow.python.framework.ops.Tensor’> соответственно. Большое спасибо, я надеюсь, что смогу исправить проблему сейчас.