'keras.utils importError in Colab cannot import name "to_categorical"
I'm using Google's Colab to run the Deep Learning codes from the Book " Deep Learning with python" by François Chollet. The 1st exercise is to use the mnist dataset. I get the following error:
ImportError: cannot import name 'to_categorical' from 'keras.utils' (/usr/local/lib/python3.7/dist-packages/keras/utils/__init__.py)
I copied the code to make sure there are no typos.
Colab suggests "... manually install dependencies using either !pip or !apt.", in case a package is missing, which doesn't seem to be the case.
I nevertheless tried:
!pip install keras
which is either incorrect or irrelevant; the error persists.
What am I doing wrong? How can I correct it?
The code causing the error is:
from keras.utils import to_categorical
And this is the complete program directly from the book's source code.
from keras.datasets import mnist
from keras.utils import to_categorica
from jeras import models
from keras import layers
(train_images, train_labels), (test_images, test-labels) = mnist.load_data()
network = models.Sequential()
network.add(layers.Dense(512, activation="relu", input_shape=(28*28,)))
network.add(layers.Dense(10, activation="softmax"))
network.compile(optimizer="rmsprop",
loss="categorical_crossentropy",
metrics=["accuracy"])
train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype("float32") / 255
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype("float32") / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images, train_labels, epochs=5, batch_size=128)
test_loss, test_acc = network.evaluate(test_images, test-test_labels)
print("test_acc:", test_acc)
According to the book, this is "to classify grayscale images of handwritten images" and is supposedly the "Hello World" of deep learning.
Solution 1:[1]
Change the line
from keras.utils import to_categorical
to
from tensorflow.keras.utils import to_categorical
and it'll work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mojtaba Abdi Kh. |