I'm trying to import my training dataset for my CNN (30,000 images), but there's something about this line that breaks the program.
data_dir = tf.keras.utils.get_file(origin=dataset_url,
fname='functionidentifier',
untar=True)
Here's the full code block for more context:
dataset_url = "https://barisciencelab.tech/functionidentifier.tgz"
data_dir = tf.keras.utils.get_file(origin = dataset_url,
fname = "functionidentifier",
untar = True)
data_dir = pathlib.Path(data_dir)
It was working just last week, but suddenly broke:
Some things I tried:
Changing extension of my training set from .tar.gz to .zip and .tar.tar and .tgz.
Unit testing (all other parts of code are fine; they're just importing stuff anyway)
Exact same code in a new Google Colab Notebook and Jupyter Notebook. Neither worked.
Checked the documentation. My code is verbatim the same! The only thing that's different is literally my URL. That's it.
Nothing worked. And no, I can't manually download the whole training set and do this locally (big-time hassle).
MWE (Full Code)
pip install tensorflow
pip install numpy
pip install matplotlib
!git clone https://github.com/Refath/SinusoidalAnalyzer.git
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import pathlib
dataset_url = "https://barisciencelab.tech/TrainingSet.tar.gz"
data_dir = tf.keras.utils.get_file(origin = dataset_url, fname = "TrainingSet", untar = True)
data_dir = pathlib.Path(data_dir)
Folks in the SO Chat valiantly tried to debug the issue as well, but to no avail. If anyone can help, that would be great.
Have you tried installing a previous version of TF in the colab notebook
pip install tensorflow==2.x
import tensorflow as tf
print(tf.__version__)
Or maybe your URL is no longer reachable from the colab VM. Try to ping its ip, you can run terminal commands with !ping "IP"
For anyone in the future battling with this issue:
I came across this problem as well. I did some digging and found that the problem was that I didn't have the right certificates installed for Python3. Fairly easy fix on a Mac - run the file located at Applications>Python 3.X>Install Certificates.command and that should do the trick.
Not sure if this problem pops up on other OSs or not but I'd imagine the fix is similar.
Took me three solid days. In the end, here's what worked:
import os
import pathlib
!wget https://barisciencelab.tech/FunctionIdentifier.zip
!unzip FunctionIdentifier.zip
PATH = os.path.join(os.path.dirname('FunctionIdentifier.zip'), 'FunctionIdentifier')
data_dir = pathlib.Path(PATH)
Here's the output:
And of course, it goes on for 30,000 lines.
How did I come up with this solution? After combing through the web, I stumbled upon the 403 – Forbidden code, different from my 406--Not Acceptable code, but nonetheless worth a look. I tried porting the solution over and after some modifications (i.e., I define the training/test/validation set parameters separately and feed the PATH into data_dir).
Also, thanks to #Kevin & #AndrasDeak for spending a significant amount of time helping me debug.
Related
When I import tensorflow
import tensorflow as tf
I don't get an error. However, I do get the error below. I'm using spyder if that helps.
As per other questions, I ensured up to date (v1.8) tensorflow using both conda and then pip installs. This didn't resolve the issue. Please assist.
import tensorflow.examples.tutorials.mnist.input_data as input_data
ModuleNotFoundError: No module named 'tensorflow.examples'
I think you should use like bellow on tensorflow 2
import tensorflow_datasets
mnist = tensorflow_datasets.load('mnist')
Use the following, it will download the data. It is from the tensorflow documentation
import tensorflow as tf
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
Sometimes the TensorFlow examples are not pre-downloaded, so you might need to run the below command to install the examples from Github using the below code.
!pip install -q git+https://github.com/tensorflow/examples.git
To load the mnist dataset in Tensorflow 2.0:
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
Here is the reference:
TensorFlow 2 quickstart for beginners
Another method(also works for locally saved dataset):
DATA_URL = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz'
path = tf.keras.utils.get_file('mnist.npz', DATA_URL)
with np.load(path) as data:
train_examples = data['x_train']
train_labels = data['y_train']
test_examples = data['x_test']
test_labels = data['y_test']
Here is the reference:
Load NumPy data
Sometimes on downloading the TF, the example directory might not be available. You could rectify it by linking the 'example' directory from the GitHub repo into the tensorflow python wheel folder. That way you don't need to change the code.
If this doesn't work, try to replace import tensorflow.examples.tutorials.mnist.input_data as input_data as import input_data as mentioned in the link:
TensorFlow MNIST example not running with fully_connected_feed.py
Hope this helps!!!
Different approach
OS: Windows
copy from:
https://github.com/tensorflow/examples/tree/master/tensorflow_examples
to
[python folder]\Lib\site-packages\tensorflow_examples
use
import tensorflow_examples
example
from tensorflow_examples.models import pix2pix
but for datasets use:
pip install tensorflow_datasets
I solved this issue by adding **tutorial** directory into tensorflow_core, usually this issue pops up when lacking of this file
..\anaconda3\envs\tensorflow\Lib\site-packages\tensorflow_core\examples check this directory to see if you have tutorials file.
lack of tutorial file
If you do not have, then go to https://github.com/tensorflow/tensorflow download the zip file, and extract all (or open it).
download tutorial file
find tutorials file from tensorflow-master\tensorflow\examples\, and copy it to ..\anaconda3\envs\tensorflow\Lib\site-packages\tensorflow_core\examples.
Issue resolved.
run
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
im = mnist.train.images[1]
im = im.reshape(-1, 28)
plt.imshow(im)
I solved this issue on Mac, simply copy the official examples to tensorflow_core/examples directory.
pull the tensorflow code
git clone https://github.com/tensorflow/tensorflow
copy the examples to the system python3 directory
cp -a tensorflow/examples/ /usr/local/lib/python3.7/site-packages/tensorflow_core/examples/
You need to download the data sets to use it.
Command:
pip install tensorflow-datasets
Code part:
mnist_train = tfds.load(name="mnist", split="train")
You are done now. Happy coding! :)
You just need to download the lost files and copy them to the tensorflow-core/ examples.
for me on windows 10 is :
C:\Users\Amirreza\AppData\Local\Programs\Python\Python37\Lib\site-packages\tensorflow_core\examples
This folder has been deleted at September/2020. See their repository.
I used the commands:
git clone https://github.com/tensorflow/tensorflow.git
tensorflow> git checkout c31acd156c
I solved this issue by installing Keras according to this answer from different question:
I didn't have Keras installed and had to add it manualy
ImportError: No module named 'keras'
I have a bunch of code written using Keras that was installed as a separate pip install and the import statements are written like from keras.models import Sequential, etc..
On a new machine, I have Tensorflow installed which now includes Keras inside the contrib directory. In order to keep the versions consistent I thought it would be best to use what's in contrib instead of installing Keras separately, however this causes some import issues.
I can import Keras using import tensorflow.contrib.keras as keras but doing something like from tensorflow.contrib.keras.models import Sequential gives ImportError: No module named models, and from keras.models import Sequential gives a similar ImportError: No module named keras.models.
Is there a simple method to get the from x.y import z statements to work? If not it means changing all the instances to use the verbose naming (ie.. m1 = keras.models.Sequential()) which isn't my preferred syntax but is do-able.
Try this with recent versions of tensorflow:
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import LSTM, TimeDistributed, Dense, ...
Try with tensorflow.contrib.keras.python.keras:
from tensorflow.contrib.keras.python.keras.models import Sequential
Unfortunately from tensorflow.contrib.keras.python.keras.models import Sequential no longer works. It looks like they are changing the interface as of version 1.4 (currently at RC0). There is a note saying the tensorflow.contrib.keras interface is deprecated and you should use tensorflow.keras but this doesn't work either without python in the line.
The following did work for me under V1.4rc0
from tensorflow.python.keras.models import Sequential
import tensorflow.python.keras
import tensorflow.contrib.keras as keras
The following did not...
import tensorflow.python.keras as keras
Hopefully this gets cleaned up a bit more before final release.
I am doing a deep learning course on udacity. For the first assignment whenI tried to run the script which is below the problem 1 , I got this error. So I tried to uninstall PIL and pillow and then installed these individually but I didnot succeeded.
I need help guy. I am using tensorflow docker image with python notebook.
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import scipy
import tarfile
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlretrieve
from six.moves import cPickle as pickle
# Config the matplotlib backend as plotting inline in IPython
%matplotlib inline
url = 'http://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None
def download_progress_hook(count, blockSize, totalSize):
percent = int(count * blockSize * 100 / totalSize)
if last_percent_reported != percent:
if percent % 5 == 0:
sys.stdout.write("%s%%" % percent)
sys.stdout.flush()
else:
sys.stdout.write(".")
sys.stdout.flush()
last_percent_reported = percent
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb
You can see the code here. I got error in the code block after problem 1
Error Image
I tried each and everything describe here in these two links or solutions:
Solution 1 on stackoverflow
Solution 2 on stackoverflow
Operating System:
using docker and tensorflow is installed in a container with IPython notebook.
The output from python -c "import tensorflow; print(tensorflow.version)".
0.11.0
pip install pillow
Then replace
from IPython.display import display, Image
with
from IPython.display import display
from PIL import Image
I met the same problem. But I am using a different setting for the tensorflow. OS: Ubuntu 14.04 LTS. Installation using Anaconda.
I solved it by following the warnings in Pillow installation. It may not be useful for a docker installation of tensorflow though.
Here are the steps I did. First enter the tensorflow environment,
source activate tensorflow
Then uninstall PIL and install Pillow
conda uninstall PIL
conda install Pillow
Then in the provided code, replace
from IPython.display import display, Image
by
from IPython.display import display
from PIL import Image
That's all. Re-run the code and it works without PIL error.
I solved this issue by uninstalling Jupyter and re-installed it properly. The problem was linked to the notebook kernel. My terminal and my notebook didn't have the same kernel.
To check it, I did in my virtualenv:
jupyter-kernelspec list
then go to your kernel directories lists and open the json file (something like /Library/Jupyter/kernels/virtualenv/kernel.json)
and check than the Python link is the same than in the output of
which python.
If not, create another kernel for your virtualenv.
As for Windows users who use Anaconda, there is likely a simple solution to your problem. If you've installed 'tensorflow' with pip, or a pip variant (ie. pip3), then you will have to install tensorflow again, but this time with the command conda install tensorflow.
Install PIL in anaconda, then:
from PIL import Image
model.fit_generator(
train_generator,
steps_per_epoch=2000 // batch_size,
epochs=50,
validation_data=validation_generator,
validation_steps=800 // batch_size)
model.save_weights('first_try.h5')
output will display like: Epoch 1/50
34/125 [=======>......................] - ETA: 7:23 - loss: 0.7237 - acc: 0.5478 ... comntinue
TensorFlow MNIST example not running with fully_connected_feed.py
I checked this out and realized that input_data was not built-in. So I downloaded the whole folder from here. How can I start the tutorial:
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-6-a5af65173c89> in <module>()
----> 1 import input_data
2 mnist = tf.input_data.read_data_sets("MNIST_data/", one_hot=True)
ImportError: No module named input_data
I'm using iPython (Jupyter) so do I need to change my working directory to this folder I downloaded? or can I add this to my tensorflow directory? If so, where do I add the files? I installed tensorflow with pip (on my OSX) and the current location is ~/anaconda/lib/python2.7/site-packages/tensorflow/__init__.py
Are these files meant to be accessed directly through tensorflow like sklearn datasets? or am I just supposed to cd into the directory and work from there? The example is not clear.
EDIT:
This post is very out-dated
So let's assume that you are in the directory: /somePath/tensorflow/tutorial (and this is your working directory).
All you need to do is to download the input_data.py file and place it like this. Let's assume that the file name you invoke:
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
...
is main.py and it is also in the same directory.
Once this is done, you can just start running main.py which will start downloading the files and will put them in the MNIST_data folder (once they are there the script will not be downloading them next time).
The old tutorial said, to import the MNIST data, use:
import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
This will cause the error.
The new tutorial uses the following code to do so:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
And this works well.
I am using different version - following Install on Windows with Docker here - and had similar problem.
An easy workaround I've found was:
1.Into the Linux command line, figure out where is the input_data.py on my Docker image (in your case you mentionned that you had to download it manually. In my case, it was already here). I used the follwing linux command:
$ sudo find . -print | grep -i '.*[.]py'
I've got the files & path
./tensorflow/g3doc/tutorials/mnist/mnist.py
./tensorflow/g3doc/tutorials/mnist/input_data.py
2.launch Python and type the following command using SYS:
>> import sys
>> print(sys.path)
you will get the existing paths.
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat']
4.add the path of inputa_data.py:
>> sys.path.insert(1,'/tensorflow/tensorflow/g3doc/tutorials/mnist')
Hope that it can help. If you found better option, let me know. :)
How can I start the tutorial
I didn't download the folder you did but I installed tensorflow by pip and then I had similar problem.
My workaround was to replace
import tensorflow.examples.tutorials.mnist.input_data
with
import tensorflow.examples.tutorials.mnist.input_data as input_data
If you're using Tensorflow 2.0 or higher, you need to install tensorflow_datasets first:
pip install tensorflow_datasets
or if you're using an Anaconda distribution:
conda install tensorflow_datasets
from the command line.
If you're using a Jupyter Notebook you will need to install and enable ipywidgets. According to the docs (https://ipywidgets.readthedocs.io/en/stable/user_install.html) using pip:
pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension
If you're using an Anaconda distribution, install ipywidgets from the command line like such:
conda install -c conda-forge ipywidgets
With the Anaconda distribution there is no need to enable the extension, conda handles this for you.
Then import into your code:
import tensorflow_datasets as tfds
mnist = tfds.load(name='mnist')
You should be able to use it without error if you follow these instructions.
I might be kinda late, but for tensorflow version 0.12.1, you might wanna use input_data.read_data_sets instead.
Basically using this function to load the data from your local drive that you had downloaded from http://yann.lecun.com/exdb/mnist/.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data_set/')
For TensorFlow API 2.0 the mnist data changed place to: tf.keras.datasets.mnist.load_data
There's now a much easier way to load MNIST data into tensorflow without having to download the data by using Tensorflow 2 and Tensorflow Datasets
To get started, make sure you import Tensorflow and specify the 2nd version:
%tensorflow_version 2.x
import tensorflow as tf
Then load the data into a dictionary using the following code:
MNIST_data = tfds.load(name = "mnist")
and Then split the data into train and test:
train, test = MNIST_data['train'] , MNIST_data['test']
Now you can use these data generators however you like.
Remove the lines:
from tensorflow.examples.tutorials.mnist import input_data
fashion_mnist = input_data.read_data_sets('input/data',one_hot=True)
and the line below will suffice:
fashion_mnist = keras.datasets.fashion_mnist
Note that if the dataset is not available in the examples built-in to the keras, this will download the dataset and solve the problem. :)
cd your_mnist_dir &&\
wget https://github.com/HIPS/hypergrad/raw/master/data/mnist/mnist_data.pkl &&\
wget https://github.com/HIPS/hypergrad/raw/master/data/mnist/t10k-images-idx3-ubyte.gz &&\
wget https://github.com/HIPS/hypergrad/raw/master/data/mnist/t10k-labels-idx1-ubyte.gz &&\
wget https://github.com/HIPS/hypergrad/raw/master/data/mnist/train-images-idx3-ubyte.gz &&\
wget https://github.com/HIPS/hypergrad/raw/master/data/mnist/train-labels-idx1-ubyte.gz
MNIST input_data was built-in, it's just not a individual module, it's inside Tensorflow module, try
from tensorflow.examples.tutorials.mnist import input_data
MNIST data set included as a part of tensorflow examples tutorial, If we want to use this :
Import MNIST data to identify handwritten digites
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST data", one_hot=True)
As TensorFlow official website shown, All MNIST data is hosted on http://yann.lecun.com/exdb/mnist/
For Tensorflow API above 2.0, to use MNIST dataset following command can be used,
import tensorflow_datasets as tfds
data = tfds.load(name = "mnist")
The following steps work perfectly in my Notebook:
step 1 : get Python files from github :
!git clone https://github.com/tensorflow/tensorflow.git
step 2 : append these files in my Python path :
import sys
sys.path.append('/content/tensorflow/tensorflow/examples/tutorials/mnist')
step 3 : load the MNIST data with 'input_data' fonction
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
That's all !
I am able to run the Deep MNIST Example fine, but when running fully_connected_feed.py, I am getting the following error:
File "fully_connected_feed.py", line 19, in <module>
from tensorflow.g3doc.tutorials.mnist import input_data ImportError: No module named
g3doc.tutorials.mnist
I am new to Python so could also just be a general setup problem.
This is a Python path issue. Assuming that the directory tensorflow/g3doc/tutorials/mnist is your current working directory (or in your Python path), the easiest way to resolve it is to change the following lines in fully_connected_feed.py from:
from tensorflow.g3doc.tutorials.mnist import input_data
from tensorflow.g3doc.tutorials.mnist import mnist
...to:
import input_data
import mnist
Another alternative is to link the 'g3doc' directory from the github repo into the tensorflow python wheel folder. That way you don't need to change the code.