Vscode keras intellisense(suggestion) not working properly

Question:

Intellisense works fine on importing phrase

image1

But when it comes with chaining method, it shows different suggestions

image2

Python & Pylance extensions are installed.

Asked By: user8659363

||

Answers:

did you try clearing the cache on your system?

Answered By: ALEX1A

From this issue on github
try adding this to the bottom of your tensorflow/__init__.py (in .venv/Lib/site-packages/tensorflow for me)

# Explicitly import lazy-loaded modules to support autocompletion.
# pylint: disable=g-import-not-at-top
if _typing.TYPE_CHECKING:
  from tensorflow_estimator.python.estimator.api._v2 import estimator as estimator
  from keras.api._v2 import keras
  from keras.api._v2.keras import losses
  from keras.api._v2.keras import metrics
  from keras.api._v2.keras import optimizers
  from keras.api._v2.keras import initializers
# pylint: enable=g-import-not-at-top

The problem is because keras is a special class that enables lazy loading and not a normal module.

Edit: With updates to tf, vscode, or something else I’m not having this issue and don’t need to use the above fix anymore. I just have to use keras = tf.keras instead of from tensorflow import keras and I have Intellisense working now.

Answered By: bahalbach

Try this

Don’t import it directly like this

import tensorflow as tf
import tensorflow.keras as keras

Instead Do

import tensorflow as tf
keras = tf.keras

After this change, Everything was fixed and started showing better suggestions including function documentations

Answered By: Abraham

tensorflow.python.keras is for developers only and should not be used, but I think it is fine to be used as "type". I have also read it is a different version than the tensorflow.keras so have this in mind.

# Those are the imports, that actualy load the correct code
import tensorflow.keras as tfk
import tensorflow.keras.layers as layers

# This is for typehinting and intllisense
import tensorflow.python.keras as _tfk
import tensorflow.python.keras.layers as _layers

# This gets highlighted as error by my linter, but it runs
tfk: _tfk
layers: _layers

# from now on, the intellisense and docstrings work
# ...
Answered By: Kacper Kwaƛny

While keras = tf.keras does the trick, I was dumbstruck that IntelliSense on my home machine wasn’t working. Turns out, the Jupyter notebook I was using wasn’t using the right Python interpreter (conda environment with tf and keras both @ 2.11.0) due to a window reload or whatever.

Answered By: Akash Agarwal

This worked for me using conda with cuda and tensoflow:

import tensorflow as tf 

from tensorflow import keras

from keras.api._v2 import keras as KerasAPI


KerasAPI.applications.ResNet50() 
Answered By: Daniel Gemer