Unexpected errors in object_detection project, absolutely dumbfounded - python

I am trying to learn tensorflow by following this tutorial: https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10 After executing step 2g, my code appears online and I have to check it for errors. When I did so, I received many errors, some seemingly unwarranted (for example 'os' is not defined when it clearly was). I viewed both the "common errors" section of the GitHub as well as the comments section but nobody seems to have the same issues as me. I also followed the instructions in some of the errors, but nothing worked. The code errors are a little garbled so I will do my best to format them below. I am completely new to tensorflow so this is completely foreign territory for me. Any help would be much appreciated.
Code:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from object_detection.utils import ops as utils_ops
if StrictVersion(tf.__version__) < StrictVersion('1.9.0'):
raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!')
# This is needed to display the images.
%matplotlib inline
from utils import label_map_util
from utils import visualization_utils as vis_util
# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
opener = urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
tar_file = tarfile.open(MODEL_FILE)
for file in tar_file.getmembers():
file_name = os.path.basename(file.name)
if 'frozen_inference_graph.pb' in file_name:
tar_file.extract(file, os.getcwd())
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add the path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, ) ]
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
def run_inference_for_single_image(image, graph):
with graph.as_default():
with tf.Session() as sess:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in [
'num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks'
]:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
# The following processing is only for single image
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(
detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Run inference
output_dict = sess.run(tensor_dict,
feed_dict={image_tensor: np.expand_dims(image, 0)})
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict[
'detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
return output_dict
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
output_dict = run_inference_for_single_image(image_np, detection_graph)
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=8)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
Errors (many of them are redundant):
ImportError Traceback (most recent call last)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
15 try:
---> 16 from . import multiarray
17 except ImportError as exc:
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\overrides.py in <module>
5
----> 6 from numpy.core._multiarray_umath import (
7 add_docstring, implement_array_function, _get_implementing_args)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-1-1e9eee4e6961> in <module>
----> 1 import numpy as np
2 import os
3 import six.moves.urllib as urllib
4 import sys
5 import tarfile
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\__init__.py in <module>
140 from . import _distributor_init
141
--> 142 from . import core
143 from .core import *
144 from . import compat
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
45 Original error was: %s
46 """ % (sys.executable, exc)
---> 47 raise ImportError(msg)
48 finally:
49 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
(removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
1. Check that you are using the Python you expect (you're using c:\users\vfx\anaconda3\envs\tensorflow1\python.exe),
and that you have no directories in your PATH or PYTHONPATH that can
interfere with the Python and numpy versions you're trying to use.
2. If (1) looks fine, you can open a new issue at
https://github.com/numpy/numpy/issues. Please include details on:
- how you installed Python
- how you installed numpy
- your operating system
- whether or not you have multiple versions of Python installed
- if you built from source, your compiler versions and ideally a build log
Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.
Original error was: DLL load failed: The specified module could not be found.
ImportError Traceback (most recent call last)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
15 try:
---> 16 from . import multiarray
17 except ImportError as exc:
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\overrides.py in <module>
5
----> 6 from numpy.core._multiarray_umath import (
7 add_docstring, implement_array_function, _get_implementing_args)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-2-0f0a85121700> in <module>
1 # This is needed to display the images.
----> 2 get_ipython().run_line_magic('matplotlib', 'inline')
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2285 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2286 with self.builtin_trap:
-> 2287 result = fn(*args,**kwargs)
2288 return result
2289
<c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\decorator.py:decorator-gen-108> in matplotlib(self, line)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\magics\pylab.py in matplotlib(self, line)
97 print("Available matplotlib backends: %s" % backends_list)
98 else:
---> 99 gui, backend = self.shell.enable_matplotlib(args.gui)
100 self._show_matplotlib_backend(args.gui, backend)
101
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\interactiveshell.py in enable_matplotlib(self, gui)
3341 """
3342 from IPython.core import pylabtools as pt
-> 3343 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3344
3345 if gui != 'inline':
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\IPython\core\pylabtools.py in find_gui_and_backend(gui, gui_select)
274 """
275
--> 276 import matplotlib
277
278 if gui and gui != 'auto':
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\matplotlib\__init__.py in <module>
139 # cbook must import matplotlib only within function
140 # definitions, so it is safe to import from it here.
--> 141 from . import cbook, rcsetup
142 from matplotlib.cbook import (
143 MatplotlibDeprecationWarning, dedent, get_label, sanitize_sequence)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\matplotlib\cbook\__init__.py in <module>
31 from weakref import WeakMethod
32
---> 33 import numpy as np
34
35 import matplotlib
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\__init__.py in <module>
140 from . import _distributor_init
141
--> 142 from . import core
143 from .core import *
144 from . import compat
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
45 Original error was: %s
46 """ % (sys.executable, exc)
---> 47 raise ImportError(msg)
48 finally:
49 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
(removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
1. Check that you are using the Python you expect (you're using c:\users\vfx\anaconda3\envs\tensorflow1\python.exe),
and that you have no directories in your PATH or PYTHONPATH that can
interfere with the Python and numpy versions you're trying to use.
2. If (1) looks fine, you can open a new issue at
https://github.com/numpy/numpy/issues. Please include details on:
- how you installed Python
- how you installed numpy
- your operating system
- whether or not you have multiple versions of Python installed
- if you built from source, your compiler versions and ideally a build log
Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.
The original error was: DLL load failed: The specified module could not be found.
ImportError Traceback (most recent call last)
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
15 try:
---> 16 from . import multiarray
17 except ImportError as exc:
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\multiarray.py in <module>
11
---> 12 from . import overrides
13 from . import _multiarray_umath
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\overrides.py in <module>
5
----> 6 from numpy.core._multiarray_umath import (
7 add_docstring, implement_array_function, _get_implementing_args)
ImportError: DLL load failed: The specified module could not be found.
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-54-aa270cd948af> in <module>
----> 1 from utils import label_map_util
2
3 from utils import visualization_utils as vis_util
C:\tensorflow1\models\research\object_detection\utils\label_map_util.py in <module>
17 import logging
18
---> 19 import tensorflow as tf
20 from google.protobuf import text_format
21 from object_detection.protos import string_int_label_map_pb2
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\__init__.py in <module>
22
23 # pylint: disable=g-bad-import-order
---> 24 from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
25
26 from tensorflow._api.v1 import app
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\tensorflow\python\__init__.py in <module>
45 # pylint: disable=wildcard-import,g-bad-import-order,g-import-not-at-top
46
---> 47 import numpy as np
48
49 from tensorflow.python import pywrap_tensorflow
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\__init__.py in <module>
140 from . import _distributor_init
141
--> 142 from . import core
143 from .core import *
144 from . import compat
c:\users\vfx\anaconda3\envs\tensorflow1\lib\site-packages\numpy\core\__init__.py in <module>
45 Original error was: %s
46 """ % (sys.executable, exc)
---> 47 raise ImportError(msg)
48 finally:
49 for envkey in env_added:
ImportError:
IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
Importing the multiarray numpy extension module failed. Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
(removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
1. Check that you are using the Python you expect (you're using c:\users\vfx\anaconda3\envs\tensorflow1\python.exe),
and that you have no directories in your PATH or PYTHONPATH that can
interfere with the Python and numpy versions you're trying to use.
2. If (1) looks fine, you can open a new issue at
https://github.com/numpy/numpy/issues. Please include details on:
- how you installed Python
- how you installed numpy
- your operating system
- whether or not you have multiple versions of Python installed
- if you built from source, your compiler versions and ideally a build log
Note: this error has many possible causes, so please don't comment on
an existing issue about this - open a new one instead.
Original error was: DLL load failed: The specified module could not be found.
NameError Traceback (most recent call last)
<ipython-input-3-8920c723e613> in <module>
8
9 # List of the strings that is used to add correct label for each box.
---> 10 PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
NameError: name 'os' is not defined
NameError Traceback (most recent call last)
<ipython-input-4-f921d2932261> in <module>
----> 1 opener = urllib.request.URLopener()
2 opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
3 tar_file = tarfile.open(MODEL_FILE)
4 for file in tar_file.getmembers():
5 file_name = os.path.basename(file.name)
NameError: name 'urllib' is not defined
NameError Traceback (most recent call last)
<ipython-input-5-d55b98fd5a78> in <module>
----> 1 detection_graph = tf.Graph()
2 with detection_graph.as_default():
3 od_graph_def = tf.GraphDef()
4 with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
5 serialized_graph = fid.read()
NameError: name 'tf' is not defined
NameError Traceback (most recent call last)
<ipython-input-6-d9bd1cb2606d> in <module>
----> 1 category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
NameError: name 'label_map_util' is not defined
NameError Traceback (most recent call last)
<ipython-input-12-9d222f84ff65> in <module>
4 # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
5 PATH_TO_TEST_IMAGES_DIR = 'test_images'
----> 6 TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, ) ]
7
8 # Size, in inches, of the output images.
<ipython-input-12-9d222f84ff65> in <listcomp>(.0)
4 # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
5 PATH_TO_TEST_IMAGES_DIR = 'test_images'
----> 6 TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, ) ]
7
8 # Size, in inches, of the output images.
NameError: name 'os' is not defined
NameError Traceback (most recent call last)
<ipython-input-10-b19082c2666b> in <module>
----> 1 for image_path in TEST_IMAGE_PATHS:
2 image = Image.open(image_path)
3 # the array based representation of the image will be used later in order to prepare the
4 # result image with boxes and labels on it.
5 image_np = load_image_into_numpy_array(image)
NameError: name 'TEST_IMAGE_PATHS' is not defined

Related

Error in importing shapefile in jupyter using geopanda

I am using Jupyter from Anaconda and trying to import a shapefile with following command line:
import geopandas as gpd
gdf = gpd.read_file('C:\Downloads\Temp\shapefile\regions.shp')
print (gdf)
gdf.plot()
However, I got following errors:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 gdf = gpd.read_file('C:\Downloads\Temp\shapefile\regions.shp')
2 print (gdf)
3 gdf.plot()
File C:\Anaconda3\lib\site-packages\geopandas\io\file.py:166, in _read_file(filename, bbox, mask, rows, **kwargs)
104 def _read_file(filename, bbox=None, mask=None, rows=None, **kwargs):
105 """
106 Returns a GeoDataFrame from a file or URL.
107
(...)
164 by using the encoding keyword parameter, e.g. ``encoding='utf-8'``.
165 """
--> 166 _check_fiona("'read_file' function")
167 filename = _expand_user(filename)
169 if _is_url(filename):
File C:\Anaconda3\lib\site-packages\geopandas\io\file.py:80, in _check_fiona(func)
78 def _check_fiona(func):
79 if fiona is None:
---> 80 raise ImportError(
81 f"the {func} requires the 'fiona' package, but it is not installed or does "
82 f"not import correctly.\nImporting fiona resulted in: {fiona_import_error}"
83 )
ImportError: the 'read_file' function requires the 'fiona' package, but it is not installed or does not import correctly.
Importing fiona resulted in: DLL load failed while importing ogrext: The specified module could not be found.
I have geopanda installed and not sure what is the problem.

Issue when installing the Spacy python package

I tried to install the Spacy package using the conda terminal with the command:
"conda install -c conda-forge spacy"
Even though the installation seems to be working, when I use Jupyter Notebook and import spacy I get the following error:
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
<ipython-input-1-76a01d9c502b> in <module>
----> 1 import spacy
~\anaconda3\lib\site-packages\spacy\__init__.py in <module>
9
10 # These are imported as part of the API
---> 11 from thinc.api import prefer_gpu, require_gpu, require_cpu # noqa: F401
12 from thinc.api import Config
13
~\anaconda3\lib\site-packages\thinc\__init__.py in <module>
3
4 from .about import __version__
----> 5 from .config import registry
~\anaconda3\lib\site-packages\thinc\config.py in <module>
11 from pydantic.main import ModelMetaclass
12 from pydantic.fields import ModelField
---> 13 from wasabi import table
14 import srsly
15 import catalogue
~\anaconda3\lib\site-packages\wasabi\__init__.py in <module>
10 from .about import __version__ # noqa
11
---> 12 msg = Printer()
~\anaconda3\lib\site-packages\wasabi\printer.py in __init__(self, pretty, no_print, colors, icons, line_max, animation, animation_ascii, hide_animation, ignore_warnings, env_prefix, timestamp)
54 self.pretty = pretty and not env_no_pretty
55 self.no_print = no_print
---> 56 self.show_color = supports_ansi() and not env_log_friendly
57 self.hide_animation = hide_animation or env_log_friendly
58 self.ignore_warnings = ignore_warnings
~\anaconda3\lib\site-packages\wasabi\util.py in supports_ansi()
262 if "ANSICON" in os.environ:
263 return True
--> 264 return _windows_console_supports_ansi()
265
266 return True
~\anaconda3\lib\site-packages\wasabi\util.py in _windows_console_supports_ansi()
234 raise ctypes.WinError()
235
--> 236 console = msvcrt.get_osfhandle(sys.stdout.fileno())
237 try:
238 # Try to enable ANSI output support
UnsupportedOperation: fileno

UPDATED - Further complications - ImportError: `load_weights` requires h5py

I'm working with a previously saved model, however, when I try to load the model, I receive the following error message:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-11-f8d353bad309> in <module>
----> 1 estimator, corpus_encoder, label_encoder, tokenizer = load_model(MODEL_PATH, loss=weighted_binary_crossentropy)
<ipython-input-6-03f944f0a51f> in load_model(model_base_dir, loss, optimizer, metrics)
9 json_file.close()
10 model = model_from_json(loaded_model_json)
---> 11 model.load_weights(os.path.join(MODEL_PATH, 'model.h5'))
12 model.compile(loss=loss, optimizer=optimizer, metrics=metrics)
13 # loading context_encoder
~\anaconda3\envs\davis_env\lib\site-packages\keras\engine\network.py in load_weights(self, filepath, by_name, skip_mismatch, reshape)
1154 """
1155 if h5py is None:
-> 1156 raise ImportError('`load_weights` requires h5py.')
1157 with h5py.File(filepath, mode='r') as f:
1158 if 'layer_names' not in f.attrs and 'model_weights' in f:
ImportError: `load_weights` requires h5py.
I have since install cython and h5py as described in the answers found here and here
Are there any other solutions?
I'm using tensorflow version 1.12.0 and keras version 2.2.4
UPDATE:
When simply trying to import h5py (via ```import h5py``) I receive the following error message:
ImportError Traceback (most recent call last)
<ipython-input-15-c9f0b8c65221> in <module>
----> 1 import h5py
~\anaconda3\envs\davis_env\lib\site-packages\h5py\__init__.py in <module>
32 raise
33
---> 34 from . import version
35
36 if version.hdf5_version_tuple != version.hdf5_built_version_tuple:
~\anaconda3\envs\davis_env\lib\site-packages\h5py\version.py in <module>
15
16 from collections import namedtuple
---> 17 from . import h5 as _h5
18 import sys
19 import numpy
h5py\h5.pyx in init h5py.h5()
ImportError: DLL load failed: The specified procedure could not be found.```

NameError: name 'exit' is not defined/tfnet/darkflow/custom dataset object detection

I'm trying to train my custom dataset by creating yolov3.cfg file and yolov3.weights file with labelled annotations and images using darkflow. However when I'm trying to run tfnet = TFNet(history), it throws an error of "exit not defined".
I have installed darkflow by the following steps:
In Anaconda Prompt:
git clone https://github.com/thtrieu/darkflow.git
cd darkflow
python3 setup.py build_ext –inplace
pip install
then:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import cv2
from darkflow.net.build import TFNet
history = {"model": "C:/Users/Business Intelli/Desktop/Object-Detection/Dataset/yolov3.cfg",
"load": "C:/Users/Business Intelli/Desktop/Object-Detection/Dataset/yolov3.weights",
"batch": 8,
"epoch": 50,
"gpu": 1.0,
"train": True,
"annotation": "C:/Users/Business Intelli/Desktop/Object-Detection/Dataser/Stumps",
"dataset": "C:/Users/Business Intelli/Desktop/Object-Detection/Dataser/Stumps"}
tfnet = TFNet(history)
Parsing C:/Users/Business Intelli/Desktop/Object-Detection/Dataset/yolov3.cfg
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-6f6b945047c5> in <module>
----> 1 tfnet = TFNet(history)
~\Anaconda3\lib\site-packages\darkflow\net\build.py in __init__(self, FLAGS, darknet)
56
57 if darknet is None:
---> 58 darknet = Darknet(FLAGS)
59 self.ntrain = len(darknet.layers)
60
~\Anaconda3\lib\site-packages\darkflow\dark\darknet.py in __init__(self, FLAGS)
15
16 print('Parsing {}'.format(self.src_cfg))
---> 17 src_parsed = self.parse_cfg(self.src_cfg, FLAGS)
18 self.src_meta, self.src_layers = src_parsed
19
~\Anaconda3\lib\site-packages\darkflow\dark\darknet.py in parse_cfg(self, model, FLAGS)
66 cfg_layers = cfg_yielder(*args)
67 meta = dict(); layers = list()
---> 68 for i, info in enumerate(cfg_layers):
69 if i == 0: meta = info; continue
70 else: new = create_darkop(*info)
~\Anaconda3\lib\site-packages\darkflow\utils\process.py in cfg_yielder(model, binary)
314 #-----------------------------------------------------
315 else:
--> 316 exit('Layer {} not
implemented'.format(d['type']))
317
318 d['_size'] = list([h, w, c, l, flat])
NameError: name 'exit' is not defined
So I faced the same problem and the issue is with the process.py file in
darkflow --> utils folder.
Apparently the exit() method is not in-built so you have to add this line in process.py
from sys import exit
Note : If your code is reaching this point it means the models can't read the layers. The weights file that I downloaded for yolov3 gave me same trouble and I couldn't find a link that has a proper weight file for yolov3 that works in darkflow. So I had to stick to yolo.cfg and yolo.weights .

Theano step gives File in wrong format error

I am trying to replicate the example
Getting Started PyMC3.
on Windows 2012 R2.
The step
from pymc3 import Model, Normal, HalfNormal
gives
D:\Anaconda3\libs/python35.lib: error adding symbols: File in wrong format
collect2.exe: error: ld returned 1 exit status
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
D:\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py in <module>()
64 if version != getattr(lazylinker_ext, '_version', None):
---> 65 raise ImportError()
66 except ImportError:
ImportError:
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
D:\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py in <module>()
81 if version != getattr(lazylinker_ext, '_version', None):
---> 82 raise ImportError()
83 except ImportError:
ImportError:
During handling of the above exception, another exception occurred:
Exception Traceback (most recent call last)
<ipython-input-4-582c90a634a6> in <module>()
----> 1 from pymc3 import Model, Normal, HalfNormal
D:\Anaconda3\lib\site-packages\pymc3\__init__.py in <module>()
1 __version__ = "3.0"
2
----> 3 from .core import *
4 from .distributions import *
5 from .math import *
D:\Anaconda3\lib\site-packages\pymc3\core.py in <module>()
1 from .vartypes import *
----> 2 from .model import *
3 from .theanof import *
4 from .blocking import *
5 import numpy as np
D:\Anaconda3\lib\site-packages\pymc3\model.py in <module>()
1 from .vartypes import *
2
----> 3 from theano import theano, tensor as t, function
4 from theano.tensor.var import TensorVariable
5
D:\Anaconda3\lib\site-packages\theano\__init__.py in <module>()
53 object2, utils
54
---> 55 from theano.compile import \
56 SymbolicInput, In, \
57 SymbolicOutput, Out, \
D:\Anaconda3\lib\site-packages\theano\compile\__init__.py in <module>()
7 SpecifyShape, specify_shape, register_specify_shape_c_code)
8
----> 9 from theano.compile.function_module import *
10
11 from theano.compile.mode import *
D:\Anaconda3\lib\site-packages\theano\compile\function_module.py in <module>()
16 from theano import gof
17 from theano.compat.python2x import partial
---> 18 import theano.compile.mode
19 from theano.compile.io import (
20 In, SymbolicInput, SymbolicInputKit, SymbolicOutput)
D:\Anaconda3\lib\site-packages\theano\compile\mode.py in <module>()
9 import theano
10 from theano import gof
---> 11 import theano.gof.vm
12 from theano.configparser import config, AddConfigVar, StrParam
13 from theano.compile.ops import register_view_op_c_code, _output_guard
D:\Anaconda3\lib\site-packages\theano\gof\vm.py in <module>()
566
567 try:
--> 568 from . import lazylinker_c
569
570 class CVM(lazylinker_c.CLazyLinker, VM):
D:\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py in <module>()
115 args = cmodule.GCC_compiler.compile_args()
116 cmodule.GCC_compiler.compile_str(dirname, code, location=loc,
--> 117 preargs=args)
118 # Save version into the __init__.py file.
119 init_py = os.path.join(loc, '__init__.py')
D:\Anaconda3\lib\site-packages\theano\gof\cmodule.py in compile_str(module_name, src_code, location, include_dirs, lib_dirs, libs, preargs, py_module)
2008 # difficult to read.
2009 raise Exception('Compilation failed (return status=%s): %s' %
-> 2010 (status, compile_stderr.replace('\n', '. ')))
2011 elif config.cmodule.compilation_warning and compile_stderr:
2012 # Print errors just below the command line.
I have for gcc
C:\>gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=C:/TDM-GCC-64/bin/../libexec/gcc/x86_64-w64-mingw32/5.1.0/lt
o-wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../../../src/gcc-5.1.0/configure --build=x86_64-w64-mingw32 --e
nable-targets=all --enable-languages=ada,c,c++,fortran,lto,objc,obj-c++ --enable
-libgomp --enable-lto --enable-graphite --enable-cxx-flags=-DWINPTHREAD_STATIC -
-disable-build-with-cxx --disable-build-poststage1-with-cxx --enable-libstdcxx-d
ebug --enable-threads=posix --enable-version-specific-runtime-libs --enable-full
y-dynamic-string --enable-libstdcxx-threads --enable-libstdcxx-time --with-gnu-l
d --disable-werror --disable-nls --disable-win32-registry --prefix=/mingw64tdm -
-with-local-prefix=/mingw64tdm --with-pkgversion=tdm64-1 --with-bugurl=http://td
m-gcc.tdragon.net/bugs
Thread model: posix
gcc version 5.1.0 (tdm64-1)
what am i missing?
thanks
Whatever the issue was creating a python 3.4 environment together with
conda install mingw libpython
solved it.
What solved my issue is installing Python 2.7 version of anaconda
I got the same error using ipython. Using just python I imported theano without problem. Subsequent uses with ipython worked fine after the first compilation with just python.

Categories

Resources