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 <module>
    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: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123)>

原因分析:

通过调试定位到torch.utils.data.utils.py源文件_get_redirect_url函数中调用urllib.request.urlopen时出的问题。
在这里插入图片描述
经过网上资料分析:这个错误是因为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)

最后下载成功
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值