类型错误:只能将整数标量数组转换为标量索引

新手上路,请多包涵

我正在尝试来自 github 链接 的 tensorflow 的简单演示代码。

我目前使用的是 python 版本 3.5.2

 Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py Python
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32<br> Type "help", "copyright", "credits" or "license" for more information.

我在命令行中尝试 board.py 时遇到了这个错误。我已经安装了运行所需的所有依赖项。

 def _read32(bytestream):
    dt = numpy.dtype(numpy.uint32).newbyteorder('>')
    return numpy.frombuffer(bytestream.read(4), dtype=dt)

def extract_images(filename):
    """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
    print('Extracting', filename)
    with gzip.open(filename) as bytestream:
        magic = _read32(bytestream)
        if magic != 2051:
            raise ValueError(
                'Invalid magic number %d in MNIST image file: %s' %
                (magic, filename))
        num_images = _read32(bytestream)
        rows = _read32(bytestream)
        cols = _read32(bytestream)
        buf = bytestream.read(rows * cols * num_images)
        data = numpy.frombuffer(buf, dtype=numpy.uint8)
        data = data.reshape(num_images, rows, cols, 1)
    return data

Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py board.py
Extracting  Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
Traceback (most recent call last):
File "board.py", line 3, in <module>
    mnist = input_data.read_data_sets(r'Z:/downloads/MNIST dataset', one_hot=True)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 150, in read_data_sets
    train_images = extract_images(local_file)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 40, in extract_images
    buf = bytestream.read(rows * cols * num_images)
File "C:\Users\surak\AppData\Local\Programs\Python\Python35\lib\gzip.py", line 274, in read
    return self._buffer.read(size)
TypeError: only integer scalar arrays can be converted to a scalar index

原文由 Suraksha Ajith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 557
2 个回答

您可以修改功能:

 def _read32(bytestream):
    dt = numpy.dtype(numpy.uint32).newbyteorder('>')
    return numpy.frombuffer(bytestream.read(4), dtype=dt)

新版本:

 def _read32(bytestream):
    dt = numpy.dtype(numpy.uint32).newbyteorder('>')
    return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]

添加 [0] 最后。

这似乎是最新版本的 Numpy 的问题。最近的更改使得将单元素数组视为标量以进行索引是错误的。

原文由 Von 发布,翻译遵循 CC BY-SA 3.0 许可协议

您提供的代码链接使用名为 input_data.py 的单独文件,使用 board.py 中的以下两行从 MNIST 下载数据

import input_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=True)

由于 MNIST 数据经常用于演示目的,因此 Tensorflow 提供了一种自动下载它的方法。

board.py 中的以上两行替换为以下两行,错误将消失。

 from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

原文由 bhaskarc 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题