简体   繁体   中英

Can't import tensorflow when run script from terminal, even though tensorflow works in jupyter notebook and terminal

TLDR: When I write a small script named toy_model.py and attempt to run it from the command line with

py toy_model.py

I get an error message complaining about loading tensorflow.

However, I am able to use import and use tensorflow in many other settings without any problem, such as

  • In a jupyter notebook
  • when I import toy_model.py into a jupyter notebook
  • when I use python from the command line

I have tried many recommended solutions (downloading Spyder in the Anaconda Navigator virtual environment I am using, switching from tensorflow 2.1.0 to tensorflow 2.0.0, downloading microsoft visual studio), and none have been succesful.

I would be grateful for any assistance or insight into this problem, which I will describe in more detail below.


I use Anaconda Navigator to code in Python. In Anaconda Navigator, I prepared an environment with the name updated_tensorflow . I used Anaconda's package manager to download tensorflow 2.0.0 and keras 2.3.1 into this environment.

I prepared a jupyter notebook named test1.ipynb with the following code:

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import keras
model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=(10,))])
model.compile(optimizer='adam',
          loss= 'sparse_categorical_crossentropy', #should be 'sparse_categorical_crossentropy' b/c one-hot encoded
          metrics=['accuracy'])
model.predict([[1,2,3,4,5,6,7,8,9,10], [-1,2,-3,4,-5,6,-7,8,-9,10]])

When I run test1.ipynb from the environment updated_tensorflow , there are no problems.

In the terminal I entered the environment updated_tensorflow , and began using python by typing python in the command line. I entered the same code as in test1.ipynb and had no problems.

I create a file with the name toy_model.py that contained the following code:

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import keras
model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=(10,))])
model.compile(optimizer='adam',
          loss= 'sparse_categorical_crossentropy', #should be 'sparse_categorical_crossentropy' b/c one-hot encoded
          metrics=['accuracy'])

Then, I created another jupyter notebook in the same directory as toy_model1.py with the name test2.ipynb and the following code:

from toy_model1 import *
model.predict([[1,2,3,4,5,6,7,8,9,10], [-1,2,-3,4,-5,6,-7,8,-9,10]])

This cell ran with no problems.

Finally, in this same directory, I produced a small file with the name toy_model.py which contained the code

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import keras
model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=(10,))])
model.compile(optimizer='adam',
          loss= 'sparse_categorical_crossentropy', #should be 'sparse_categorical_crossentropy' b/c one-hot encoded
          metrics=['accuracy'])
model.predict([[1,2,3,4,5,6,7,8,9,10], [-1,2,-3,4,-5,6,-7,8,-9,10]])

Then in my terminal, still in the environment updated_tensorflow , I moved to the directory containing toy_model.py and attempted to run it with

py toy_model.py

I got the following message that indicated I could not import tensorflow:

Traceback (most recent call last):
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\me\Anaconda3\Anaconda3\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\me\Anaconda3\Anaconda3\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "toy_model.py", line 3, in <module>
    import tensorflow as tf
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\__init__.py", line 50, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 69, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\me\Anaconda3\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\me\Anaconda3\Anaconda3\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\me\Anaconda3\Anaconda3\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.


Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Some of the advice I have followed in my unsuccessful efforts to fix this problem includes:

  • making sure pip and setup tools are updated

  • uninstalling and reinstalling tensorflow and keras using pip

  • uninstalling and reinstalling tensorflow and keras using conda

  • switching from tensorflow 2.1.0 to tensorflow to 2.0.0

  • installing tensorflow and keras on my base anaconda environment

  • installing tensorflow and keras on my machine

  • downloading Spyder in my updated_tensorflow environment

  • downloading Microsoft visual studios None have been successful.

I would be very grateful for any assistance in understanding and fixing whatever error I am making. It would be so nice if I could use run.py files from my terminal instead of using python exclusively in Jupyter notebooks!

Even a hint as to what the error message means would be helpful: I do not properly understand what a DLL even is.

It sounds like, by invoking python , you are not getting the specific python installation that has tensorflow (or tensorflow in that installation is broken). By default, invoking python will give you the system default (it's the first one in the environment path, so that's the first hit).

I would advise identifying exactly which python interpreter your notebook is using and calling that one specifically by saying

/path/to/notebook/interpreter/python toy_model.py

Try to get the latest supported Microsoft Visual C++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM