这可能完全是一个与 python 模块导入有关的菜鸟问题,但我不明白为什么以下内容有效:
> import tensorflow as tf
> f = tf.train.Feature()
> from tensorflow import train
> f = train.Feature()
但是以下语句会导致错误:
> from tensorflow.train import Feature
ModuleNotFoundError: No module named 'tensorflow.train'
有人可以解释一下为什么它不能这样工作吗?我的目标是在代码中使用更短的符号,如下所示:
> 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 版本是 1.7.0
最佳答案
解决方案
代替
from tensorflow.train import Feature
和
from tensorflow.core.example.feature_pb2 import Feature
解释
关于 TensorFlow 的 Aliases 的备注
一般来说,您必须记住这一点,例如:
from tensorflow import train
实际上是一个别名
from tensorflow.python.training import training
您可以通过打印模块轻松检查真实模块名称。对于当前示例,您将获得:
from tensorflow import train
print (train)
<module 'tensorflow.python.training.training' from ....
你的问题
在 TensorFlow 1.7 中,您不能使用
from tensorflow.train import Feature
, 因为 from
子句需要一个实际的模块名称(而不是别名)。给定 train
是别名,您将得到 ImportError
.通过做
from tensorflow import train
print (train.Feature)
<class 'tensorflow.core.example.feature_pb2.Feature'>
你会得到
train
的完整路径.现在,您可以在上面的解决方案中使用如上所示的导入路径。笔记
在 TensorFlow 1.9.0 中,
from tensorflow.train import Feature
会起作用,因为 tensorflow.train
是一个实际的包,因此您可以导入它。 (这是我在安装的 Tensorflow 1.9.0 以及文档中看到的,但在 Github 存储库中没有。它必须在某个地方生成。)有关模块路径的信息
您可以在文档中找到完整的模块路径。每个模块都有一个“定义在”部分。见下图(取自 Module: tf.train):
关于python-3.x - 为什么导入 "from tensorflow.train import Feature"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51329327/