Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to import classes of a submodule?

Tags:

Currently, I do this:

import tensorflow as tf
keras = tf.contrib.keras
Sequential = keras.models.Sequential
Dense = keras.layers.Dense
Dropout = keras.layers.Dropout
Flatten = keras.layers.Flatten
Conv2D = keras.layers.Conv2D
MaxPooling2D = keras.layers.MaxPooling2D

I would like to do something like this:

import tensorflow as tf
keras = tf.contrib.keras
from tf.contrib.keras import (Sequential, Dense, Dropout, Flatten,
                              Conv2D, MaxPooling2D)

but when I try this I get

ImportError: No module named tf.contrib.keras

Is there a shorter way than the first code block to import those classes?

Other tries

>>> from tensorflow.contrib.keras import (Sequential, Dense, Dropout, Flatten)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name Sequential

Nr 2

>>> import tensorflow
>>> from tensorflow.contrib.keras.models import Sequential
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named models
>>> tensorflow.contrib.keras.models.Sequential
<class 'tensorflow.contrib.keras.python.keras.models.Sequential'>
like image 375
Martin Thoma Avatar asked Jun 21 '17 18:06

Martin Thoma


1 Answers

First, you need to import using the actual name of the tensorflow module, not the tf alias you used for it:

Second, the package structure of tensorflow.contrib.keras is kind of weird. The names

tensorflow.contrib.keras.models
tensorflow.contrib.keras.layers

are actually aliases for the more deeply nested modules

tensorflow.contrib.keras.api.keras.models
tensorflow.contrib.keras.api.keras.layers

and the way these aliases are created doesn't allow you to use from imports to import their contents. You can use the "real" names directly:

from tensorflow.contrib.keras.api.keras.models import Sequential
from tensorflow.contrib.keras.api.keras.layers import (
        Dense, Dropout, Flatten, Conv2D, MaxPooling2D)

(There's even more aliasing here - the tensorflow.contrib.keras.api.keras.* modules pull most of their contents from tensorflow.contrib.keras.python.keras - but we don't need to worry about that.)

like image 55
user2357112 supports Monica Avatar answered Oct 04 '22 23:10

user2357112 supports Monica