Cannot import Tensorflow in ipython - python

I have tensorflow version 1.0.0 non-GPU version on my macbook pro Yosemite. It is installed in a virtualenv, and I have python 2.7. I have six version 1.4.1. When I do python on the command line and import six, it works fine. But when I enter 'ipython' and import tensorflow, I see this error:
AttributeError Traceback (most recent call last)
<ipython-input-1-cd232424f60d> in <module>()
----> 1 execfile('hw4/net.py')
/Users/lingxiao/Documents/research/dialogue-systems/hw4/net.py in <module>()
8 import time
9 import numpy as np
---> 10 import tensorflow as tf
11
12 import app
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/__init__.py in <module>()
22
23 # pylint: disable=wildcard-import
---> 24 from tensorflow.python import *
25 # pylint: enable=wildcard-import
26
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/python/__init__.py in <module>()
122 from tensorflow.python.platform import resource_loader
123 from tensorflow.python.platform import sysconfig
--> 124 from tensorflow.python.platform import test
125
126 from tensorflow.python.util.all_util import remove_undocumented
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/test.py in <module>()
67 # pylint: disable=g-bad-import-order
68 from tensorflow.python.client import device_lib as _device_lib
---> 69 from tensorflow.python.framework import test_util as _test_util
70 from tensorflow.python.platform import googletest as _googletest
71 from tensorflow.python.util.all_util import remove_undocumented
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/test_util.py in <module>()
41 from tensorflow.python.framework import random_seed
42 from tensorflow.python.framework import versions
---> 43 from tensorflow.python.platform import googletest
44 from tensorflow.python.platform import tf_logging as logging
45 from tensorflow.python.util import compat
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/googletest.py in <module>()
31
32 from tensorflow.python.platform import app
---> 33 from tensorflow.python.platform import benchmark # pylint: disable=unused-import
34
35 Benchmark = benchmark.TensorFlowBenchmark # pylint: disable=invalid-name
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/benchmark.py in <module>()
115
116
--> 117 class Benchmark(six.with_metaclass(_BenchmarkRegistrar, object)):
118 """Abstract class that provides helper functions for running benchmarks.
119
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six.pyc in with_metaclass(meta, *bases)
564 def with_metaclass(meta, *bases):
565 """Create a base class with a metaclass."""
--> 566 return meta("NewBase", bases, {})
567
568 def add_metaclass(metaclass):
/Users/lingxiao/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/benchmark.py in __new__(mcs, clsname, base, attrs)
110 newclass = super(mcs, _BenchmarkRegistrar).__new__(
111 mcs, clsname, base, attrs)
--> 112 if not newclass.is_abstract():
113 GLOBAL_BENCHMARK_REGISTRY.add(newclass)
114 return newclass
AttributeError: type object 'NewBase' has no attribute 'is_abstract'
I tried upgrading six and I am still seeing version 1.4.1. Is six the problem here? if not what is?

It seems that there's a number of things tangled. I'm using Anaconda2 with six==1.10.0, tensorflow==1.0.0 and Python 2.7.12. A quick experiment would be to install Anaconda2 (i.e. with python2.7) then pip install TF and other dependencies and try it out.
The Anaconda installation is self-contained, so that you won't be affected by other system-wide issues. I just did it by running /Users/myusername/anaconda2/bin/ipython

My guess is that you need to install iPython from within the virtual environment. if you haven't done that, ipython will use the vanilla interpreter even though you are in a virtual environment.

Related

How to resolve importing tensorflow library

I am working on deep learing project so for that I wanted to import tensorflow library but when I run the code cell in the jupyter notebook it pops up the following error.
Importing tensforflow library error screenshot
Importing tensforflow library error screenshot continue
import tensorflow as tf
error
AttributeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 import tensorflow as tf
File ~\anaconda3\lib\site-packages\tensorflow\__init__.py:469
467 if hasattr(_current_module, "keras"):
468 try:
--> 469 _keras._load()
470 except ImportError:
471 pass
File ~\anaconda3\lib\site-packages\tensorflow\python\util\lazy_loader.py:41, in LazyLoader._load(self)
39 """Load the module and insert it into the parent's globals."""
40 # Import the target module and insert it into the parent's namespace
---> 41 module = importlib.import_module(self.__name__)
42 self._parent_module_globals[self._local_name] = module
44 # Emit a warning if one was specified
File ~\anaconda3\lib\importlib\__init__.py:127, in import_module(name, package)
125 break
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
File ~\anaconda3\lib\site-packages\keras\__init__.py:21
15 """Implementation of the Keras API, the high-level API of TensorFlow.
16
17 Detailed documentation and user guides are available at
18 [keras.io](https://keras.io).
19 """
20 from keras import distribute
---> 21 from keras import models
22 from keras.engine.input_layer import Input
23 from keras.engine.sequential import Sequential
File ~\anaconda3\lib\site-packages\keras\models\__init__.py:18
1 # Copyright 2022 The TensorFlow Authors. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
(...)
13 # limitations under the License.
14 # ==============================================================================
15 """Keras models API."""
---> 18 from keras.engine.functional import Functional
19 from keras.engine.sequential import Sequential
20 from keras.engine.training import Model
File ~\anaconda3\lib\site-packages\keras\engine\functional.py:34
32 from keras.engine import input_spec
33 from keras.engine import node as node_module
---> 34 from keras.engine import training as training_lib
35 from keras.engine import training_utils
36 from keras.saving.legacy import serialization
File ~\anaconda3\lib\site-packages\keras\engine\training.py:45
43 from keras.saving.experimental import saving_lib
44 from keras.saving.legacy import hdf5_format
---> 45 from keras.saving.legacy import save
46 from keras.saving.legacy import saving_utils
47 from keras.saving.legacy import serialization
File ~\anaconda3\lib\site-packages\keras\saving\legacy\save.py:24
22 from keras.saving.legacy import serialization
23 from keras.saving.legacy.saved_model import load as saved_model_load
---> 24 from keras.saving.legacy.saved_model import load_context
25 from keras.saving.legacy.saved_model import save as saved_model_save
26 from keras.utils import traceback_utils
File ~\anaconda3\lib\site-packages\keras\saving\legacy\saved_model\load_context.py:68
64 """Returns whether under a load context."""
65 return _load_context.in_load_context()
---> 68 tf.__internal__.register_load_context_function(in_load_context)
AttributeError: module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function'
I am expecting such explanation which can easily be understood and even a beginner can interpret the solution.
You have an incompatible version of keras installed.
Uninstall it with pip uninstall keras and try again.
The Keras API is available within Tensorflow itself if you need it; from tensorflow import keras.

How to prevent getting error "AttributeError: module 'cv2' has no attribute 'gapi_wip_gst_GStreamerPipeline" when importing gym library of RL?

Hello I have been trying to learn Reinforcement Learning and I am trying to import the following libraries:
import os
import gym
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.evaluation import evaluate_policy
However, I am getting the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-5bf8ebd8fe1a> in <module>
1 import os
----> 2 import gym
3 from stable_baselines3 import PPO
4 from stable_baselines3.common.vec_env import DummyVecEnv
5 from stable_baselines3.common.evaluation import evaluate_policy
~\Anaconda3\lib\site-packages\gym\__init__.py in <module>
14 from gym import logger
15 from gym import vector
---> 16 from gym import wrappers
17
18 __all__ = ["Env", "Space", "Wrapper", "make", "spec", "register"]
~\Anaconda3\lib\site-packages\gym\wrappers\__init__.py in <module>
3 from gym.wrappers.time_limit import TimeLimit
4 from gym.wrappers.filter_observation import FilterObservation
----> 5 from gym.wrappers.atari_preprocessing import AtariPreprocessing
6 from gym.wrappers.time_aware_observation import TimeAwareObservation
7 from gym.wrappers.rescale_action import RescaleAction
~\Anaconda3\lib\site-packages\gym\wrappers\atari_preprocessing.py in <module>
5
6 try:
----> 7 import cv2
8 except ImportError:
9 cv2 = None
~\Anaconda3\lib\site-packages\cv2\__init__.py in <module>
179
180
--> 181 bootstrap()
~\Anaconda3\lib\site-packages\cv2\__init__.py in bootstrap()
173
174 for submodule in __collect_extra_submodules(DEBUG):
--> 175 if __load_extra_py_code_for_module("cv2", submodule, DEBUG):
176 if DEBUG: print("Extra Python code for", submodule, "is loaded")
177
~\Anaconda3\lib\site-packages\cv2\__init__.py in __load_extra_py_code_for_module(base, name, enable_debug_print)
26 native_module = sys.modules.pop(module_name, None)
27 try:
---> 28 py_module = importlib.import_module(module_name)
29 except ImportError as err:
30 if enable_debug_print:
~\Anaconda3\lib\importlib\__init__.py in import_module(name, package)
125 break
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
129
~\Anaconda3\lib\site-packages\cv2\gapi\__init__.py in <module>
288
289
--> 290 cv.gapi.wip.GStreamerPipeline = cv.gapi_wip_gst_GStreamerPipeline
AttributeError: module 'cv2' has no attribute 'gapi_wip_gst_GStreamerPipeline'
I have tried searching on the stackoverflow and one of the recommendations was to update opencv that I did using the following command:
!pip install opencv-python==4.6.0.66
However, This did not work and the system told me it is already pre-installed.
Requirement already satisfied: opencv-python==4.6.0.66 in c:\users\mashood\anaconda3\lib\site-packages (4.6.0.66)
Requirement already satisfied: numpy>=1.14.5 in c:\users\mashood\anaconda3\lib\site-packages (from opencv-python==4.6.0.66) (1.19.5)
I need to know what I am doing wrong! Thanks!

matplotlib.pyplot import failed in ipython but works in jupyter

I get this long error when i try importing pyplot in ipython. Everything works fine when i try the same in jupyter notebook.
I think I've tried all the suggestions I found about pyplot import errors. I tried reinstalling matplotlib, ipykernel, zmq etc etc., I tried rolling back to old versions. I've tried matching sys.path from notebook and my ipython kernel, but no success.
I'm using python 3.7, windows 10, ConEmu for ipython kernel.
from matplotlib import pyplot
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-02aaac1810fb> in <module>
----> 1 from matplotlib import pyplot
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in <module>
2347 dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
2348 # Set up the backend.
-> 2349 switch_backend(rcParams["backend"])
2350
2351 # Just to be safe. Interactive mode can be turned on without
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in switch_backend(newbackend)
219 else "matplotlib.backends.backend_{}".format(newbackend.lower()))
220
--> 221 backend_mod = importlib.import_module(backend_name)
222 Backend = type(
223 "Backend", (matplotlib.backends._Backend,), vars(backend_mod))
C:\ProgramData\Python3\Continuum\anaconda3\lib\importlib\__init__.py in import_module(name, package)
125 break
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
129
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_tkagg.py in <module>
1 from . import _backend_tk
----> 2 from .backend_agg import FigureCanvasAgg
3 from ._backend_tk import (
4 _BackendTk, FigureCanvasTk, FigureManagerTk, NavigationToolbar2Tk)
5
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in <module>
43
44 if _has_pil:
---> 45 from PIL import Image
46
47 backend_version = 'v2.2'
C:\ProgramData\Python3\Continuum\anaconda3\lib\site-packages\PIL\Image.py in <module>
93 # Also note that Image.core is not a publicly documented interface,
94 # and should be considered private and subject to change.
---> 95 from . import _imaging as core
96
97 if __version__ != getattr(core, "PILLOW_VERSION", None):
ImportError: DLL load failed: The specified module could not be found.

Module tesnorflow has no attribute "UninitializedVariable" tensorflow hub error

I have tensorflow version "1.14.0" and pip3 is also updated. But when I do:-
import tensorflow as tf
I get this error:
AttributeError: module 'tensorflow.python.ops.resource_variable_ops' has no attribute 'UninitializedVariable'
Tensorflow hub has version 0.5.0. Some answers on stack overflow have suggested that tensorflow version should be greater than 1.7.0 and mine is greater and still I don't know why is hub not being imported. The complete traceback of error is:-
AttributeError Traceback (most recent call last)
<ipython-input-24-d70b4e927300> in <module>
1 from sklearn.model_selection import train_test_split
2 import tensorflow as tf
----> 3 import tensorflow_hub as hub
~/.local/lib/python3.6/site-packages/tensorflow_hub/__init__.py in <module>
27 # error message is thrown instead of an obscure error of missing
28 # symbols at executing the imports.
---> 29 from tensorflow_hub.estimator import LatestModuleExporter
30 from tensorflow_hub.estimator import register_module_for_export
31 from tensorflow_hub.feature_column import image_embedding_column
~/.local/lib/python3.6/site-packages/tensorflow_hub/estimator.py in <module>
23 from absl import logging
24 import tensorflow as tf
---> 25 from tensorflow_hub import tf_utils
26 from tensorflow_hub import tf_v1
27
~/.local/lib/python3.6/site-packages/tensorflow_hub/tf_utils.py in <module>
31 # depending on TensorFlow internal implementation details.
32 # pylint: disable=g-direct-tensorflow-import
---> 33 from tensorflow.python.feature_column import feature_column_v2
34 # pylint: enable=g-direct-tensorflow-import
35
~/.local/lib/python3.6/site-packages/tensorflow/python/feature_column/feature_column_v2.py in <module>
164 from tensorflow.python.platform import tf_logging as logging
165 from tensorflow.python.training import checkpoint_utils
--> 166 from tensorflow.python.training.tracking import tracking
167 from tensorflow.python.util import deprecation
168 from tensorflow.python.util import nest
~/.local/lib/python3.6/site-packages/tensorflow/python/training/tracking/tracking.py in <module>
21 import weakref
22
---> 23 from tensorflow.python.eager import def_function
24 from tensorflow.python.eager import function as defun
25 from tensorflow.python.framework import dtypes
~/.local/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in <module>
38
39
---> 40 class UnliftedInitializerVariable(resource_variable_ops.UninitializedVariable):
41 """Variable which does not lift its initializer out of function context.
42
AttributeError: module 'tensorflow.python.ops.resource_variable_ops' has no attribute 'UninitializedVariable'
I have tried uninstalling tf completely and then installing again, reinstalling tf hub and updating pip so far. Any help will be very much appreciated!

Error while importing matplotlib in Canopy - rc_params_from_file()

I have the Enthought Canopy installed on my Ubuntu 14.04. I'm trying to run sample matplotlib programs (from the library's website). Every attempt of running the program makes the Canopy's command prompt display following message:
TypeError Traceback (most recent call last)
/home/guras/Canopy/appdata/canopy-1.4.1.1975.rh5-x86_64/lib/python2.7/site-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
202 else:
203 filename = fname
--> 204 __builtin__.execfile(filename, *where)
/home/guras/Python programy/pierwszy.py in <module>()
4 This example uses the Fahrenheit and Celsius scales.
5 """
----> 6 import matplotlib.pyplot as plt
7 import numpy as np
8
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
26 import matplotlib
27 import matplotlib.colorbar
---> 28 from matplotlib import style
29 from matplotlib import _pylab_helpers, interactive
30 from matplotlib.cbook import dedent, silent_list, is_string_like, is_numlike
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/__init__.py in <module>()
1 from __future__ import absolute_import
2
----> 3 from .core import use, context, available, library, reload_library
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/core.py in <module>()
147 # Load style library
148 # ==================
--> 149 _base_library = load_base_library()
150
151 library = None
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/core.py in load_base_library()
92 """Load style library defined in this package."""
93 library = dict()
---> 94 library.update(read_style_directory(BASE_LIBRARY_PATH))
95 return library
96
/home/guras/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/style/core.py in read_style_directory(style_dir)
125 styles = dict()
126 for path, name in iter_style_files(style_dir):
--> 127 styles[name] = rc_params_from_file(path, use_default_template=False)
128 return styles
129
TypeError: **rc_params_from_file() got an unexpected keyword argument 'use_default_template'**
Any ideas how to fix it?
The use_default_template keyword parameter was added to the rc_params_from_file function in matplotlib version 1.4.0rc1.
Most likely, your version of matplotlib is older than 1.4.0rc1 and needs to be upgraded.
If you have more than one installation of matplotlib installed, you'll need to make sure the directory containing the newer version is listed earlier than the older version in sys.path, or perhaps, simply delete the older version of matplotlib.
Use the Canopy Package Manager to update matplotlib to the latest version.

Categories