Home > OS >  Error while importing tensorflow as tf on Colab
Error while importing tensorflow as tf on Colab

Time:09-01

I had been using a simple "import tensorflow as tf" command to import tensorflow on my Colab notebook for months. However, just recently the same code and notebooks started giving me the error "from future imports must occur at the beginning of the file".

The tensorflow package version I found on using "!pip list" was "2.8.2 zzzcolab20220719082949".

The main thing confusing me is how a notebook/code that was working perfectly 2 weeks back suddenly starts giving errors.

The code for the cell I ran which gave this error was:

import sys
from tflite_model_maker import image_classifier
from tflite_model_maker.image_classifier import DataLoader
from tflite_model_maker.image_classifier import EfficientNetLite0Spec
from tflite_model_maker.image_classifier import EfficientNetLite4Spec
from __future__ import absolute_import, division, print_function, unicode_literals

import matplotlib.pylab as plt
import tensorflow as tf

The error I got was -

File "", line 9 import tensorflow as tf ^ SyntaxError: from future imports must occur at the beginning of the file

CodePudding user response:

You only have to move your __future__ import at the top of your code to make it work:

from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from tflite_model_maker import image_classifier
from tflite_model_maker.image_classifier import DataLoader
from tflite_model_maker.image_classifier import EfficientNetLite0Spec
from tflite_model_maker.image_classifier import EfficientNetLite4Spec

import matplotlib.pylab as plt
import tensorflow as tf

Please have a look at the future-statements docs:

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

  • the module docstring (if any),
  • comments,
  • blank lines, and
  • other future statements.

In your case you have other imports before your __future__, which is not allowed.

  • Related