TypeError: only integer scalar arrays can be converted to a scalar index

这个错误从字面的意思是:只有整数标量数组才能转换成标量索引。
关键错误代码如下:

def _read32(bytestream):  
    dt = numpy.dtype(numpy.uint32).newbyteorder('>')  
    return numpy.frombuffer(bytestream.read(4), dtype=dt)  
def extract_images(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) 
        #try to print the value
        print("the rows=",rows,"--the cols=",cols,"--the num_images=",num_images)
        buf = bytestream.read(rows * cols * num_images)  
        data = numpy.frombuffer(buf, dtype=numpy.uint8)  
        data = data.reshape(num_images, rows, cols, 1)  
        return data

输出log如下:

the rows= [28] –the cols= [28] –the num_images= [60000]

错误log及调用栈如下:
TypeError Traceback (most recent call last)
in ()
167 #import input_data
168 #mnist = input_data.read_data_sets(“MNIST_data/”, one_hot=True)
–> 169 mnist = read_data_sets(“MNIST_data/”, one_hot=True)
170 import tensorflow as tf
171 x = tf.placeholder(‘float’,[None,784])

in read_data_sets(train_dir, fake_data, one_hot)
141 VALIDATION_SIZE = 5000
142 local_file = maybe_download(TRAIN_IMAGES, train_dir)
–> 143 train_images = extract_images(local_file)
144 local_file = maybe_download(TRAIN_LABELS, train_dir)
145 train_labels = extract_labels(local_file, one_hot=one_hot)

in extract_images(filename)
39 cols = cols.astype(numpy.integer)
40 print(“the rows=”,rows,”–the cols=”,cols,”–the num_images=”,num_images)
—> 41 buf = bytestream.read(rows * cols * num_images)
42 data = numpy.frombuffer(buf, dtype=numpy.uint8)
43 data = data.reshape(num_images, rows, cols, 1)

/usr/lib/python2.7/gzip.pyc in read(self, size)
273
274 offset = self.offset - self.extrastart
–> 275 chunk = self.extrabuf[offset: offset + size]
276 self.extrasize = self.extrasize - size
277

TypeError: only integer scalar arrays can be converted to a scalar index

从打印出来的log 及调用栈可以看到,问题出现在这条语句:
buf = bytestream.read(rows * cols * num_images)
后来改为bytestream.read(28*28*60000),这块的问题消失。
打印rows,cols,num_num_images,
发现都加了中括号。【】感觉这是个数组。
结合字面意思感觉传入的参数是一个整数数组。实际上应该是个整数。

后来找到一个一样的错误,
他们给出了解决方案:
https://stackoverflow.com/questions/42128830/typeerror-only-integer-scalar-arrays-can-be-converted-to-a-scalar-index

def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder(‘>’)
return numpy.frombuffer(bytestream.read(4), dtype=dt)
new version:

def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder(‘>’)
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
add [0] in the end.

主要是numpy.frombuffer()函数返回了一个数组,这个数组长度是1,内容就是我们要的值。
所以使用【0】就可以取得这个整数值。

以此mark 一下,以后碰到类似问题可以使用类似的方式解决。

相关文章
相关标签/搜索