Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the import "from tensorflow.train import Feature" doesn't work

That's probably totally noob question which has something to do with python module importing, but I can't understand why the following is valid:

> import tensorflow as tf
> f = tf.train.Feature()

> from tensorflow import train
> f = train.Feature()

But the following statement causes an error:

> from tensorflow.train import Feature
ModuleNotFoundError: No module named 'tensorflow.train'

Can please somebody explain me why it doesn't work this way? My goal is to use more short notation in the code like this:

> example = Example(
    features=Features(feature={
        'x1': Feature(float_list=FloatList(value=feature_x1.ravel())),
        'x2': Feature(float_list=FloatList(value=feature_x2.ravel())),
        'y': Feature(int64_list=Int64List(value=label))
    })
)

tensorflow version is 1.7.0

like image 363
Vlad-HC Avatar asked Jul 13 '18 16:07

Vlad-HC


2 Answers

Solution

Replace

from tensorflow.train import Feature

with

from tensorflow.core.example.feature_pb2 import Feature

Explanation

Remarks about TensorFlow's Aliases

In general, you have to remember that, for example:

from tensorflow import train

is actually an alias for

from tensorflow.python.training import training

You can easily check the real module name by printing the module. For the current example you will get:

from tensorflow import train
print (train)
<module 'tensorflow.python.training.training' from ....

Your Problem

In Tensorflow 1.7, you can't use from tensorflow.train import Feature, because the from clause needs an actual module name (and not an alias). Given train is an alias, you will get an ImportError.

By doing

from tensorflow import train
print (train.Feature)
<class 'tensorflow.core.example.feature_pb2.Feature'>

you'll get the complete path of train. Now, you can use the import path as shown above in the solution above.

Note

In TensorFlow 1.9.0, from tensorflow.train import Feature will work, because tensorflow.train is an actual package, which you can therefore import. (This is what I see in my installed Tensorflow 1.9.0, as well as in the documentation, but not in the Github repository. It must be generated somewhere.)

Info about the path of the modules

You can find the complete module path in the docs. Every module has a "Defined in" section. See image below (taken from Module: tf.train):

enter image description here

like image 83
Tim Avatar answered Nov 13 '22 12:11

Tim


I would advise against importing Feature (or any other object) from the non-public API, which is inconvenient (you have to figure out where Feature is actually defined), verbose, and subject to change in future versions.

I would suggest as an alternative to simply define

import tensorflow as tf
Feature = tf.train.Feature
like image 1
P-Gn Avatar answered Nov 13 '22 13:11

P-Gn