10

I'm trying to run the code below in my Jupyter Notebook. I get:

AttributeError: module 'tensorflow.python.keras.utils' has no attribute 'to_categorical'

This is code from Kaggle tutorial. I have installed Keras and Tensorflow.

 import numpy as np
    import pandas as pd
    from sklearn.model_selection import train_test_split
    from tensorflow.python import keras
    from tensorflow.python.keras.models import Sequential
    from tensorflow.python.keras.layers import Dense, Flatten, Conv2D, Dropout
  img_rows, img_cols = 28, 28
num_classes = 10

def data_prep(raw):
    out_y = keras.utils.to_categorical(raw.label, num_classes)

    num_images = raw.shape[0]
    x_as_array = raw.values[:,1:]
    x_shaped_array = x_as_array.reshape(num_images, img_rows, img_cols, 1)
    out_x = x_shaped_array / 255
    return out_x, out_y

raw_data = pd.read_csv('trainMNIST.csv')

x, y = data_prep(raw_data)

model = Sequential()
model.add(Conv2D(20, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=(img_rows, img_cols, 1)))
model.add(Conv2D(20, kernel_size=(3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer='adam',
              metrics=['accuracy'])
model.fit(x, y,
          batch_size=128,
          epochs=2,
          validation_split = 0.2)

vojtak
  • 241
  • 1
  • 2
  • 6

5 Answers5

8

Newer versions of keras==2.4.0 and tensorflow==2.3.0 would work as follows.

Import:

from keras.utils import np_utils

or

from keras import utils as np_utils

and then replace keras.utils.to_categorical with

keras.utils.np_utils.to_categorical
Vin Bolisetti
  • 81
  • 1
  • 2
2

Include this in your code

from tensorflow import keras

in place of

from tensorflow.python import keras

1

As of tensorflow version 2.9.2, the correct import is:

from tensorflow.python.keras.utils.np_utils import to_categorical
1

Use keras>=2.2 and tensorflow >=1.14 to resolve the issue.

SrJ
  • 838
  • 4
  • 9
1

As it already has been said, to_categorical() is function. It in keras for tensorflow 2.x can be imported this way:

from keras.utils import to_categorical

then used like this:

digit=6
x=to_categorical(digit, 10)
print(x)

it will print

[0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]

Where 10 is the number of classes, the input values range is [0;number_of_classes-1]. The output is activated (1) or not active (0) position.

A. Genchev
  • 111
  • 3