无法从 Datalab 中的 TensorFlow contrib 包导入 Keras

Cannot import Keras from TensorFlow contrib package in Datalab

我正在尝试从 Datalab 实例中的 TensorFlow contrib 包导入 Keras(我使用的是 Tensorflow 1.1.0 版本和 Python 2.7)

from tensorflow.contrib.keras.python.keras.regularizers import l1,l2
from tensorflow.contrib.keras.python.keras.models import Sequential, load_model
from tensorflow.contrib.keras.python.keras.layers import Dense, Dropout, Activation
from tensorflow.contrib.keras.python.keras.constraints import max_norm
from tensorflow.contrib.keras.python.keras.optimizers import RMSprop, Adam
from tensorflow.contrib.keras.python.keras.layers.normalization import BatchNormalization

但是我得到以下错误:

ImportErrorTraceback (most recent call last)
<ipython-input-52-adf3061b6b33> in <module>()
      1 #from tensorflow.contrib.keras import *
----> 2 from tensorflow.contrib.keras.python.keras.regularizers import l1,l2
      3 from tensorflow.contrib.keras.python.keras.models import Sequential, load_model
      4 from tensorflow.contrib.keras.python.keras.layers import Dense, Dropout, Activation
      5 from tensorflow.contrib.keras.python.keras.constraints import max_norm

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/keras/__init__.py in <module>()
     24 
     25 # pylint: disable=wildcard-import
---> 26 from tensorflow.contrib.keras.api.keras import *
     27 
     28 try:

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/keras/api/keras/__init__.py in <module>()
     23 from __future__ import print_function
     24 
---> 25 from tensorflow.contrib.keras.api.keras import activations
     26 from tensorflow.contrib.keras.api.keras import applications
     27 from tensorflow.contrib.keras.api.keras import backend

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/keras/api/keras/activations/__init__.py in <module>()
     20 
     21 # Activation functions.
---> 22 from tensorflow.contrib.keras.python.keras.activations import elu
     23 from tensorflow.contrib.keras.python.keras.activations import hard_sigmoid
     24 from tensorflow.contrib.keras.python.keras.activations import linear

/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/keras/python/keras/__init__.py in <module>()
     19 from __future__ import print_function
     20 
---> 21 from tensorflow.contrib.keras.python.keras import activations
     22 from tensorflow.contrib.keras.python.keras import applications
     23 from tensorflow.contrib.keras.python.keras import backend

ImportError: cannot import name activations

我试过将Tensorflow升级到1.2.1版本,还是不行。

知道为什么会出现此错误吗?谢谢!

我来回答我自己的问题:Datalab实例中安装的python包似乎每次重启实例时都重置为默认包(我还没有找到为什么会这样),所以我改为使用 1.0.0 tensorflow 版本执行代码。我刚刚在单元格中写道:

!pip install tensorflow==1.1.0

然后我重新启动了 Datalab 内核(重新启动会话按钮)。在那之后,一切正常,我可以从 Tensorflow contrib 包中导入 Keras。