module 'tensorflow' has no attribute 'tanh' - tensorflow

I am trying to repeat what is shown in this tutorial: https://www.kaggle.com/alexisbcook/deep-reinforcement-learning
When I run this code:
# Check version of tensorflow
import tensorflow as tf
tf.__version__
I am getting this error:
module 'tensorflow' has no attribute 'version'
When I run this piece of code I am not getting any error:
from kaggle_environments import make, evaluate
from gym import spaces
class ConnectFourGym:
...
Then running this code without error:
# Create ConnectFour environment
env = ConnectFourGym(agent2="random")
But when I try to run the following code
import os
from stable_baselines.bench import Monitor
from stable_baselines.common.vec_env import DummyVecEnv
# Create directory for logging training information
log_dir = "ppo/"
os.makedirs(log_dir, exist_ok=True)
# Logging progress
monitor_env = Monitor(env, log_dir, allow_early_resets=True)
# Create a vectorized environment
vec_env = DummyVecEnv([lambda: monitor_env])
I am getting the following error:
module 'tensorflow' has no attribute 'tanh'
The error is pointing these lines causing the problem:
----> 2 from stable_baselines.bench import Monitor
...
----> 1 from stable_baselines.a2c import A2C
...
----> 1 from stable_baselines.a2c.a2c import A2C
...
----> 9 from stable_baselines.common import explained_variance, tf_util, ActorCriticRLModel, SetVerbosity, TensorboardWriter
...
----> 7 from stable_baselines.common.base_class import BaseRLModel, ActorCriticRLModel, OffPolicyRLModel, SetVerbosity,
...
---> 16 from stable_baselines.common.policies import get_policy_from_name, ActorCriticPolicy ...
--> 375 class LstmPolicy(RecurrentActorCriticPolicy):
Why this is happening? How can I fix this problem?

I fixed the problem by specifying TensorFlow version:
# Check version of tensorflow
!pip install -q 'tensorflow==1.15.0'
import tensorflow as tf
tf.__version__
This code snippet installs TensorFlow version 1.15.0 and prints
'1.15.0'

Related

cannot import name 'get_config' from 'tensorflow.python.eager.context'?

I'm trying to follow this repo's tutorial on colabhttps://github.com/divamgupta/image-segmentation-keras
but I'm getting this error again and again
cannot import name 'get_config' from 'tensorflow.python.eager.context' (/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/context.py)
I googled it a lot so I found some solutions that solved same problems for them, like upgrade tensorflow version or using from tensorflow import keras instead of import keras
or add this code snippet
!pip install --upgrade tensorflow
!pip install --upgrade tensorflow-gpu
But none of them worked!
Full error codes are as follow
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-10-5c4963dc4fff> in <module>()
1 from tensorflow import keras
2 from tensorflow.keras.preprocessing import image
----> 3 from keras_segmentation.models.unet import vgg_unet
4
5 model = vgg_unet(n_classes=50 , input_height=320, input_width=640 )
3 frames
/usr/local/lib/python3.7/dist-packages/keras_segmentation/models/unet.py in <module>()
----> 1 from keras.models import *
2 from keras.layers import *
3
4 from .config import IMAGE_ORDERING
5 from .model_utils import get_segmentation_model
/usr/local/lib/python3.7/dist-packages/keras/__init__.py in <module>()
23
24 # See b/110718070#comment18 for more details about this import.
---> 25 from keras import models
26
27 from keras.engine.input_layer import Input
/usr/local/lib/python3.7/dist-packages/keras/models.py in <module>()
17
18 import tensorflow.compat.v2 as tf
---> 19 from keras import backend
20 from keras import metrics as metrics_module
21 from keras import optimizer_v1
/usr/local/lib/python3.7/dist-packages/keras/backend.py in <module>()
35 from tensorflow.python.distribute import distribute_coordinator as dc
36 from tensorflow.python.distribute import distribute_coordinator_context as dc_context
---> 37 from tensorflow.python.eager.context import get_config
38 from tensorflow.python.framework import config
39 from keras import backend_config
ImportError: cannot import name 'get_config' from 'tensorflow.python.eager.context' (/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/context.py)
---------------------------------------------------------------------------
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.
---------------------------------------------------------------------------
Full codes are as follow
!pip install keras-segmentation
!pip install keras==2.4.3
#!pip install tensorflow==2.4.1
!pip install tensorflow==2.5.0
!apt-get install -y libsm6 libxext6 libxrender-dev
!pip install opencv-python
!pip install --upgrade tensorflow
!pip install --upgrade tensorflow-gpu
! wget https://github.com/divamgupta/datasets/releases/download/seg/dataset1.zip && unzip dataset1.zip
from tensorflow import keras
from tensorflow.keras.preprocessing import image
from keras_segmentation.models.unet import vgg_unet
model = vgg_unet(n_classes=50 , input_height=320, input_width=640 )
model.train(
train_images = "dataset1/images_prepped_train/",
train_annotations = "dataset1/annotations_prepped_train/",
checkpoints_path = "/tmp/vgg_unet_1" , epochs=5
)
out = model.predict_segmentation(
inp="dataset1/images_prepped_test/0016E5_07965.png",
out_fname="/tmp/out.png"
)
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.imshow(out)
from IPython.display import Image
Image('/tmp/out.png')
o = model.predict_segmentation(
inp="dataset1/images_prepped_test/0016E5_07965.png",
out_fname="/tmp/out.png" , overlay_img=True, show_legends=True,
class_names = [ "Sky", "Building", "Pole","Road","Pavement","Tree","SignSymbol", "Fence", "Car","Pedestrian", "Bicyclist"]
)
from IPython.display import Image
Image('/tmp/out.png')
I would appreciate any of your help
thanks in advance
From comments
It was just a matter of version
with tensorflow and keras. I looked into traceback tensorflow error
messages and opened it and changed import keras to from tensorflow import keras issue was resolved (Paraphrased from z2ouu).

How to install and use IB API within Colab?

I am creating a notebook on Google Colab to run trading algorithms which execute on Interactive Brokers (IB). I want to use the IB API for this.
My current code downloads and installs the API:
# Install IB and related libraries
!wget -cq http://interactivebrokers.github.io/downloads/twsapi_macunix.975.01.zip
!unzip -qq -o twsapi_macunix.975.01.zip
!cd IBJts/source/pythonclient && python setup.py build install
!pip install ib_insync
!pip install ibapi
# Import generic libraries
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
import pandas as pd
import numpy as np
import matplotlib as plt
import time
from datetime import datetime
import argparse
# Import IB and IB_InSync, and start an IB connection
from ib_insync import *
from ibapi import *
The last line returns an error:
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-4-3cdef93fab15> in <module>()
48 from ib_insync import *
---> 49 from ibapi import *
ModuleNotFoundError: No module named 'ibapi'
As the installation seems to run properly, I do not understand why I cannot import the API for use in the subsequent code.
Thanks already for your help!
Found a workaround by installing the library directly from the .egg file:
'''
ib_path='/usr/local/lib/python3.6/dist-packages/ibapi-9.75.1-py3.6.egg'
sys.path.append(ib_path)
from ibapi import *
'''

tf.VERSION is always 1.6.0 even though I installed the latest version

Please help me to solve the problem - I use Google's Colaboratory to run tensor_hub example Text classification with TF-Hub, it needs the version later than 1.7.0, but the version I installed is 1.8.0.
# Install the latest Tensorflow version.
!pip install --quiet "tensorflow>=1.7"
# Install TF-Hub.
!pip install tensorflow-hub
import tensorflow as tf
import tensorflow_hub as hub
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import seaborn as sns
RuntimeErrorTraceback (most recent call last) <ipython-input-20-48e1bdaa8642> in <module>()
1 import tensorflow as tf
----> 2 import tensorflow_hub as hub
3 import matplotlib.pyplot as plt
4 import numpy as np
5 import os
/usr/local/lib/python2.7/dist-packages/tensorflow_hub/__init__.py in <module>()
63
64 # Comment/uncomment to skip checking the TensorFlow version.
---> 65 _check_tensorflow_version(tf.VERSION)
66
67 # Used by doc generation script.
/usr/local/lib/python2.7/dist-packages/tensorflow_hub/__init__.py in
_check_tensorflow_version(version)
60 "TensorFlow Hub depends on 'tf-nightly' build after %s or "
61 "'tensorflow~=%s'. Found tf.VERSION = %s" % (
---> 62 _NIGHTLY_VERSION, _MAIN_VERSION, version))
63
64 # Comment/uncomment to skip checking the TensorFlow version.
RuntimeError: TensorFlow Hub depends on 'tf-nightly' build after 20180308 or 'tensorflow~=1.7'. Found tf.VERSION = 1.6.0
Good news: TF 1.7 is now available by default. :)
The underlying problem you were hitting is just that python caches loaded modules in sys.modules -- re-importing a module doesn't pick up the new version until you restart the process, as Korakot noted.
You may need to restart the runtime.
menu > Runtime > Restart runtime...

Keras import error: cannot import np_utils

import keras
Runs in the following error. My python is installed with Anaconda and I have done pip install Tensorflow / Keras / Numpy
ImportError Traceback (most recent call
last)
<ipython-input-7-c74e2bd4ca71> in <module>()
----> 1 import keras
/Users/florianfontaine-papion/anaconda2/lib/python2.7/site-
packages/keras/__init__.py in <module>()
1 from __future__ import absolute_import
2
----> 3 from . import utils
4 from . import activations
5 from . import applications
/Users/florianfontaine-papion/anaconda2/lib/python2.7/site-packages/keras/utils/__init__.py in <module>()
1 from __future__ import absolute_import
----> 2 from . import np_utils
3 from . import generic_utils
4 from . import data_utils
5 from . import io_utils
ImportError: cannot import name np_utils
First, check whether Keras is installed or not by running following command in terminal. If you are using python3, use python3 in place of python.
python -c 'import keras; print(keras.__version__)'
And if above command showing error do the following
Open terminal and type this
anaconda-navigator
Go to Environments tab present on left side
Select your destined environment
It will list all the packages installed. In first dropdown select ALL and in search bar type keras
It will list keras package. Select it and click apply at bottom
Done

Keras Import Error Tensorflow backend

---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/CJL/anaconda3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py in <module>()
4 try:
----> 5 from tensorflow.python.ops import ctc_ops as ctc
6 except ImportError:
ImportError: cannot import name 'ctc_ops'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-10-c74e2bd4ca71> in <module>()
----> 1 import keras
/Users/CJL/anaconda3/lib/python3.5/site-packages/keras/__init__.py in <module>()
1 from __future__ import absolute_import
----> 2 from . import backend
3 from . import datasets
4 from . import engine
5 from . import layers
/Users/CJL/anaconda3/lib/python3.5/site-packages/keras/backend/__init__.py in <module>()
67 elif _BACKEND == 'tensorflow':
68 sys.stderr.write('Using TensorFlow backend.\n')
---> 69 from .tensorflow_backend import *
70 else:
71 raise Exception('Unknown backend: ' + str(_BACKEND))
/Users/CJL/anaconda3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py in <module>()
5 from tensorflow.python.ops import ctc_ops as ctc
6 except ImportError:
----> 7 import tensorflow.contrib.ctc as ctc
8
9 import numpy as np
ImportError: No module named 'tensorflow.contrib.ctc'
Seems like is an problem with Keras and not Tensorflow according to this post enter link description here
I was wondering if this has been fixed yet?
This is a problem between Keras and tensorflow. You should change this fix to use something like
if hasattr(tf.contrib, 'ctc'):
ctc = tf.contrib.ctc # old version
else:
ctc = tf.nn # New official version.
The current "official" way to access the ctc operations are in tf.nn, for instance, tf.nn.ctc_loss.
If keras is giving an import problem and you are facing "no module named keras" even if you have installed it.
Just upgrade your pip by:
python -m pip install –upgrade pip
Re-install upgraded keras and tensorflow by:
pip install keras
pip install tensorflow
Hope it will solve the problem. If not, try upgrading your conda (Anaconda) and then do steps 1 to 3 above again.