Cannot import 'swish' in 'tensorflow.python.keras.activations' - python

I am running a jupyter notebook from an Anaconda Prompt (Anaconda 3), and I am trying to use tensorflow keras.
I am trying to run the import statement:
from tensorflow.keras.models import Sequential
I get the following error:
ImportError Traceback (most recent call last)
<ipython-input-1-d23f18c08372> in <module>
4 from keras.models import Model
5
----> 6 from tensorflow.keras.models import Sequential
7
8 from tensorflow.keras.layers import Dense, Activation, Dropout
~\Anaconda3\lib\site-packages\tensorflow\keras\__init__.py in <module>
12 import sys as _sys
13
---> 14 from . import activations
15 from . import applications
16 from . import backend
~\Anaconda3\lib\site-packages\tensorflow\keras\activations\__init__.py in <module>
21 from tensorflow.python.keras.activations import softplus
22 from tensorflow.python.keras.activations import softsign
---> 23 from tensorflow.python.keras.activations import swish
24 from tensorflow.python.keras.activations import tanh
25
ImportError: cannot import name 'swish' from 'tensorflow.python.keras.activations' (C:\Users\FlamePrinz\Anaconda3\lib\site-packages\tensorflow\python\keras\activations.py)

Try this way
from keras.utils.generic_utils import get_custom_objects
from keras.layers import Activation
get_custom_objects().update({'swish': Activation(swish)})
swish function needs to be passed into activation class to actually build it.
And then you can do
model.add(Dense(64, activation = "swish"))

You can download swish activation from pypi. Try the following:
pip install swish-activation
import swish_package
from swish_package import swish

This is an older question, but I ended up taking Dr. Snoopy's suggestion uninstalling and reinstalling TensorFlow which solved my issue.

Related

AttributeError: module 'keras.engine.base_layer' has no attribute 'BaseRandomLayer'

Context - I was getting errors when saving/loading EfficientNetB7 and one of the articles I saw suggested installing tf-nightly. Well that really blew things up in my Google Colab! I uninstalled tf-nightly, restarted my runtime, and now when I go to run my import cell, I get the errors below.
I reinstalled tensorflow 2.6.0.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-5d853ee59f92> in <module>()
11 import tensorflow as tf
12 from tensorflow import keras
---> 13 from tensorflow.keras import Model
14 from tensorflow.keras.models import Sequential
15 from tensorflow.keras.utils import to_categorical
11 frames
/usr/local/lib/python3.7/dist-packages/keras/layers/core/dropout.py in <module>()
24
25 #keras_export('keras.layers.Dropout')
---> 26 class Dropout(base_layer.BaseRandomLayer):
27 """Applies Dropout to the input.
28
AttributeError: module 'keras.engine.base_layer' has no attribute 'BaseRandomLayer'
I also had an issue with this import before:
from tensorflow.keras import backend as keras
Here are all my imports:
import os
import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage.io import imread
from skimage.transform import resize
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.losses import categorical_crossentropy
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout, BatchNormalization
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from datetime import datetime
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score
import skimage.io as io
import skimage.transform as trans
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from tensorflow.keras import backend as keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras_preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers.schedules import ExponentialDecay
import scipy.misc as sc
import h5py
from sklearn.semi_supervised import LabelSpreading
from sklearn.model_selection import GridSearchCV
from tensorflow.keras.applications import * #Efficient Net included here
import shutil
from sklearn import model_selection
from tqdm import tqdm
# import warnings
# warnings.filterwarnings("ignore", category=DeprecationWarning)
Try rolling back the python version to 3.6. If you are using Anaconda run
conda install python=3.6
Then install keras
pip install keras==2.0.8
Worked for me in Ubuntu.
I was able to get rid of the issue after installing tensorflow==2.8.0.

cant install Adam from keras.optimizer

Was working on google colab yesterday and everything works fine. but now I got a problem when trying to import Adam.
this is what I try to import
from keras.optimizers import Adam, SGD, RMSprop
this is what I got
ImportError Traceback (most recent call last)
<ipython-input-1-36a1fe725448> in <module>()
30 from keras.layers import GlobalAveragePooling2D
31 from keras.layers import BatchNormalization, Activation, MaxPooling2D
---> 32 from keras.optimizers import Adam, SGD, RMSprop
ImportError: cannot import name 'Adam' from 'keras.optimizers' (/usr/local/lib/python3.7/dist-packages/keras/optimizers.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.
Try to import from tf.keras as follows
from tensorflow.keras.optimizers import Adam, SGD, RMSprop
You can call the Adam optimizer function using TensorFlow:
from tensorflow.keras.optimizers import Adam

TensorFlow 2.5 update in Colab breaks keras code

I have been running several deep learning models in google colab using Keras.
My codes worked perfectly but suddenly, today, a lot of errors appeared reporting problemas with the imports. Pasting one here.
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-3-745bb0894037> in <module>()
19 from keras.preprocessing.image import ImageDataGenerator
20 from keras.utils import np_utils
---> 21 from keras_contrib.applications.densenet import DenseNetFCN
22 from keras_contrib.losses.jaccard import jaccard_distance
1 frames
/usr/local/lib/python3.7/dist-packages/keras_contrib/applications/densenet.py in <module>()
66 from keras.layers import BatchNormalization
67 from keras.regularizers import l2
---> 68 from keras.utils.layer_utils import convert_all_kernels_in_model
69 from keras.utils.data_utils import get_file
70 from keras.engine.topology import get_source_inputs
ImportError: cannot import name 'convert_all_kernels_in_model' from 'keras.utils.layer_utils' (/usr/local/lib/python3.7/dist-packages/keras/utils/layer_utils.py)
so I am answering my question for anyone who might have trouble with it.
They updated Tensorflow and Keras in Colab to 2.5 versions, and some functions are not migrated (i.e. convert_all_kernels_in_model).
For me, the solution was to paste the code of the NN architecture and comment the line with that function as I was not using it.
I know it is not the best solution but it got me through what I needed.
The final release of TensorFlow version 2.5 requires a nightly dev build of keras that seems to be the source of these issues.
https://github.com/tensorflow/tensorflow/blob/v2.5.0/tensorflow/tools/pip_package/setup.py#L107
The relevant TensorFlow issue to report your experience is:
https://github.com/tensorflow/tensorflow/issues/49823

import error of ArcFace using python in jupyternotebbok

When I am importing the package ArcFace.
from arcface.metrics import ArcFace
It is showning the import error. Like this,
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-4-fe2759a1802e> in <module>
15 from keras.layers.convolutional import MaxPooling2D
16 from keras.layers.core import Activation, Flatten, Dropout, Dense
---> 17 from arcface.metrics import ArcFace
18 from keras.layers import Input
19 from keras import backend as K
ModuleNotFoundError: No module named 'arcface'
I have searched for importing it for Anaconda and pip too. I have not found any results. Please help me to solve this.
This is part of project keras-arcface but it is not part of keras so you have to install/copy it separatelly.
If you put it in your project in subfolder arcface then it should work.
You can run ArcFace within deepface. The framework is mainly based on keras and tensorflow. It handles model building and downloading pre-trained weights in the background. Besides, it covers face recognition pipeline stages includign detect, align.
#!pip install deepface
from deepface import DeepFace
resp = DeepFace.verify("img1.jpg", "img2.jpg", model_name = 'ArcFace')

How can I fix this error in python 3.8 pycharm? It is about importing packages

This is the error it gives me when I try to run it:
Traceback (most recent call last):
File "/Users/kids/Library/Mail/V5/E60CBF1C-9021-4A10-8D60-06C96C141AF1/Outbox.mbox/E7C72E99-E3DB-4CDC-B1C9-15116F3478D8/Data/Attachments/405/2/ASL-Finger-Spelling-Recognition-master/main.py", line 10, in <module>
from keras.layers.convolutional import Convolution3D, MaxPooling3D
This is the code error which it is showing:
from keras.layers.convolutional import Convolution3D, MaxPooling3D
Keras version is 2.3.1. Python version is Python 3.8. Running on MacOS.
Your import statement
from keras.layers.convolutional import Convolution3D, MaxPooling3D
attempts to import MaxPooling3D from keras.layers.convolutional. MaxPooling3D is actually part of the pooling module, i.e. keras.layers.pooling.
According to the keras source and docs, the best way to import these two classes in a single statement would be
from keras.layers import Convolution3D, MaxPooling3D
Alternatively, you could import them separately:
from keras.layers.convolutional import Convolution3D
from keras.layers.pooling import MaxPooling3D
but in general, you should pay attention to what is purposefully exposed via the package; that is, the classes accessible from keras.layers.

Categories

Resources