Is there a shorter way to import submodule classes?

I am currently doing 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 to do it, I get

 ImportError: No module named tf.contrib.keras 

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

Other attempts

 >>> 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'> 
+5
source share
2 answers

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

Secondly, the structure of the tensorflow.contrib.keras package looks strange. Names

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

- actually aliases for more deeply nested modules

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

and the way to create these aliases does not allow the use of import from to import their contents. You can directly use the "real" names:

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

(There are even more aliases here - tensorflow.contrib.keras.api.keras.* Modules extract most of their contents from tensorflow.contrib.keras.python.keras ), but we don’t need to worry about that.)

+3
source

Try the following:

 from tensorflow.contrib.keras.models import Sequential from tensorflow.contrib.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D 
+1
source

Source: https://habr.com/ru/post/1269079/


All Articles