【问题标题】:EOFError: Compressed file ended before the end-of-stream marker was reached - MNIST data setEOFError:压缩文件在到达流结束标记之前结束 - MNIST 数据集
【发布时间】:2016-11-29 23:37:47
【问题描述】:

我在运行mnist = input_data.read_data_sets("MNIST_data", one_hot = True) 时收到以下错误。

EOFError: 压缩文件在到达流结束标记之前结束

即使我手动提取文件并将其放在MNIST_data 目录中,程序仍在尝试下载文件而不是使用提取的文件。

当我使用手动方式的 WinZip 提取文件时,WinZip 告诉我文件已损坏。

我该如何解决这个问题?

我现在连数据集都加载不出来,还要自己调试程序。请帮忙。

我 pip 安装了 Tensorflow,所以我没有 Tensorflow 示例。于是我去 GitHub 上获取了input_data 文件,并将其保存在与我的main.py 相同的目录中。该错误仅与 .gz 文件有关。程序无法提取它。

runfile('C:/Users/Nikhil/Desktop/Tensor Flow/tensf.py', wdir='C:/Users/Nikhil/Desktop/Tensor Flow') 重新加载的模块:input_data 提取 MNIST_data/train-images-idx3-ubyte.gz C:\Users\Nikhil\Anaconda3\lib\gzip.py:274: VisibleDeprecationWarning: convert an array with ndim > 0 to an index 以后会报错 返回 self._buffer.read(size) Traceback(最近一次调用最后一次):

文件“”,第 1 行,在 runfile('C:/Users/Nikhil/Desktop/Tensor Flow/tensf.py', wdir='C:/Users/Nikhil/Desktop/Tensor Flow')

文件“C:\Users\Nikhil\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 866 行,在运行文件中 execfile(文件名,命名空间)

文件“C:\Users\Nikhil\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 102 行,在 execfile exec(编译(f.read(),文件名,'exec'),命名空间)

文件“C:/Users/Nikhil/Desktop/Tensor Flow/tensf.py”,第 26 行,在 mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)

文件“C:\Users\Nikhil\Desktop\Tensor Flow\input_data.py”,第 181 行,在 read_data_sets 中 train_images = extract_images(local_file)

文件“C:\Users\Nikhil\Desktop\Tensor Flow\input_data.py”,第 60 行,在 extract_images buf = bytestream.read(rows * cols * num_images)

文件“C:\Users\Nikhil\Anaconda3\lib\gzip.py”,第 274 行,正在读取 return self._buffer.read(size)

文件“C:\Users\Nikhil\Anaconda3\lib_compression.py”,第 68 行,读入 数据 = self.read(len(byte_view))

文件“C:\Users\Nikhil\Anaconda3\lib\gzip.py”,第 480 行,正在读取 raise EOFError("压缩文件在 "

EOFError: 压缩文件在到达流结束标记之前结束

【问题讨论】:

  • 你有没有解决这个错误?我遇到了类似的错误。
  • 这也发生在我身上,但经过 2 次运行后,它就消失了!而且我不知道发生了什么!

标签: python tensorflow


【解决方案1】:

这是因为由于某种原因,您对 MNIST 数据集的下载不完整。

您必须手动删除下载的文件夹,该文件夹通常位于 ~/.keras/datasets 或您指定的相对于此路径的任何路径,在您的情况下为 MNIST_data

在终端中执行以下步骤(ctrl + alt + t):

  1. cd ~/.keras/datasets/
  2. rm -rf "dataset name"

你应该很高兴!

【讨论】:

  • 如何概括?我有一个正在上传的 .tar.gz 文件,它给了我同样的错误。我必须采取哪些步骤?
  • 或者,如果是 Windows,请删除 C:\Users\{yourname}\.keras\datasets
【解决方案2】:

在windows中很简单:

转到:C:\Users\Username\.keras\datasets

然后删除要重新下载或出现错误的数据集

【讨论】:

    【解决方案3】:

    对于任何挣扎的人,我也有类似的问题。在我的 Mac Mojave 10.14.3 上。 使用 Anaconda 和 Jupyter 在 UDEMY 上上课,使用以下方法解决了这个问题。 Finder > Go > Go to Folder > In go to folder window input ~/.keras/datasets/fashion_mnist > delete the partially downloaded files

    去 GitHub 搜索来自https://github.com/zalandoresearch/fashion-mnist.git的时尚mnist-master

    下载文件定位数据>时尚文件解压四个文件

    将四个解压后的文件放入~/.keras/datasets/fashion_mnist >

    在新页面中打开 Jupyter Lab 插入以下内容:

    from keras.datasets import fashion_mnist
    
    #message states using TensorFlow backend
    
    (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
    
    #it will then cycle through as if the download were successful  
    

    祝你好运,可能对你有利。

    【讨论】:

      【解决方案4】:

      如果下载中断,请删除C:/tmp/imagenet文件夹并重新开始下载。

      另外,对于通过 Google 访问的用户,请通过命令行运行 classify_image.py 文件,而不是使用 IDLE:

      python classify_image.py
      

      【讨论】:

        【解决方案5】:

        首先,从 Keras 目录中删除部分安装的fashion_mnist 目录。

        之后,从 GitHub 下载文件

        https://github.com/zalandoresearch/fashion-mnist/blob/master/data/fashion/train-labels-idx1-ubyte.gz

        将这些文件和提取的文件放在 Keras 文件夹的 fashion_mnist 目录中。

        这将解决您的问题。

        【讨论】:

          【解决方案6】:

          下载数据集时会发生这种情况,但由于某些原因未下载。 任何人在使用 pytorch 时都在 Windows 中苦苦挣扎。 我通过删除位于以下路径中的文件夹解决了同样的问题

          C:/Users/UserName/.pytorch/foldername
          

          同时检查您的情况,由于禁用隐藏文件,.pytorch 可能不可见。

          【讨论】:

            【解决方案7】:

            我在 Windows 上使用 torchvision 下载数据集时遇到了同样的问题。我可以通过从以下路径中删除所有文件来解决此问题: C:\Users\UserName\MNIST\raw

            【讨论】:

              【解决方案8】:

              我首先遇到了同样的问题,你必须使用以下 2 行代码下载数据集 我正在使用 pycharm

              'name'=tensorflow.keras.datasets.fashion_mnist
              name.load_data()
              

              先运行这个,它会下载数据然后你可以使用下面的方法加载

              'name'=tensorflow.keras.datasets.fashion_mnist
              (train_images,train_lables),(test_images,test_lables)=name.load_data()
              

              [tag:load_data() 错误,压缩文件结束 之前,fashion_nmist]

              【讨论】:

                【解决方案9】:

                我似乎无法在我的 Linux 中找到其他答案中提到的 Keras 数据集下载文件夹。

                所以,我找到了一个有点笨拙但很容易解决这个问题的方法。原来有一种内置方法可以force download mnist 库中的文件。

                1. 只需转到您 pip 安装的 mnist 库副本。这可以在您的 python 虚拟环境中轻松找到。
                venv/lib/python3.10/site-packages/mnist/__init__.py
                

                1. 现在,我们需要做的就是在这个文件中寻找force=False并将它们设置为force=True

                这是更新后的文件:

                import os
                import functools
                import operator
                import gzip
                import struct
                import array
                import tempfile
                try:
                    from urllib.request import urlretrieve
                except ImportError:
                    from urllib import urlretrieve  # py2
                try:
                    from urllib.parse import urljoin
                except ImportError:
                    from urlparse import urljoin
                import numpy
                
                
                __version__ = '0.2.2'
                
                
                # `datasets_url` and `temporary_dir` can be set by the user using:
                # >>> mnist.datasets_url = 'http://my.mnist.url'
                # >>> mnist.temporary_dir = lambda: '/tmp/mnist'
                datasets_url = 'http://yann.lecun.com/exdb/mnist/'
                temporary_dir = tempfile.gettempdir
                
                
                class IdxDecodeError(ValueError):
                    """Raised when an invalid idx file is parsed."""
                    pass
                
                
                def download_file(fname, target_dir=None, force=True):
                    """Download fname from the datasets_url, and save it to target_dir,
                    unless the file already exists, and force is False.
                
                    Parameters
                    ----------
                    fname : str
                        Name of the file to download
                
                    target_dir : str
                        Directory where to store the file
                
                    force : bool
                        Force downloading the file, if it already exists
                
                    Returns
                    -------
                    fname : str
                        Full path of the downloaded file
                    """
                    target_dir = target_dir or temporary_dir()
                    target_fname = os.path.join(target_dir, fname)
                
                    if force or not os.path.isfile(target_fname):
                        url = urljoin(datasets_url, fname)
                        urlretrieve(url, target_fname)
                
                    return target_fname
                
                
                def parse_idx(fd):
                    """Parse an IDX file, and return it as a numpy array.
                
                    Parameters
                    ----------
                    fd : file
                        File descriptor of the IDX file to parse
                
                    endian : str
                        Byte order of the IDX file. See [1] for available options
                
                    Returns
                    -------
                    data : numpy.ndarray
                        Numpy array with the dimensions and the data in the IDX file
                
                    1. https://docs.python.org/3/library/struct.html
                        #byte-order-size-and-alignment
                    """
                    DATA_TYPES = {0x08: 'B',  # unsigned byte
                                  0x09: 'b',  # signed byte
                                  0x0b: 'h',  # short (2 bytes)
                                  0x0c: 'i',  # int (4 bytes)
                                  0x0d: 'f',  # float (4 bytes)
                                  0x0e: 'd'}  # double (8 bytes)
                
                    header = fd.read(4)
                    if len(header) != 4:
                        raise IdxDecodeError('Invalid IDX file, '
                                             'file empty or does not contain a full header.')
                
                    zeros, data_type, num_dimensions = struct.unpack('>HBB', header)
                
                    if zeros != 0:
                        raise IdxDecodeError('Invalid IDX file, '
                                             'file must start with two zero bytes. '
                                             'Found 0x%02x' % zeros)
                
                    try:
                        data_type = DATA_TYPES[data_type]
                    except KeyError:
                        raise IdxDecodeError('Unknown data type '
                                             '0x%02x in IDX file' % data_type)
                
                    dimension_sizes = struct.unpack('>' + 'I' * num_dimensions,
                                                    fd.read(4 * num_dimensions))
                
                    data = array.array(data_type, fd.read())
                    data.byteswap()  # looks like array.array reads data as little endian
                
                    expected_items = functools.reduce(operator.mul, dimension_sizes)
                    if len(data) != expected_items:
                        raise IdxDecodeError('IDX file has wrong number of items. '
                                             'Expected: %d. Found: %d' % (expected_items,
                                                                          len(data)))
                
                    return numpy.array(data).reshape(dimension_sizes)
                
                
                def download_and_parse_mnist_file(fname, target_dir=None, force=True):
                    """Download the IDX file named fname from the URL specified in dataset_url
                    and return it as a numpy array.
                
                    Parameters
                    ----------
                    fname : str
                        File name to download and parse
                
                    target_dir : str
                        Directory where to store the file
                
                    force : bool
                        Force downloading the file, if it already exists
                
                    Returns
                    -------
                    data : numpy.ndarray
                        Numpy array with the dimensions and the data in the IDX file
                    """
                
                    fname = download_file(fname, target_dir=target_dir, force=force)
                    fopen = gzip.open if os.path.splitext(fname)[1] == '.gz' else open
                    with fopen(fname, 'rb') as fd:
                        return parse_idx(fd)
                
                
                def train_images():
                    """Return train images from Yann LeCun MNIST database as a numpy array.
                    Download the file, if not already found in the temporary directory of
                    the system.
                
                    Returns
                    -------
                    train_images : numpy.ndarray
                        Numpy array with the images in the train MNIST database. The first
                        dimension indexes each sample, while the other two index rows and
                        columns of the image
                    """
                    return download_and_parse_mnist_file('train-images-idx3-ubyte.gz')
                
                
                def test_images():
                    """Return test images from Yann LeCun MNIST database as a numpy array.
                    Download the file, if not already found in the temporary directory of
                    the system.
                
                    Returns
                    -------
                    test_images : numpy.ndarray
                        Numpy array with the images in the train MNIST database. The first
                        dimension indexes each sample, while the other two index rows and
                        columns of the image
                    """
                    return download_and_parse_mnist_file('t10k-images-idx3-ubyte.gz')
                
                
                def train_labels():
                    """Return train labels from Yann LeCun MNIST database as a numpy array.
                    Download the file, if not already found in the temporary directory of
                    the system.
                
                    Returns
                    -------
                    train_labels : numpy.ndarray
                        Numpy array with the labels 0 to 9 in the train MNIST database.
                    """
                    return download_and_parse_mnist_file('train-labels-idx1-ubyte.gz')
                
                
                def test_labels():
                    """Return test labels from Yann LeCun MNIST database as a numpy array.
                    Download the file, if not already found in the temporary directory of
                    the system.
                
                    Returns
                    -------
                    test_labels : numpy.ndarray
                        Numpy array with the labels 0 to 9 in the train MNIST database.
                    """
                    return download_and_parse_mnist_file('t10k-labels-idx1-ubyte.gz')
                
                
                1. 为了提高效率,您可以将它们设置回force=False,只要您不想再次下载它们(并且不要面对这个愚蠢的问题 xD)但是这些数据集无论如何都需要 1 秒才能下载,所以它应该永远不会成为大问题。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-05-11
                  • 1970-01-01
                  • 2013-02-08
                  • 1970-01-01
                  相关资源
                  最近更新 更多