【问题标题】:Tensorflow issue with conversion of type numpy.float64 to int将 numpy.float64 类型转换为 int 的 Tensorflow 问题
【发布时间】:2019-05-10 06:28:11
【问题描述】:

我正在使用 Tensorflow 创建一个非常基本的 AI,并使用官方文档/教程中的代码。这是我的完整代码:

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()

问题出在这一行:

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

没问题,把numpy.float64改成int.item()

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

首先是int吗?

这是在 Python 3.7 上运行的,带有 Tensorflow 1.13.1。

【问题讨论】:

    标签: python numpy tensorflow artificial-intelligence


    【解决方案1】:

    错误是由

    引起的
    train_labels = train_labels / 255.0
    

    train_labels 是一个标签数组。通过将其除以 255,生成的 ndarray 包含浮点数。因此,浮点数被用作class_names 的索引,从而导致第一个错误。

    列表索引必须是整数或切片,而不是 numpy.float64

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

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

    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()
    

    【讨论】:

      【解决方案2】:

      归一化(在这种情况下除以 255)通常是处理特征而不是标签所必需的,因为标签尝试使用One hot encoding

      【讨论】:

        猜你喜欢
        • 2019-05-14
        • 2021-01-27
        • 2019-10-11
        • 1970-01-01
        • 1970-01-01
        • 2014-02-20
        • 2016-03-12
        • 2017-11-05
        • 1970-01-01
        相关资源
        最近更新 更多