Reputation: 11
I'm creating a very basic AI with Tensorflow, and am using the code from the official docs/tutorial. Here's my full code:
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images / 255.0
train_labels = train_labels / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
The issue is on this line:
plt.xlabel(class_names[train_labels[i]])
TypeError: list indices must be integers or slices, not numpy.float64
No problem, change the numpy.float64
to int
using .item()
plt.xlabel(class_names[train_labels[i.item()]])
AttributeError: 'int' object has no attribute 'item'
Was it an int
in the first place?
This is running on Python 3.7, with Tensorflow 1.13.1.
Upvotes: 1
Views: 525
Reputation: 9
Normalization (division by 255 in this case) is what is usually necessary to do with features, and not with labels, for labels try to use One hot encoding.
Upvotes: 0
Reputation: 18371
The error is caused by
train_labels = train_labels / 255.0
train_labels
is a ndarray of labels. By dividing it to 255, the resulting ndarray contains float numbers. Therefore a floating number is used as an index for class_names
resulting to the first error.
list indices must be integers or slices, not numpy.float64
To convert a numpy array x
to int, here is the way to go: x.astype(int)
. But in this case doing so will create an array with all values to 0.
A fix is to remove the line identified above:
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images = train_images / 255.0
# train_labels = train_labels / 255.0
plt.figure(figsize=(10,10))
for i in range(25):
print(train_labels[i], train_images.shape, train_labels.shape, type(train_labels))
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
Upvotes: 1