Pytorch报urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED]错误

问题描述

在调用torchvision.datasets.CIFAR10下载数据集的过程中,

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
 download=True, transform=transform)

报如下错误

Traceback (most recent call last):
  File "D:/pythonCode/pytorch/Learn_Torchvision/Leran_datasets.py", line 13, in 
    trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
  File "C:\Users\Administrator\miniconda3\lib\site-packages\torchvision\datasets\cifar.py", line 66, in __init__
    self.download()
  File "C:\Users\Administrator\miniconda3\lib\site-packages\torchvision\datasets\cifar.py", line 144, in download
    download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5)
  File "C:\Users\Administrator\miniconda3\lib\site-packages\torchvision\datasets\utils.py", line 427, in download_and_extract_archive
    download_url(url, download_root, filename, md5)
  File "C:\Users\Administrator\miniconda3\lib\site-packages\torchvision\datasets\utils.py", line 130, in download_url
    url = _get_redirect_url(url, max_hops=max_redirect_hops)
  File "C:\Users\Administrator\miniconda3\lib\site-packages\torchvision\datasets\utils.py", line 78, in _get_redirect_url
    with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as response:
  File "C:\Users\Administrator\miniconda3\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\Administrator\miniconda3\lib\urllib\request.py", line 525, in open
    response = self._open(req, data)
  File "C:\Users\Administrator\miniconda3\lib\urllib\request.py", line 542, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "C:\Users\Administrator\miniconda3\lib\urllib\request.py", line 502, in _call_chain
    result = func(*args)
  File "C:\Users\Administrator\miniconda3\lib\urllib\request.py", line 1393, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "C:\Users\Administrator\miniconda3\lib\urllib\request.py", line 1353, in do_open
    raise URLError(err)
urllib.error.URLError: 

原因分析:

通过调试定位到torch.utils.data.utils.py源文件_get_redirect_url函数中调用urllib.request.urlopen时出的问题。
Pytorch报urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED]错误_第1张图片
经过网上资料分析:这个错误是因为Python 2.7.9 之后引入了一个新特性,当使用urllib.urlopen一个 https 的时候会验证一次 SSL证书。当目标使用的是自签名的证书时就会报urllib.error.URLError错误。

解决方案:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
 download=True, transform=transform)

最后下载成功
在这里插入图片描述
在这里插入图片描述
Pytorch报urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED]错误_第2张图片

你可能感兴趣的:(Pytorch,pytorch)