【问题标题】:Cannot get MNIST database through Anaconda/jupyter无法通过 Anaconda/jupyter 获取 MNIST 数据库
【发布时间】:2017-08-26 05:34:55
【问题描述】:

各位,

我是 python/anaconda/jupyter/numPy、panda 等的新手……所以如果这是一个非常愚蠢的问题,请原谅。 我正在尝试使用 anaconda/jupyter 获取 MNIST 数据库。但是每次我最后都会收到一个 HTTP 错误 500。这真的是服务器问题(正如 500 所建议的那样)还是我做错了什么?

在jupyter中输入:

from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')

结果:

    ---------------------------------------------------------------------------
    HTTPError                                 Traceback (most recent call last)
    <ipython-input-1-15dc285fb373> in <module>()
          1 from sklearn.datasets import fetch_mldata
    ----> 2 mnist = fetch_mldata('MNIST original')

    e:\ProgramData\Anaconda3\lib\site-packages\sklearn\datasets\mldata.py in fetch_mldata(dataname, target_name, data_name, transpose_data, data_home)
        140         urlname = MLDATA_BASE_URL % quote(dataname)
        141         try:
    --> 142             mldata_url = urlopen(urlname)
        143         except HTTPError as e:
        144             if e.code == 404:

    e:\ProgramData\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
        221     else:
        222         opener = _opener
    --> 223     return opener.open(url, data, timeout)
        224 
        225 def install_opener(opener):

    e:\ProgramData\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
        530         for processor in self.process_response.get(protocol, []):
        531             meth = getattr(processor, meth_name)
    --> 532             response = meth(req, response)
        533 
        534         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
        640         if not (200 <= code < 300):
        641             response = self.parent.error(
    --> 642                 'http', request, response, code, msg, hdrs)
        643 
        644         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
        562             http_err = 0
        563         args = (dict, proto, meth_name) + args
    --> 564         result = self._call_chain(*args)
        565         if result:
        566             return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
        502         for handler in handlers:
        503             func = getattr(handler, meth_name)
    --> 504             result = func(*args)
        505             if result is not None:
        506                 return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_error_302(self, req, fp, code, msg, headers)
        754         fp.close()
        755 
    --> 756         return self.parent.open(new, timeout=req.timeout)
        757 
        758     http_error_301 = http_error_303 = http_error_307 = http_error_302

    e:\ProgramData\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
        530         for processor in self.process_response.get(protocol, []):
        531             meth = getattr(processor, meth_name)
    --> 532             response = meth(req, response)
        533 
        534         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_response(self, request, response)
        640         if not (200 <= code < 300):
        641             response = self.parent.error(
    --> 642                 'http', request, response, code, msg, hdrs)
        643 
        644         return response

    e:\ProgramData\Anaconda3\lib\urllib\request.py in error(self, proto, *args)
        568         if http_err:
        569             args = (dict, 'default', 'http_error_default') + orig_args
    --> 570             return self._call_chain(*args)
        571 
        572 # XXX probably also want an abstract factory that knows when it makes

    e:\ProgramData\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
        502         for handler in handlers:
        503             func = getattr(handler, meth_name)
    --> 504             result = func(*args)
        505             if result is not None:
        506                 return result

    e:\ProgramData\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
        648 class HTTPDefaultErrorHandler(BaseHandler):
        649     def http_error_default(self, req, fp, code, msg, hdrs):
    --> 650         raise HTTPError(req.full_url, code, msg, hdrs, fp)
        651 
        652 class HTTPRedirectHandler(BaseHandler):

    HTTPError: HTTP Error 500: INTERNAL SERVER ERROR

【问题讨论】:

  • 错误信息返回 HTTP 错误 500,表示服务器内部错误。因此,很可能服务器上存在错误。我稍后再试。如果您查看 ulr mldata.org,您会发现它当前不可用。

标签: scikit-learn anaconda jupyter


【解决方案1】:

我也遇到了和你一样的错误。以下是一些不需要此服务器的可能解决方案。

如果你安装了tensorflow,你可以通过以下方式获取MNIST数据:

import tensorflow.examples.tutorials.mnist.input_data as input_data
m=input_data.read_data_sets("MNIST")

那么例如len(m.train.images)是55000。

如果你没有 tensorflow,你可以使用指令here 获取这个数据集。

【讨论】:

    【解决方案2】:

    这里是下载 MNIST 数据集的替代位置(引用自 https://github.com/ageron/handson-ml/blob/master/03_classification.ipynb)

    from six.moves import urllib
    from sklearn.datasets import fetch_mldata
    try:
        mnist = fetch_mldata('MNIST original')
    except urllib.error.HTTPError as ex:
        print("Could not download MNIST data from mldata.org, trying alternative...")
    
        # Alternative method to load MNIST, if mldata.org is down
        from scipy.io import loadmat
        mnist_alternative_url = "https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat"
        mnist_path = "./mnist-original.mat"
        response = urllib.request.urlopen(mnist_alternative_url)
        with open(mnist_path, "wb") as f:
            content = response.read()
            f.write(content)
        mnist_raw = loadmat(mnist_path)
        mnist = {
            "data": mnist_raw["data"].T,
            "target": mnist_raw["label"][0],
            "COL_NAMES": ["label", "data"],
            "DESCR": "mldata.org dataset: mnist-original",
        }
        print("Success!")
    

    【讨论】:

      【解决方案3】:

      在这里找到了一个好的解决方案:https://github.com/Lasagne/Lasagne/blob/master/examples/mnist.py

      它从严乐存的网站(http://yann.lecun.com/exdb/mnist/)下载数据集。

      import os
      from urllib import urlretrieve
      
      def download(filename, source='http://yann.lecun.com/exdb/mnist/'):
          print("Downloading %s" % filename)
          urlretrieve(source + filename, filename)
      
      # We then define functions for loading MNIST images and labels.
      # For convenience, they also download the requested files if needed.
      import gzip
      
      def load_mnist_images(filename):
          if not os.path.exists(filename):
              download(filename)
          # Read the inputs in Yann LeCun's binary format.
          with gzip.open(filename, 'rb') as f:
              data = np.frombuffer(f.read(), np.uint8, offset=16)
          # The inputs are vectors now, we reshape them to monochrome 2D images,
          # following the shape convention: (examples, channels, rows, columns)
          data = data.reshape(-1, 1, 28, 28)
          # The inputs come as bytes, we convert them to float32 in range [0,1].
          # (Actually to range [0, 255/256], for compatibility to the version
          # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)
          return data / np.float32(256)
      
      def load_mnist_labels(filename):
          if not os.path.exists(filename):
              download(filename)
          # Read the labels in Yann LeCun's binary format.
          with gzip.open(filename, 'rb') as f:
              data = np.frombuffer(f.read(), np.uint8, offset=8)
          # The labels are vectors of integers now, that's exactly what we want.
          return data
      
      
      X_train = load_mnist_images('train-images-idx3-ubyte.gz')
      y_train = load_mnist_labels('train-labels-idx1-ubyte.gz')
      X_test = load_mnist_images('t10k-images-idx3-ubyte.gz')
      y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')
      

      【讨论】:

        【解决方案4】:

        我也遇到了同样的错误,不得不关闭防火墙。在 Macbook 上,转到系统偏好设置 > 安全和隐私 > 防火墙 > 关闭防火墙。

        【讨论】:

        • 我建议遇到此错误的每个人都先尝试一下。所有这些其他解决方法都可能有效,但为此禁用防火墙更容易。
        【解决方案5】:
        from sklearn.datasets import fetch_mldata
        try:
            mnist = fetch_mldata('MNIST original')
        except Exception as ex:        
            from six.moves import urllib
            from scipy.io import loadmat
            import os
        
            mnist_path = os.path.join(".", "datasets", "mnist-original.mat")
        
            # download dataset from github.
            mnist_alternative_url = "https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat"
            response = urllib.request.urlopen(mnist_alternative_url)
            with open(mnist_path, "wb") as f:
                content = response.read()
                f.write(content)
        
            mnist_raw = loadmat(mnist_path)
            mnist = {
                "data": mnist_raw["data"].T,
                "target": mnist_raw["label"][0],
                "COL_NAMES": ["label", "data"],
                "DESCR": "mldata.org dataset: mnist-original",
            }
            print("Done!")
        

        【讨论】:

        • 这个答案全是代码。请添加一些解释和放大信息。
        • 我第一次运行此代码时一切正常,但在打开 jupyter 并再次运行后,它给了我以下错误: FileNotFoundError: [Errno 2] No such file or directory: '.\\datasets \\mnist-original.mat'
        【解决方案6】:

        这适用于 python 3.6.*

        import os
        from urllib.request import urlretrieve
        import numpy as np
        
        def download(filename, source='http://yann.lecun.com/exdb/mnist/'):
            print("Downloading %s" % filename)
            urlretrieve(source + filename, filename)
        
        # We then define functions for loading MNIST images and labels.
        # For convenience, they also download the requested files if needed.
        import gzip
        
        def load_mnist_images(filename):
            if not os.path.exists(filename):
                download(filename)
            # Read the inputs in Yann LeCun's binary format.
            with gzip.open(filename, 'rb') as f:
                data = np.frombuffer(f.read(), np.uint8, offset=16)
            # The inputs are vectors now, we reshape them to monochrome 2D images,
            # following the shape convention: (examples, channels, rows, columns)
            data = data.reshape(-1, 1, 28, 28)
            # The inputs come as bytes, we convert them to float32 in range [0,1].
            # (Actually to range [0, 255/256], for compatibility to the version
            # provided at http://deeplearning.net/data/mnist/mnist.pkl.gz.)
            return data / np.float32(256)
        
        def load_mnist_labels(filename):
            if not os.path.exists(filename):
                download(filename)
            # Read the labels in Yann LeCun's binary format.
            with gzip.open(filename, 'rb') as f:
                data = np.frombuffer(f.read(), np.uint8, offset=8)
            # The labels are vectors of integers now, that's exactly what we want.
            return data
        
        
        X_train = load_mnist_images('train-images-idx3-ubyte.gz')
        y_train = load_mnist_labels('train-labels-idx1-ubyte.gz')
        X_test = load_mnist_images('t10k-images-idx3-ubyte.gz')
        y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')
        

        【讨论】:

          【解决方案7】:

          聚会迟到了,但我遇到了同样的错误,我的简单解决方案是分别运行这两个命令,例如:

          from sklearn import datasets
          

          并确保在 jupyter notebook 的单独行中运行它

          mnist_data = datasets.fetch_mldata('MNIST original', data_home = 'datasets/')
          

          【讨论】:

          • 这确实有效,我很惊讶。想知道这与在同一个单元格中运行两个命令有何不同?
          【解决方案8】:

          我在https://github.com/ageron/handson-ml/issues/7 上找到了这个解决方案,这个解决方案对我最有用。只需从https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat下载文件

          之后使用这个脚本:

          from scipy.io import loadmat
          mnist_path = "my/local/path/mnist-original.mat" #type the directory where you want to the file is located
          mnist_raw = loadmat(mnist_path)
          mnist = {
          "data": mnist_raw["data"].T,
          "target": mnist_raw["label"][0],
          "COL_NAMES": ["label", "data"],
          "DESCR": "mldata.org dataset: mnist-original",
          }
          print("Success!")
          

          【讨论】:

            【解决方案9】:

            你去这个链接怎么样:

            https://anaconda.org/conda-forge/mnist

            按照说明进行操作:

            1. 打开 Anaconda 提示
            2. 键入 conda install -c conda-forge mnist
            3. 键入 conda install -c conda-forge/label/cf201901 mnist

            我也遇到了同样的问题,我按照这些说明进行操作,再也没有出现任何错误。 希望这会有所帮助。抱歉,如果这不能解决您的问题。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-07-07
              • 2018-01-10
              • 2016-11-14
              • 1970-01-01
              • 1970-01-01
              • 2013-02-10
              • 2021-11-30
              相关资源
              最近更新 更多