Error in keras - name 'Dense' is not defined - python-2.7

I'm new to Deep Neural Network libraries in python. I've installed Theano & keras in my windows system by following these steps(I already had anaconda):
Install TDM GCC x64.
Run the below code from command prompt
conda update conda
conda update --all
conda install mingw libpython
pip install git+git://github.com/Theano/Theano.git
pip install git+git://github.com/fchollet/keras.git
When I'm running the following code in Ipython,
import numpy as np
import keras.models
from keras.models import Sequential
model = Sequential()
model.add(Dense(32, input_shape=(784,)))
model.add(Activation('relu'))
it is showing the following error:
NameError
Traceback (most recent call last)
----> 1 model.add(Dense(32, input_shape=(784,)))
NameError: name 'Dense' is not defined
Here is the error message screenshot.
How come sequential was imported successfully and 'Dense' was not defined?

You need from keras.layers import Activation, Dense.

I had a similar problem in tensorflow 2.0 and solved it by using
from tensorflow.keras.layers import Dense

For TensorFlow 2.6 you should do this:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

Related

python related (numpy and scipy)

when i run command import numpy as np or import scipy as sp, it gives me error like:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import numpy as np
ImportError: No module named numpy
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
import scipy as sp
ImportError: No module named scipy
(Disclaimer: there are already tons of well established way / tutorials on the internet. I'm merely posting this to hopefully help out quickly)
 What you want to achieve
To install a library (e.g. numpy, scipy) locally on a machine (e.g. laptop, server, etc.) and import that library from a Python code.
 One of the solutions: Anaconda
One of the popular / quick ways in the Python scientific community is to do this via Anaconda (disclaimer 2: I personally prefer Anaconda due to its ease of enabling me to switch / play with different Python environments). Here is the step by step instructions:
Download and install the Anaconda distribution onto the machine locally.
Create a file environment.yml and store it anywhere you like (e.g. a subdirectory within your home directory). The file looks like this gist file - tweak it to your taste (e.g. choose Python version 2.x vs 3.x, add/remove/edit dependencies, etc.)
Within the same directory where you've created the environment.yml, create a conda environment by: conda env create -f environment.yml. For this particular gist file, it will create a conda environment (called "helloworld") with the specific Python version (2.7) and the anaconda package (which includes the popular numpy and scipy libraries).
Activate the environment (i.e. "go inside that environment") by: source activate helloworld (replace "helloworld" with whatever name you specified in environment.yml).
Now you are in the "helloworld" conda environment, start up a python console: jupyter console.
Now try importing stuff within this console:
Python 2.7.13 |Anaconda 4.4.0 (x86_64)| (default, Dec 20 2016, 23:05:08)
Type "copyright", "credits" or "license" for more information.
IPython 5.3.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import numpy as np
In [2]: import scipy as sp
In [3]: np.version.version
Out[3]: '1.12.1'
In [4]: sp.version.version
Out[4]: '0.19.0'
(to quit console just do a Ctrl + D to go back to command line)
For step 5 above, also try out:
jupyter notebook
jupyter qtconsole
And play with the python commands.
When you are done with the conda environment, just "deactivate" (i.e. get out of) it by doing this in the command line: source deactivate.
Top tip: don't forget step 4 - this defines which conda environment you are in (i.e. which python version and libraries available etc.). I occasionally ommited step 4 by accident and get that error "no module named numpy", etc.)
See this Anaconda get started guide for more info.
The non Anaconda way
If you would like to avoid Anaconda all together, just simply do this in the command line:
Install the numpy and scipy libraries:
pip install numpy
pip install scipy
Start a Python interpreter:
python
Do the library import stuff within the Python interpreter:
>>> import numpy as np
>>> import scipy as sp
>>> np.version.version
'1.11.3'
>>> sp.version.version
'1.11.3'
 Additional alternatives
You could try out the Python VirtualEnv - though I've never really used it since I've started using Anaconda.

Getting import error when using gensim.summeraization

I am trying to use gensim's summarizer and keywords to extract important keywords and summarizing contents. However, I am getting the following error:
from gensim.summarization import summarize
Traceback:
ImportError Traceback (most recent call last)
<ipython-input-12-70743b938b65> in <module>()
----> 1 from gensim.summarization import summarize
ImportError: No module named summarization
I checked the version which is gensim 0.10.0. I am using Anaconda distribution and installed gensim using
conda install gensim
Any help would greatly help.
Thanks
Please update gensim to the latest version.
pip/conda install --upgrade gensim

can't import package pandas, statsmodels and matplotlib on Jupyter for anaconda

I failed to import package pandas statsmodels and matplotlib in Jupyter in Anaconda 2,
import pandas
import statsmodels
import matplotlib as mpl
for example the error information for import pandas like this
--------------------------------------------------------------------------- ImportError Traceback (most recent call
last) in ()
----> 1 import pandas
/Applications/anaconda/lib/python2.7/site-packages/pandas/init.py
in ()
29 "pandas from the source directory, you may need to run "
30 "'python setup.py build_ext --inplace' to build the C "
---> 31 "extensions first.".format(module))
32
33 from datetime import datetime
ImportError: C extension: hashtable not built. If you want to import
pandas from the source directory, you may need to run 'python setup.py
build_ext --inplace' to build the C extensions first.
but I can import numpy, scipy,sklearn correctly
import scipy as sp
import numpy as np
import sklearn as sk
In addition, if I use Spyder or ipython on Anaconda, it works for all the 6 packages mentioned above. I used the Mac OS 10.10.5, Python 2.7.12 Anaconda 2 (x86_64). The question is similar to the question mentioned in the following link, but the answer seems not work for my problem (I have deleted the python 2.7 installed on the Mac by default).
Import pandas on jupyter ipython notebook fails
uninstall and reinstall pandas and try again. Also if there are useless files in your directory delete them.

Caffe install getting ImportError: DLL load failed: The specified module could not be found

I am trying to compile and run the snippets posted here, which basically is going to let me visualize the network internals(feature maps).
I have successfully compiled caffe and pycaffe using the caffe-windows branch, And I have copied the caffe folder, into T:\Anaconda\Lib\site-packages folder.
Yet still, when I try to run this snippet of code in jupyter notebook :
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Make sure that caffe is on the python path:
caffe_root = 'TC:/Caffe/' # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
import os
if not os.path.isfile(caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'):
print("Downloading pre-trained CaffeNet model...")
!../scripts/download_model_binary.py ../models/bvlc_reference_caffenet
I get the following error :
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-e7a8ec94e861> in <module>()
8 sys.path.insert(0, caffe_root + 'python')
9
---> 10 import caffe
L:\Anaconda2\lib\site-packages\caffe\__init__.py in <module>()
----> 1 from .pycaffe import Net, SGDSolver
2 from ._caffe import set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver
3 from .proto.caffe_pb2 import TRAIN, TEST
4 from .classifier import Classifier
5 from .detector import Detector
L:\Anaconda2\lib\site-packages\caffe\pycaffe.py in <module>()
11 import numpy as np
12
---> 13 from ._caffe import Net, SGDSolver
14 import caffe.io
15
ImportError: DLL load failed: The specified module could not be found.
Whats wrong here?
Notes:
I'm using Anaconda2-2.4.1-Windows-x86_64.exe
There's most likely a more specific dependency issue you are not seeing (Protobuf / OpenCV). First try using the C++ API to load an example and make sure all the DLL's load. Then you can more confidently narrow things down to the Python side. I recommend the more recent windows caffe instructions based off the branch you're using:
https://initialneil.wordpress.com/2015/01/11/build-caffe-in-windows-with-visual-studio-2013-cuda-6-5-opencv-2-4-9/
I had to do a complete rebuild as detailed above (note that some dependencies are easier to find with NuGet). Also be on the lookout for the right protobuf binaries in various 3rdParty.zip files throughout the above blog.
If you are okay with a snapshot version of Caffe and you don't need to modify the project itself, the following binaries are much easier to install and get working:
https://initialneil.wordpress.com/2015/07/15/caffe-vs2013-opencv-in-windows-tutorial-i/

Error importing theano "cannot import name gof"

I am current getting the error
ImportError: cannot import name gof
when importing theano.
>>> import theano
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
import theano
File "C:\Python27\lib\site-packages\theano\__init__.py", line 63, in <module>
from theano.compile import (
File "C:\Python27\lib\site-packages\theano\compile\__init__.py", line 9, in <module>
from theano.compile.function_module import *
File "C:\Python27\lib\site-packages\theano\compile\function_module.py", line 16, in <module>
from theano import gof
ImportError: cannot import name gof
I am using python 2.7.10 (). Theano is installed using pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git.
Hope to get you suggestion to solve this problem
Most of the time, when I see this error, it is caused by those 2 errors:
1) A syntax error in Theano. Update Theano and make sure to have no local modifcation. I nerver saw this error in the master of Theano, but just in case.
2) When there is multiple version of Theano that are installed.
In both case, remove all version of Theano. Do it multiple time to be sure there is none left. Then install again.
From memory, this always solved the problem when it wasn't a syntax error during development (but not in the master version of Theano that you use)
This ImportError can be caused because Theano is unable to compile the gof module itself. If this is the case, you will see an error message that looks like "Exception: Compilation Failed (return status=1): C:\Long\Path\...\mod.cpp:1: sorry, unimplemented: 64-bit mode not compiled in".
Fixing With Conda
If you are installing theano into a conda environment, make sure that you have a C compiler available to that environment.
The command
conda install m2w64-toolchain
will provide a C compiler to your environment that's isolated from the rest of the machine.
After the m2w64-toolchain package is installed, import theano should work
Fixing Manually
If you are installing Theano yourself, two points from these threads may help:
Install the bleeding edge version of Theano
Install libpython from http://www.lfd.uci.edu/%7Egohlke/pythonlibs/
I assume you're using Windows 7 or later.
If you have installed Python Anaconda, then open Windows Powershell or Command Prompt and type conda install mingw libpython before typing pip install theano
Alternatively, if you don't have Anaconda, download those packages from
anaconda.org/anaconda/mingw/files
anaconda.org/anaconda/libpython/files
github.com/Theano/Theano
Then open Command Prompt, navigate to each folder and type python setup.py install
Now run Python and import theano
Possible errors:
If you get the RuntimeError: "To use MKL 2018 with Theano you MUST set "MKL_THREADING_LAYER=GNU" in your environement" then
Go to Control Panel > System > Advanced system settings and select "Environment Variables".
In the "System variables" section, make a new variable name MKL_THREADING_LAYER and set its value to GPU
If you get other kinds of errors, then try the following:
Make an empty file called .theanorc (a file extension without a file name) in your home folder C:\Users\<username>. If you get the error "You must type a file name" then see stackoverflow.com/q/5004633
Open .theanorc and write this:
[global]
cxx=C:\<path to Anaconda>\Anaconda3\MinGW\bin\g++.exe
Run Python again and import theano. If it works, then you can probably delete .theanorc
In my case, the fix was to install a python build that's callable as a shared library:
PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install 2.7.15