matplotlib.pyplot import failed in ipython but works in jupyter - python

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.

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!

runas /netonly yields DLL import errors with python

After running runas /netonly /user:domain\username "ipython" on windows cmd, IPython 3.8.8 (installed via Anaconda) successfully launches but as soon as I start importing packages, I get DLL load failed errors. For example if I run import nltk or import matplotlib.pyplot I get the following error messages respectively:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-1d2184025e54> in <module>
----> 1 import nltk
~\Anaconda3\lib\site-packages\nltk\__init__.py in <module>
147 from nltk.tag import *
148 from nltk.tokenize import *
--> 149 from nltk.translate import *
150 from nltk.sem import *
151 from nltk.stem import *
~\Anaconda3\lib\site-packages\nltk\translate\__init__.py in <module>
21 from nltk.translate.bleu_score import sentence_bleu as bleu
22 from nltk.translate.ribes_score import sentence_ribes as ribes
---> 23 from nltk.translate.meteor_score import meteor_score as meteor
24 from nltk.translate.metrics import alignment_error_rate
25 from nltk.translate.stack_decoder import StackDecoder
~\Anaconda3\lib\site-packages\nltk\translate\meteor_score.py in <module>
8
9
---> 10 from nltk.stem.porter import PorterStemmer
11 from nltk.corpus import wordnet
12 from itertools import chain, product
~\Anaconda3\lib\site-packages\nltk\stem\__init__.py in <module>
27 from nltk.stem.isri import ISRIStemmer
28 from nltk.stem.porter import PorterStemmer
---> 29 from nltk.stem.snowball import SnowballStemmer
30 from nltk.stem.wordnet import WordNetLemmatizer
31 from nltk.stem.rslp import RSLPStemmer
~\Anaconda3\lib\site-packages\nltk\stem\snowball.py in <module>
27 import re
28
---> 29 from nltk.corpus import stopwords
30 from nltk.stem import porter
31 from nltk.stem.util import suffix_replace, prefix_replace
~\Anaconda3\lib\site-packages\nltk\corpus\__init__.py in <module>
64 from nltk.tokenize import RegexpTokenizer
65 from nltk.corpus.util import LazyCorpusLoader
---> 66 from nltk.corpus.reader import *
67
68 abc = LazyCorpusLoader(
~\Anaconda3\lib\site-packages\nltk\corpus\reader\__init__.py in <module>
103 from nltk.corpus.reader.categorized_sents import *
104 from nltk.corpus.reader.comparative_sents import *
--> 105 from nltk.corpus.reader.panlex_lite import *
106 from nltk.corpus.reader.panlex_swadesh import *
107
~\Anaconda3\lib\site-packages\nltk\corpus\reader\panlex_lite.py in <module>
13
14 import os
---> 15 import sqlite3
16
17 from nltk.corpus.reader.api import CorpusReader
~\Anaconda3\lib\sqlite3\__init__.py in <module>
21 # 3. This notice may not be removed or altered from any source distribution.
22
---> 23 from sqlite3.dbapi2 import *
~\Anaconda3\lib\sqlite3\dbapi2.py in <module>
25 import collections.abc
26
---> 27 from _sqlite3 import *
28
29 paramstyle = "qmark"
ImportError: DLL load failed while importing _sqlite3: The specified module could not be found.
AND
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-2-864e826dab68> in <module>
----> 1 import matplotlib.pyplot
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in <module>
172
173
--> 174 _check_versions()
175
176
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in _check_versions()
157 # Quickfix to ensure Microsoft Visual C++ redistributable
158 # DLLs are loaded before importing kiwisolver
--> 159 from . import ft2font
160
161 for modname, minver in [
ImportError: DLL load failed while importing ft2font: The specified module could not be found.
However, imports such as import numpy or import pandas run fine.
Furthermore, when launching "ipython" without runas all imports run perfectly.
Any ideas on what's going on here?
EDIT:
I can confirm that it is not an administrative thing.
I installed python independently from Anaconda - and now when I run runas /netonly /user:domain\username "C:\somenewpath\python", importing nltk and matplotlib are successful. However, this is not necessarily ideal for two reasons: 1) because I have to manually install a host of packages, and 2) now I have 2 separate python IDLEs sitting in my environment.

Cannot import Tensorflow in ipython

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.

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