I followed the steps described on their Github to install the Object Detection API and then I ran this script:
python object_detection/builders/model_builder_test.py
and the test were successful, so I assumed everything was setup correctly. Next I tried to run the Jupyter Notebook with qtconsole to detect objects in the test images. However it returns this error:
AttributeError Traceback (most recent call last)
<ipython-input-3-be6fe1ba8733> in <module>()
----> 1 from utils import label_map_util
2
3 from utils import visualization_utils as vis_util
4
~\Desktop\Objectdetection\models-master\object_detection\utils\label_map_util.py in <module>()
20 import tensorflow as tf
21 from google.protobuf import text_format
---> 22 from object_detection.protos import string_int_label_map_pb2
23
24
~\Desktop\Objectdetection\models-master\object_detection\object_detection.py in <module>()
114
115
--> 116 label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
117 categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
118 category_index = label_map_util.create_category_index(categories)
AttributeError: module 'utils.label_map_util' has no attribute 'load_labelmap'
Does anyone have an idea what the cause of this problem is?
Thanks.
In the file ~\Desktop\Objectdetection\models-master\object_detection\utils\label_map_util.py
Try changing this:
from object_detection.protos import string_int_label_map_pb2
to this:
from protos import string_int_label_map_pb2
Explanation:
The function load_labelmap in the module label_map_util isn't accessible because the import of string_int_label_map_pb2 is failing.
You can see this if you look at the output of print(dir(label_map_util)).
When using object_detection.protos:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'logging', 'text_format', 'tf']
After the changing the relative path to protos the function should be accessible:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_validate_label_map', 'convert_label_map_to_categories', 'create_category_index', 'get_label_map_dict', 'load_labelmap', 'logging', 'string_int_label_map_pb2', 'text_format', 'tf']
Related
I am trying to train the model for question answering with a finetuned Q&A BERT.
import torch
from transformers import BertForQuestionAnswering, BertTokenizer
model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
while i trying to use tokenizer for pretraining the bert-large-uncased-whole-word-masking-finetuned-squad model:I am getting the below error.
tokenizer = BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-29-d478833618be> in <module>
----> 1 tokenizer = BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
1 frames
/usr/local/lib/python3.7/dist-packages/transformers/tokenization_utils_base.py in _from_pretrained(cls, resolved_vocab_files, pretrained_model_name_or_path, init_configuration, use_auth_token, cache_dir, *init_inputs, **kwargs)
1857 def _save_pretrained(
1858 self,
-> 1859 save_directory: str,
1860 file_names: Tuple[str],
1861 legacy_format: bool = True,
ModuleNotFoundError: No module named 'transformers.models.auto.configuration_auto'
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
--------------------------------------------------------------------------
I am using the new version of transformer only in my notebook. But its giving me this error. Can someone help me with this issue?
Try with:
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
model = AutoModelForQuestionAnswering.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad")
I suspect that you have code from a previous version in your cache. Try
transformers.BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad', cache_dir="./")
enter image description here!python encode_images.py --optimizer=lbfgs --face_mask=True --iterations=6 --use_lpips_loss=0 --use_discriminator_loss=0 --output_video=True aligned_images/ generated_images/ latent_representations/
print("\n************ Latent code optimization finished! ***************")
2021-08-24 13:33:11.033451: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_101.dll
Traceback (most recent call last):
File "encode_images.py", line 12, in
import dnnlib.tflib as tflib
File "C:\Users\bkvij\Office Rapid Innovation\StyleGAN Face Morphing - Arxiv Insights\stylegan-encoder\dnnlib\tflib_init_.py", line 8, in
from . import autosummary
File "C:\Users\bkvij\Office Rapid Innovation\StyleGAN Face Morphing - Arxiv Insights\stylegan-encoder\dnnlib\tflib\autosummary.py", line 31, in
from . import tfutil
File "C:\Users\bkvij\Office Rapid Innovation\StyleGAN Face Morphing - Arxiv Insights\stylegan-encoder\dnnlib\tflib\tfutil.py", line 34, in
def shape_to_list(shape: Iterable[tf.Dimension]) -> List[Union[int, None]]:
AttributeError: module 'tensorflow' has no attribute 'Dimension'
It's because tf.Dimension is deprecated.
Go to stylegan/dnnlib/tflib/tfutil.py and change the tf.Dimension in line 34 to tf.compat.v1.Dimension.
I think you're using TensorFlow v2, use google colape and it will fix the problem for you, otherwise, you will need to make a virtual environment with Python 3.6 TensorFlow 1.10 cuDNN 7.3.1 and it will solve the problem
To expand on Faezeh's answer, you'll have to make the following edits to tfutils.py
From
tf.Dimension (line 34)
tf.variable_scope (line 74)
tf.Session (line 128)
To
tf.compat.v1.Dimension
tf.compat.v1.variable_scope
tf.compat.v1.Session
alternatively, you could just download tensorflow 1.x and save yourself the hassle
you can use it on terminal ' pip install tensorflow-addons==0.14.0
Enviroment
Python 3.6.3
Kivy master
OS: Linux Mint 18.2(based on Ubuntu 16.04 LTS)
Code
Hi, I'm writing unittest of kivy.animation. When I ran the code below
import unittest
from time import time, sleep
from kivy.animation import Animation
from kivy.uix.widget import Widget
from kivy.clock import Clock
class AnimationTestCase(unittest.TestCase):
SLEEP_DURATION = .3
TIMES = 2
def sleep(self, t):
start = time()
while time() < start + t:
sleep(.01)
Clock.tick()
def test_animation(self):
for index in range(self.TIMES):
print('----------------------------------')
with self.subTest(index=index):
w = Widget()
a = Animation(x=100, d=.2)
print('a:', a)
a.start(w)
self.sleep(self.SLEEP_DURATION)
print('instances_:', Animation._instances)
self.assertEqual(len(Animation._instances), 0)
output is
----------------------------------
a: <kivy.animation.Animation object at 0x7f0afb31c660>
instances_: set()
----------------------------------
a: <kivy.animation.Animation object at 0x7f0afc20b180>
instances_: {<kivy.animation.Animation object at 0x7f0afc20b250>, <kivy.animation.Animation object at 0x7f0afb31c660>}
======================================================================
FAIL: test_animation (kivy.tests.test_animations.AnimationTestCase) (index=1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/tmp/firefox/kivy/kivy/tests/test_animations.py", line 34, in test_animation
self.assertEqual(len(Animation._instances), 0)
AssertionError: 2 != 0
----------------------------------------------------------------------
Ran 1 test in 0.822s
FAILED (failures=1)
Either of
Increase SLEEP_DURATION (for example SLEEP_DURATION = 2) or
TIMES = 1
will fix this error.
Is this correct behavior or bug?
The cause of this error is kivy.modules.inspector.
After I removed this line from config.ini,
[modules]
inspector = # <= remove this line
the program behave how I expect. Seems like ScrollView inside inspector creates Animation internally, and it makes my test fails.
I have discovered something unexpected when playing with cyclic imports. I have two files in the same directory:
a.py
import b
print("hello from a")
b.py
import a
print("hello from b")
Running either python3 a.py and python3 b.py does not result in a cyclic import related error. I know that the first imported module is imported under the name __main__, but I still do not understand this behavior. For example, running python3 a.py or python -m a produces the following output:
hi from a
hi from b
hi from a
Looking at the output of print(sys.modules.keys()), I can see that both modules are somehow already imported when checking it, even when importing the sys module as the first thing in one of the modules.
I did not use sys.modules properly before answering my own question.
This does not happen if neither of the cyclic imported modules is the __main__ module. My Python version is Python 3.6.3 on Ubuntu 17.10.
It still happens, but there is a visible error only if there is actually something you use from one of the cyclically imported modules.
See my own answer for clarifications.
The answer to my question
I have discovered the answer. I will try to sketch an explanation:
Executing python3 a.py imports the module in file a.py as __main__:
import b in module __main__:
import a in module b -> Imports the module in file a.py as a
import b in module a -> Nothing happens, already imported that module
print('hello from a') in a.py (executing module a)
import a in module b finished
print('hello from b') in b.py (executing module b)
import b in module __main__ finished
print('hello from a') in a.py(executing module __main__)
The problem is that there is no cyclic import error per se. A module is imported only once, and after that, other imports of the same module can be seen as no-ops.
This operation can be seen as adding a key to the sys.modules dictionary corresponding to the name of the imported module and then setting attributes on the module object associated with that key as it gets executed. So if the key is already present in the dictionary (on a second import of the same module), nothing happens on the second import. The already imported above means already present in the sys.modules dictionary. This reflects the procedural nature of Python (being originally implemented in C) and the fact that anything in Python is an object.
The lurking problem
In order to show the fact that the problem associated with cyclic imports is still present, let's add a function to module b and try to use it from module a.
a.py
import b
b.f()
b.py
import a
def f():
print('hello from b.f()')
Executing now python a.py imports the module in file a.py as __main__:
import b in module __main__:
import a in module b -> Imports the module in file a.py as a
import b in module a -> Nothing happens, already imported that module
b.f() -> AttributeError: module 'b' has no attribute 'f'
Note: The line b.f() can be further simplified to b.f and the error will still occur. This is because b.f() first accesses the attribute f of module object b, which happens to be a function object, and then tries to call it. I wanted to point out again the object oriented nature of Python.
The from ... import ... statement
It is interesting to mention that using the from ... import ... form gives another error, even though the reason is the same:
a.py
from b import f
f()
b.py
import a
def f():
printf('hello from b.f()')
Executing python a.py imports the module in file a.py as __main__:
from b import f in module __main__ actually imports the whole module (adds it to sys.modules and executes its body), but binds only the name f in the current module namespace:
import a in module b -> Imports the module in file a.py as a
from b import f in module a -> ImportError: cannot import name f (because the first execution of from b import f did not get to see the definition of the function object f in module b)
In this last case, the from ... import ... itself fails with an error because the interpreter knows earlier in time that you are trying to access something in that module which does not exist. Compare it to the first AttributeError, where the program did not see any problem until it tried to access attribute f (in the expression b.f).
The double execution problem of the code in the main module
When importing the module in the file used to start the program (imported as __main__ first) from another module, the code in that module gets executed twice and any side effects in that module execution will happen twice too. This is why it is not recommended to import the main module of the program again in other modules.
Using sys.modules to confirm my conclusions above
I will show how checking the contents of sys.modules can clarify this problem:
a.py
import sys
assert '__main__' in sys.modules.keys()
print(f'{__name__}:')
print('\ta imported:', 'a' in sys.modules.keys())
print('\tb imported:', 'b' in sys.modules.keys())
import b
b.f()
b.py
import sys
assert '__main__' in sys.modules.keys()
print(f'{__name__}:')
print('\ta imported:', 'a' in sys.modules.keys())
print('\tb imported:', 'b' in sys.modules.keys())
import a
assert False # Control flow never gets here
def f():
print('hi from b.f()')
The output of python3 a.py:
__main__:
a imported: False
b imported: False
b:
a imported: False
b imported: True
a:
a imported: True
b imported: True
Traceback (most recent call last):
File "a.py", line 8, in <module>
import b
File "/home/andrei/PycharmProjects/untitled/b.py", line 8, in <module>
import a
File "/home/andrei/PycharmProjects/untitled/a.py", line 10, in <module>
b.f()
AttributeError: module 'b' has no attribute 'f'
I am doing Machine Learning Course from Coursera by University of Washington. In which I am using iPython's graphlab. During practise when I execute below command:
sales = graphlab.SFrame('home_data.gl/')
I am getting error.
IOError Traceback (most recent call last)
<ipython-input-2-e6a249ea422b> in <module>()
----> 1 sales = graphlab.SFrame('home_data.gl/')
C:\Users\chinesh\Anaconda2\envs\gl-env\lib\site-packages\graphlab\data_structures\sframe.pyc in __init__(self, data, format, _proxy)
951 pass
952 else:
--> 953 raise ValueError('Unknown input type: ' + format)
954
955 sframe_size = -1
C:\Users\chinesh\Anaconda2\envs\gl-env\lib\site-packages\graphlab\cython\context.pyc in __exit__(self, exc_type, exc_value, traceback)
47 if not self.show_cython_trace:
48 # To hide cython trace, we re-raise from here
---> 49 raise exc_type(exc_value)
50 else:
51 # To show the full trace, we do nothing and let exception propagate
IOError: C:\Users\chinesh\home_data.gl not found.
where i can find home_data.gl in my computer or the problem is something else ..
You need to have your ipynb file and the data file in the same directory for the above to work. Alternatively, specify the full or relative path of the data file in the function
sales = graphlab.SFrame('C:\FULL-PATH\home_data.gl/')
Here is a link to the course reading for how to arrange your directories for the course. https://www.coursera.org/learn/ml-foundations/supplement/IT04V/reading-where-should-my-files-go
Make sure to download the zip folder to the same folder where you will work on this data. For example: I downloaded the zip file to Downloads then I opened my notebook from the download file
Just follow the instructions and download the training data into the ipython working directory.
Go to terminal and run:
unzip home_data.gl.zip
You will see following files in directory home_data.gl:
Now in ipython, run:
sales = graphlab.SFrame('home_data.gl/')
sales
which will display the data in tabular format: