使用Tensorflow时将numpy.float64转换为int类型的问题

我正在使用Tensorflow创建一个非常基础的人工智能,并且使用了官方文档/教程中的代码。以下是我的完整代码:

from __future__ import absolute_import, division, print_functionimport tensorflow as tffrom tensorflow import kerasimport matplotlib.pyplot as pltfashion_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.0train_labels = train_labels / 255.0plt.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()

问题出现在这一行:

plt.xlabel(class_names[train_labels[i]])TypeError: list indices must be integers or slices, not numpy.float64

没问题,使用.item()numpy.float64转换为int

plt.xlabel(class_names[train_labels[i.item()]])AttributeError: 'int' object has no attribute 'item'

它原本就是int类型吗?

这是在Python 3.7上运行的,使用的是Tensorflow 1.13.1版本。


回答:

错误是由以下代码引起的:

train_labels = train_labels / 255.0

train_labels是一个标签的ndarray。通过将其除以255,结果ndarray中包含浮点数。因此,一个浮点数被用作class_names的索引,导致了第一个错误。

list indices must be integers or slices, not numpy.float64

要将numpy数组x转换为int,可以使用x.astype(int)。但在这种情况下,这样做会创建一个所有值都为0的数组。

解决方法是删除上面标识的行:

from __future__ import absolute_import, division, print_functionimport tensorflow as tffrom tensorflow import kerasimport matplotlib.pyplot as pltfashion_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.0plt.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()

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注