使用tf别名导入TensorFlow后无法通过该别名导入keras模块的问题求助
from tf.keras.models import Model Fails (And How to Fix It) Hey there, let's clear up this confusion for you—this isn't a TensorFlow bug, it's just how Python's module import system works!
The Root Cause
When you run import tensorflow as tf, you're not creating a new module named tf—you're just assigning the existing tensorflow module to a shorter alias variable in your current Python session.
Python’s from X import Y syntax looks for an actual module/package named X in your installed libraries or the current path. Since there’s no real module called tf (only the alias you made), Python throws that ModuleNotFoundError every time. This is why it happens both in your local Ubuntu virtual environment and Colab—they’re both following standard Python import rules.
Fixes to Use Keras with the tf Alias
You’ve got a couple straightforward options to work around this:
1. Directly Use the Alias to Access the Module
Since you already imported TensorFlow as tf, you can skip the from import entirely and reference the Model class directly:
import tensorflow as tf # Use the class directly in your code class MyModel(tf.keras.models.Model): # Your model definition here pass
Or if you want to assign it to a shorter name for repeated use:
import tensorflow as tf Model = tf.keras.models.Model # Now you can use Model directly class MyModel(Model): pass
2. Alias the Keras Submodule (If You Prefer from Syntax)
If you really want to use from ... import style, you can alias the keras submodule first, then import from that alias:
import tensorflow as tf # Assign tf.keras to a simpler alias keras = tf.keras # Now this works perfectly! from keras.models import Model
Just keep in mind: this only works because you’ve explicitly assigned tf.keras to keras in your session—Python still isn’t looking for a separate keras module (though in practice, TensorFlow’s integrated Keras behaves exactly like the standalone one here).
3. Stick with the Fully Qualified Import
Of course, the method you already know works perfectly well and is the most explicit option (great for readability in larger projects):
from tensorflow.keras.models import Model
内容的提问来源于stack exchange,提问作者user12877516




