My problem is when i try to run this code
if log_to_tensorboard: from torch.utils.tensorboard import SummaryWriter
if log_to_tensorboard: writer = SummaryWriter()
I get this error:
(import SummaryWriter works without any problems, but then I try run "writer = SummaryWriter()" and it doesnt work)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-d77d9d09e62b> in <module>
----> 1 writer = SummaryWriter()
/anaconda3/lib/python3.6/site-packages/torch/utils/tensorboard/writer.py in __init__(self, log_dir, comment, purge_step, max_queue, flush_secs, filename_suffix)
223 # and recreated later as needed.
224 self.file_writer = self.all_writers = None
--> 225 self._get_file_writer()
226
227 # Create default bins for histograms, see generate_testdata.py in tensorflow/tensorboard
/anaconda3/lib/python3.6/site-packages/torch/utils/tensorboard/writer.py in _get_file_writer(self)
254 if self.all_writers is None or self.file_writer is None:
255 self.file_writer = FileWriter(self.log_dir, self.max_queue,
--> 256 self.flush_secs, self.filename_suffix)
257 self.all_writers = {self.file_writer.get_logdir(): self.file_writer}
258 if self.purge_step is not None:
/anaconda3/lib/python3.6/site-packages/torch/utils/tensorboard/writer.py in __init__(self, log_dir, max_queue, flush_secs, filename_suffix)
64 log_dir = str(log_dir)
65 self.event_writer = EventFileWriter(
---> 66 log_dir, max_queue, flush_secs, filename_suffix)
67
68 def get_logdir(self):
/anaconda3/lib/python3.6/site-packages/tensorboard/summary/writer/event_file_writer.py in __init__(self, logdir, max_queue_size, flush_secs, filename_suffix)
71 """
72 self._logdir = logdir
---> 73 if not tf.io.gfile.exists(logdir):
74 tf.io.gfile.makedirs(logdir)
75 self._file_name = os.path.join(logdir, "events.out.tfevents.%010d.%s.%s.%s" %
/anaconda3/lib/python3.6/site-packages/tensorboard/lazy.py in __getattr__(self, attr_name)
63 class LazyModule(types.ModuleType):
64 def __getattr__(self, attr_name):
---> 65 return getattr(load_once(self), attr_name)
66
67 def __dir__(self):
AttributeError: module 'tensorflow' has no attribute 'io'
How to fix it?
I uninstall and install tensorflow, upgraded tensorboard and torch - that didnt help me
I met the same problem. And my solution is as follow:
Check to see if tensorflow-tensorboard is exists.
pip uninstall tensorflow-tensorboard
install tensorboard==1.14
because an error occurred: TensorBoard logging requires TensorBoard with Python summary writer installed. This should be available in 1.14 or above.
ref: https://github.com/pytorch/pytorch/issues/20140
pip install tensorboard==1.14.0
I was able to solve this problem by using the solution recommended here which suggests to:
pip install tensorflow-io
You can upgrade the version of tensorboard
Related
im trying to run :
models.vgg16(pretrained=True)
and get pretained model for pytorch but i get as an error this, this error already was asked about before- but answer from there aren't helping me :/
I tried to upgrade tqdm, and twine but with no success.
thanks..
full log:
TqdmKeyError Traceback
(most recent call last)
<ipython-input-13-f93ae0d83650> in <module>
2 from torchvision import transforms, datasets, models
3
----> 4 model = models.vgg16(pretrained=True)
5
6 # n_inputs = model.classifier[6].in_features
c:\users\user\appdata\local\programs\python\python37\lib\site-packages\torchvision\models\vgg.py in vgg16(pretrained, progress, **kwargs)
148 progress (bool): If True, displays a progress bar of the download to stderr
149 """
--> 150 return _vgg('vgg16', 'D', False, pretrained, progress, **kwargs)
151
152
c:\users\user\appdata\local\programs\python\python37\lib\site-packages\torchvision\models\vgg.py in _vgg(arch, cfg, batch_norm, pretrained, progress, **kwargs)
91 if pretrained:
92 state_dict = load_state_dict_from_url(model_urls[arch],
---> 93 progress=progress)
94 model.load_state_dict(state_dict)
95 return model
c:\users\user\appdata\local\programs\python\python37\lib\site-packages\torch\hub.py in load_state_dict_from_url(url, model_dir, map_location, progress, check_hash, file_name)
553 r = HASH_REGEX.search(filename) # r is Optional[Match[str]]
554 hash_prefix = r.group(1) if r else None
--> 555 download_url_to_file(url, cached_file, hash_prefix, progress=progress)
556
557 if _is_legacy_zip_format(cached_file):
c:\users\user\appdata\local\programs\python\python37\lib\site-packages\torch\hub.py in download_url_to_file(url, dst, hash_prefix, progress)
443 sha256 = hashlib.sha256()
444 with tqdm(total=file_size, disable=not progress,
--> 445 unit='B', unit_scale=True, unit_divisor=1024) as pbar:
446 while True:
447 buffer = u.read(8192)
c:\users\user\appdata\local\programs\python\python37\lib\site-packages\tqdm\_tqdm.py in __init__(self, iterable, desc, total, leave, file, ncols, mininterval, maxinterval, miniters, ascii, disable, unit, unit_scale, dynamic_ncols, smoothing, bar_format, initial, position, postfix, gui, **kwargs)
TqdmKeyError: "Unknown argument(s): {'unit_divisor': 1024}"
Reinstalling and upgrading tqdm worked for me!
pip uninstall tqdm
pip install tqdm
What version of tqdm do you have? I upgraded to 4.63.1 and it worked
I am doing some task related to image captioning and I have loaded the weights of inception model like this
model = InceptionV3(weights='imagenet')
But I am getting error like this:
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
What should I do? Please help.
Here is the full output of above code.
1 . --------------------------------------------------------------------------- AttributeError Traceback (most recent
call last) in ()
1 # Load the inception v3 model
----> 2 model = InceptionV3(include_top=True,weights='imagenet')
3 # InceptionV3(weights='imagenet')
~/anaconda3/lib/python3.6/site-packages/keras/applications/__init__.py
in wrapper(*args, **kwargs)
26 kwargs['models'] = models
27 kwargs['utils'] = utils
---> 28 return base_fun(*args, **kwargs)
29
30 return wrapper
~/anaconda3/lib/python3.6/site-packages/keras/applications/inception_v3.py
in InceptionV3(*args, **kwargs)
9 #keras_modules_injection
10 def InceptionV3(*args, **kwargs):
---> 11 return inception_v3.InceptionV3(*args, **kwargs)
12
13
~/anaconda3/lib/python3.6/site-packages/keras_applications/inception_v3.py
in InceptionV3(include_top, weights, input_tensor, input_shape,
pooling, classes, **kwargs)
155
156 if input_tensor is None:
--> 157 img_input = layers.Input(shape=input_shape)
158 else:
159 if not backend.is_keras_tensor(input_tensor):
~/anaconda3/lib/python3.6/site-packages/keras/engine/input_layer.py
in Input(shape, batch_shape, name, dtype, sparse, tensor)
176 name=name, dtype=dtype,
177 sparse=sparse,
--> 178 input_tensor=tensor)
179 # Return tensor including _keras_shape and _keras_history.
180 # Note that in this case train_output and test_output are the same pointer.
~/anaconda3/lib/python3.6/site-packages/keras/legacy/interfaces.py
in wrapper(*args, **kwargs)
89 warnings.warn('Update your `' + object_name + '` call to the ' +
90 'Keras 2 API: ' + signature, stacklevel=2)
---> 91 return func(*args, **kwargs)
92 wrapper._original_function = func
93 return wrapper
~/anaconda3/lib/python3.6/site-packages/keras/engine/input_layer.py
in __init__(self, input_shape, batch_size, batch_input_shape, dtype,
input_tensor, sparse, name)
37 if not name:
38 prefix = 'input'
---> 39 name = prefix + '_' + str(K.get_uid(prefix))
40 super(InputLayer, self).__init__(dtype=dtype, name=name)
41
~/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py
in get_uid(prefix)
72 """
73 global _GRAPH_UID_DICTS
---> 74 graph = tf.get_default_graph()
75 if graph not in _GRAPH_UID_DICTS:
76 _GRAPH_UID_DICTS[graph] = defaultdict(int)
AttributeError: module 'tensorflow' has no attribute
'get_default_graph'
Change
Import keras.<something>.<something>
to
Import tensorflow.keras.<something>.<something>
where "something" refers to the module you want to import. It worked for me.
Another cause due to which this is happening is that in tensorflow_backend.py
located in : lib/python3.6/site-packages/keras/backend/
uses tf.compat.v1.get_default_graph for obtaining graph
instead of tf.get_default_graph.
By replacing this in the directory this problem can be solved successfully.
Keras integrated into TensorFlow 2.0
The article below cleared this up for me. Key points are:
Keras is included in the TensorFlow 2.0 package
So no need to install the stand-alone Keras package in your environment
And now the fore-mentioned solutions of using "from tensorflow.keras…" make sense.
After recognizing that and making the change, my code samples work with some minor changes here and there.
https://www.pyimagesearch.com/2019/10/21/keras-vs-tf-keras-whats-the-difference-in-tensorflow-2-0/
I fixed this problem by replacing tensorflow.keras.* to tensorflow.python.keras.*
Working example:
from tensorflow.python.keras.models import Sequential
Two Steps solved this issue for me in Google Colabs
First Step
Change
from keras.something import something
To
from tensorflow.keras.something import something
Second Step
Use
tf.compat.v1.get_default_graph
instead of tf.get_default_graph
Reason
https://www.pyimagesearch.com/2019/10/21/keras-vs-tf-keras-whats-the-difference-in-tensorflow-2-0/
In my case, replacing
from keras.models import models
with:
from tensorflow.keras.models import models
in my script, fixed this problem.
This code has been working until last tf_hub update. I think, the problem is in the tensorflow_text module, that I haven't installed. But when I try to execute "pip install tensorflow_text==2.3.0" command (copied from the official tf_hub page) it throws back the error. I also tried to install it manually from github repo, but the package is still not available. Thanks.
embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
G:\Anaconda\lib\site-packages\tensorflow\python\training\py_checkpoint_reader.py in get_tensor(self, tensor_str)
69 return CheckpointReader.CheckpointReader_GetTensor(
---> 70 self, compat.as_bytes(tensor_str))
71 # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the
RuntimeError:
During handling of the above exception, another exception occurred:
OpError Traceback (most recent call last)
<ipython-input-8-c716b77a9bc1> in <module>
----> 1 embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
G:\Anaconda\lib\site-packages\tensorflow_hub\module_v2.py in load(handle, tags, options)
112 module_path, tags=tags, options=options)
113 else:
--> 114 obj = tf_v1.saved_model.load_v2(module_path, tags=tags)
115 obj._is_hub_module_v1 = is_hub_module_v1 # pylint: disable=protected-access
116 return obj
G:\Anaconda\lib\site-packages\tensorflow\python\saved_model\load.py in load(export_dir, tags, options)
601 ValueError: If `tags` don't match a MetaGraph in the SavedModel.
602 """
--> 603 return load_internal(export_dir, tags, options)
604
605
G:\Anaconda\lib\site-packages\tensorflow\python\saved_model\load.py in load_internal(export_dir, tags, options, loader_cls)
631 try:
632 loader = loader_cls(object_graph_proto, saved_model_proto, export_dir,
--> 633 ckpt_options)
634 except errors.NotFoundError as err:
635 raise FileNotFoundError(
G:\Anaconda\lib\site-packages\tensorflow\python\saved_model\load.py in __init__(self, object_graph_proto, saved_model_proto, export_dir, ckpt_options)
129
130 self._load_all()
--> 131 self._restore_checkpoint()
132
133 for node in self._nodes:
G:\Anaconda\lib\site-packages\tensorflow\python\saved_model\load.py in _restore_checkpoint(self)
328 self._checkpoint_options).expect_partial()
329 else:
--> 330 load_status = saver.restore(variables_path, self._checkpoint_options)
331 load_status.assert_existing_objects_matched()
332 checkpoint = load_status._checkpoint
G:\Anaconda\lib\site-packages\tensorflow\python\training\tracking\util.py in restore(self, save_path, options)
1280 dtype_map = reader.get_variable_to_dtype_map()
1281 try:
-> 1282 object_graph_string = reader.get_tensor(base.OBJECT_GRAPH_PROTO_KEY)
1283 except errors_impl.NotFoundError:
1284 # The object graph proto does not exist in this checkpoint. Try the
G:\Anaconda\lib\site-packages\tensorflow\python\training\py_checkpoint_reader.py in get_tensor(self, tensor_str)
72 # issue with throwing python exceptions from C++.
73 except RuntimeError as e:
---> 74 error_translator(e)
75
76
G:\Anaconda\lib\site-packages\tensorflow\python\training\py_checkpoint_reader.py in error_translator(e)
46 raise errors_impl.InternalError(None, None, error_message)
47 else:
---> 48 raise errors_impl.OpError(None, None, error_message, errors_impl.UNKNOWN)
49
50
OpError:
C:\Users\usr>pip install tensorflow_text v==2.3.0
ERROR: Could not find a version that satisfies the requirement tensorflow_text (from versions: none)
ERROR: No matching distribution found for tensorflow_text
This code is working fine in Tensorflow 2.7 in Anaconda jupyter notebook. Please specify the Tensorflow version you are using while running this code.
!pip install tensorflow-hub
import tensorflow_hub as hub
embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
There is no need to install the tensorflow_text to run this piece of code. However I have found there is typo error in your traceback error while installing tensorflow_text.
It should be as below:
!pip install tensorflow_text==2.3.0
Please check this link to access the Universal Sentence Encoder on TF-Hub.
Does anyone know how to resolve this issue? I'm using Google Collab to try run my code but I cant seem to fix this issue.
Note: I have an Environment setup in Pycharm where this issue doesn't appear and the code runs (just very laggy due to intense training).
Currently running on Tensorflow 2.0 and Python 3.7
NameError Traceback (most recent call last)
<ipython-input-5-14174aa69df8> in <module>()
666
667 # Find Initial State
--> 668 cur_state = env.reset()
669 dqn_agent = DQN(env, cur_state.shape)
670 dqn_agent.save_model('models/deepq.h5')
4 frames
<ipython-input-5-14174aa69df8> in reset(self)
303 self.car = Car(self.world, *self.track[0][1:4])
304
--> 305 return self.step(None)[0]
306
307 def step(self, action):
<ipython-input-5-14174aa69df8> in step(self, action)
319 self.t += 1.0 / FPS
320
--> 321 self.state = self.render("state_pixels")
322
323 step_reward = 0
<ipython-input-5-14174aa69df8> in render(self, mode)
340 assert mode in ['human', 'state_pixels', 'rgb_array']
341 if self.viewer is None:
--> 342 from gym.envs.classic_control import rendering
343 self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H)
344 self.score_label = pyglet.text.Label('0000', font_size=36,
/usr/local/lib/python3.6/dist-packages/gym/envs/classic_control/rendering.py in <module>()
25
26 try:
---> 27 from pyglet.gl import *
28 except ImportError as e:
29 raise ImportError('''
/usr/local/lib/python3.6/dist-packages/pyglet/gl/__init__.py in <module>()
223 elif compat_platform == 'darwin':
224 from .cocoa import CocoaConfig as Config
--> 225 del base # noqa: F821
226
227 # XXX remove
NameError: name 'base' is not defined
Link to the code - https://github.com/eoinmca/Final_Year_Project/blob/master/google_collab_version.py
If anyone tries to reproduce this error you need to ensure collab is running tf2 not tf1
Prerequisites to set up collab
!pip install box2d-py
!pip install gym[Box_2D]
print(tf.__version__)
# Run next lines if not on tf2
!pip uninstall tensorflow
!pip install tensorflow==2.0.0
I am doing some task related to image captioning and I have loaded the weights of inception model like this
model = InceptionV3(weights='imagenet')
But I am getting error like this:
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
What should I do? Please help.
Here is the full output of above code.
1 . --------------------------------------------------------------------------- AttributeError Traceback (most recent
call last) in ()
1 # Load the inception v3 model
----> 2 model = InceptionV3(include_top=True,weights='imagenet')
3 # InceptionV3(weights='imagenet')
~/anaconda3/lib/python3.6/site-packages/keras/applications/__init__.py
in wrapper(*args, **kwargs)
26 kwargs['models'] = models
27 kwargs['utils'] = utils
---> 28 return base_fun(*args, **kwargs)
29
30 return wrapper
~/anaconda3/lib/python3.6/site-packages/keras/applications/inception_v3.py
in InceptionV3(*args, **kwargs)
9 #keras_modules_injection
10 def InceptionV3(*args, **kwargs):
---> 11 return inception_v3.InceptionV3(*args, **kwargs)
12
13
~/anaconda3/lib/python3.6/site-packages/keras_applications/inception_v3.py
in InceptionV3(include_top, weights, input_tensor, input_shape,
pooling, classes, **kwargs)
155
156 if input_tensor is None:
--> 157 img_input = layers.Input(shape=input_shape)
158 else:
159 if not backend.is_keras_tensor(input_tensor):
~/anaconda3/lib/python3.6/site-packages/keras/engine/input_layer.py
in Input(shape, batch_shape, name, dtype, sparse, tensor)
176 name=name, dtype=dtype,
177 sparse=sparse,
--> 178 input_tensor=tensor)
179 # Return tensor including _keras_shape and _keras_history.
180 # Note that in this case train_output and test_output are the same pointer.
~/anaconda3/lib/python3.6/site-packages/keras/legacy/interfaces.py
in wrapper(*args, **kwargs)
89 warnings.warn('Update your `' + object_name + '` call to the ' +
90 'Keras 2 API: ' + signature, stacklevel=2)
---> 91 return func(*args, **kwargs)
92 wrapper._original_function = func
93 return wrapper
~/anaconda3/lib/python3.6/site-packages/keras/engine/input_layer.py
in __init__(self, input_shape, batch_size, batch_input_shape, dtype,
input_tensor, sparse, name)
37 if not name:
38 prefix = 'input'
---> 39 name = prefix + '_' + str(K.get_uid(prefix))
40 super(InputLayer, self).__init__(dtype=dtype, name=name)
41
~/anaconda3/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py
in get_uid(prefix)
72 """
73 global _GRAPH_UID_DICTS
---> 74 graph = tf.get_default_graph()
75 if graph not in _GRAPH_UID_DICTS:
76 _GRAPH_UID_DICTS[graph] = defaultdict(int)
AttributeError: module 'tensorflow' has no attribute
'get_default_graph'
Change
Import keras.<something>.<something>
to
Import tensorflow.keras.<something>.<something>
where "something" refers to the module you want to import. It worked for me.
Another cause due to which this is happening is that in tensorflow_backend.py
located in : lib/python3.6/site-packages/keras/backend/
uses tf.compat.v1.get_default_graph for obtaining graph
instead of tf.get_default_graph.
By replacing this in the directory this problem can be solved successfully.
Keras integrated into TensorFlow 2.0
The article below cleared this up for me. Key points are:
Keras is included in the TensorFlow 2.0 package
So no need to install the stand-alone Keras package in your environment
And now the fore-mentioned solutions of using "from tensorflow.keras…" make sense.
After recognizing that and making the change, my code samples work with some minor changes here and there.
https://www.pyimagesearch.com/2019/10/21/keras-vs-tf-keras-whats-the-difference-in-tensorflow-2-0/
I fixed this problem by replacing tensorflow.keras.* to tensorflow.python.keras.*
Working example:
from tensorflow.python.keras.models import Sequential
Two Steps solved this issue for me in Google Colabs
First Step
Change
from keras.something import something
To
from tensorflow.keras.something import something
Second Step
Use
tf.compat.v1.get_default_graph
instead of tf.get_default_graph
Reason
https://www.pyimagesearch.com/2019/10/21/keras-vs-tf-keras-whats-the-difference-in-tensorflow-2-0/
In my case, replacing
from keras.models import models
with:
from tensorflow.keras.models import models
in my script, fixed this problem.