6

I have a bunch of code written using Keras that was installed as a separate pip install and the import statements are written like from keras.models import Sequential, etc..

On a new machine, I have Tensorflow installed which now includes Keras inside the contrib directory. In order to keep the versions consistent I thought it would be best to use what's in contrib instead of installing Keras separately, however this causes some import issues.

I can import Keras using import tensorflow.contrib.keras as keras but doing something like from tensorflow.contrib.keras.models import Sequential gives ImportError: No module named models, and from keras.models import Sequential gives a similar ImportError: No module named keras.models.

Is there a simple method to get the from x.y import z statements to work? If not it means changing all the instances to use the verbose naming (ie.. m1 = keras.models.Sequential()) which isn't my preferred syntax but is do-able.

bivouac0
  • 2,494
  • 1
  • 13
  • 28

3 Answers3

2

Try this with recent versions of tensorflow:

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import LSTM, TimeDistributed, Dense, ...
Soerendip
  • 7,684
  • 15
  • 61
  • 128
1

Try with tensorflow.contrib.keras.python.keras:

from tensorflow.contrib.keras.python.keras.models import Sequential
Julio Daniel Reyes
  • 5,489
  • 1
  • 19
  • 23
0

Unfortunately from tensorflow.contrib.keras.python.keras.models import Sequential no longer works. It looks like they are changing the interface as of version 1.4 (currently at RC0). There is a note saying the tensorflow.contrib.keras interface is deprecated and you should use tensorflow.keras but this doesn't work either without python in the line.

The following did work for me under V1.4rc0

from tensorflow.python.keras.models import Sequential
import tensorflow.python.keras
import tensorflow.contrib.keras as keras

The following did not...

import tensorflow.python.keras as keras

Hopefully this gets cleaned up a bit more before final release.

bivouac0
  • 2,494
  • 1
  • 13
  • 28
  • I would be interested to know if you think I should post this behavior as a bug on Github. It seems like one to me but maybe to someone more familiar with the tensorflow import interface, this is expected. – bivouac0 Oct 22 '17 at 13:33
  • `tensorflow.python` is not meant to be exposed for the public from the begining anyway. It is just inside stuff, using it is wrong practice, now tensorflow finally fixes it, you should use `tensorflow.keras`, which is mapped to `tensorflow.python.keras`, directly instead. – THN Oct 25 '17 at 04:03